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/// How one field names its property.
84///
85/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
86/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
87/// is fixed when the class is created. Keeping the expression here instead made
88/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
89/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
90/// `{1: "a"}`.
91enum FieldKey<'a> {
92    /// `x`, `"x"`, `0` — the property name is static text.
93    Literal(&'a PropKey),
94    /// `#x`: the class-scope binding that holds the private symbol.
95    Private(String),
96    /// `[expr]`: the class-scope binding that holds the evaluated key.
97    Computed(String),
98}
99
100/// The `var_block` sentinel for a binding that lives at function scope.
101///
102/// It has to be a value a *real* block key can never take. Block keys are source
103/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
104/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
105/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
106/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
107/// sentinel takes the slot below it.
108const FUNCTION_SCOPE: u64 = u64::MAX - 3;
109
110/// The `var_block` sentinel for a binding of the parameter list.
111///
112/// A function whose parameter list contains a default expression gets *two* variable
113/// environments: one for the parameters and one for the body, so a `var` in the body
114/// that shares a name with a parameter is a different binding. The parameter bindings
115/// therefore need a scope key of their own: reachable while the defaults are
116/// evaluated, invisible to the body, and never merged with a body `var` of the same
117/// name.
118///
119/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
120/// the closure and the body shared one slot, when only the parameters were in scope
121/// when it was created.
122const PARAM_SCOPE: u64 = u64::MAX - 4;
123
124/// The name of the hidden local a `using` declaration caches its dispose method in.
125///
126/// It has to be a name no source can produce, because a script may declare anything: the
127/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
128fn using_method_name(name: &str) -> String {
129    format!("<using.method {name}>")
130}
131
132/// The `blocks` parent sentinel for "this block has no enclosing block".
133///
134/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
135/// also the terminator the chain walk from the script body reached the file's
136/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
137/// leaked into the body scope.
138const NO_PARENT: u64 = u64::MAX - 2;
139
140/// The block key for a script body. Distinct from both sentinels and unreachable from
141/// any source offset.
142const SCRIPT_BODY: u64 = u64::MAX - 1;
143
144/// An operand of a symbolic instruction.
145#[derive(Debug, Clone, PartialEq)]
146enum Op {
147    /// An immediate integer.
148    Int(i32),
149    /// A jump target.
150    Label(Label),
151    /// A constant pool index.
152    Const(u32),
153    /// An atom, before interning.
154    Atom(Atom),
155    /// An interned atom, as an index into [`Function::atoms`].
156    AtomId(u32),
157    /// A resolved slot.
158    Slot(Slot),
159}
160
161/// Where a resolved variable lives.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Slot {
164    Arg(u32),
165    Loc(u32),
166    VarRef(u32),
167    /// A global, by closure-var index.
168    Global(u32),
169    /// A global *declared* in this script. The reference keeps these bindings in
170    /// reference cells so that the script and any closure share one variable, so
171    /// a store goes through `put_var_ref` while a read uses `get_var`.
172    GlobalDecl(u32),
173}
174
175/// What a symbolic variable access does, which decides the final opcode.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum VarAction {
178    /// Read the value.
179    Get,
180    /// Read the value, yielding `undefined` for an undeclared global.
181    GetUndef,
182    /// Write, leaving nothing on the stack.
183    Put,
184    /// Write and initialise, leaving the value on the stack.
185    PutInit,
186    /// Write, leaving the value on the stack.
187    Set,
188    /// Initialise a binding that may only be initialised once, such as a derived
189    /// constructor's `this`.
190    PutInitChecked,
191    /// Initialise, leaving the value on the stack and without the `const` check.
192    ///
193    /// A class's own scope binding is a `const` that has to be initialised in the middle
194    /// of the definition — after the constructor exists but before the static fields run
195    /// — and the value has to survive for the outer store to use.
196    SetInit,
197    /// Write a binding that lives in a reference cell.
198    PutRef,
199}
200
201#[derive(Debug, Clone)]
202enum Insn {
203    /// A fully determined instruction.
204    Fixed { op: Opcode, operands: Vec<Op> },
205    /// A variable access, resolved in the second pass.
206    ///
207    /// `block` is the lexical block the access appears in, which is what makes
208    /// shadowing work: two bindings can share a name, and the one that wins is
209    /// whichever scope encloses the access.
210    Var {
211        action: VarAction,
212        name: String,
213        block: u64,
214        /// Whether the access was written in the parameter list; see
215        /// [`FnState::in_params`].
216        in_params: bool,
217    },
218    /// Close a binding *if* it turned out to be captured.
219    ///
220    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
221    /// only known once the body has been compiled — a closure created there is the
222    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
223    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
224    /// of emitted blind.
225    CloseCaptured { name: String, block: u64 },
226    /// `delete name`, which can only answer `false` once the binding is known.
227    ///
228    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
229    /// looks the name up on the global object, which is what distinguishes an implicit
230    /// global (configurable, deletable) from a declared one (a binding, always `false`).
231    DeleteVar { name: String },
232    /// An instruction that dead-code elimination removed. It keeps its slot so
233    /// that label indices stay valid, and resolves to no bytecode.
234    Dead,
235}
236
237/// Where `break` and `continue` jump to.
238///
239/// Targets are stacked as the compiler enters loops and labelled statements, so a
240/// bare `break` needs no analysis: it is simply the innermost target. A labelled
241/// one searches outward by name.
242#[derive(Debug, Clone)]
243struct JumpTarget {
244    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
245    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
246    /// same statement and `break a` must reach the same place as `break b`.
247    names: Vec<String>,
248    /// Where `break` lands. `None` for a construct `break` may only leave, not
249    /// target — a `try`, whose entry exists purely to unwind.
250    break_label: Option<Label>,
251    /// Where `continue` lands. `None` for anything that is not a loop.
252    continue_label: Option<Label>,
253    /// Stack slots to discard when control leaves this construct by a jump.
254    ///
255    /// Both `switch` and `try` leave something on the value stack for the duration
256    /// of the construct — the discriminant, or the `catch` offset — and a jump out
257    /// has to take it with it. A loop leaves nothing.
258    drop_count: u32,
259    /// The finalizer to run when control leaves this construct.
260    ///
261    /// Set on a `try` even when it has no `finally`: the label is always emitted and
262    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
263    /// does not have to know whether a finalizer exists.
264    finally_label: Option<Label>,
265    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
266    /// does not reach.
267    is_regular_stmt: bool,
268    /// Whether leaving this construct has to close an iterator.
269    ///
270    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
271    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
272    /// is dropped rather than closed.
273    has_iterator: bool,
274    /// Whether that iterator speaks the *async* protocol.
275    ///
276    /// An async close has to `await` the inner `return`, so it is an inline instruction
277    /// sequence rather than one opcode — the reference's `emit_iterator_close`.
278    is_async_iterator: bool,
279}
280
281/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
282///
283/// Both leave `source value` on the stack, so this is purely which spelling the reference
284/// picked, and it picked it by whether it had to build a *reference* for the target:
285///
286/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
287///   consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
288///   destructures);
289/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
290/// * a `var`, and any assignment target, go through `dup; get_field`, because the
291///   reference builds a reference for them — which is what `with` needs.
292fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
293    nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
294}
295
296/// Whether binding this pattern starts by boxing the value it was handed.
297fn nests_a_pattern(pattern: &Pattern) -> bool {
298    match &pattern.kind {
299        PatternKind::Array { .. } | PatternKind::Object { .. } => true,
300        PatternKind::Assign { target, .. } => nests_a_pattern(target),
301        _ => false,
302    }
303}
304
305/// `copy_data_properties` flags for an object-literal spread.
306///
307/// The byte packs three fields: the low bits are the stack offset of the source,
308/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
309/// as well as string keys. A spread passes a literal `null` exclusion list right
310/// below the source, so that field stays zero and only the source offset and the
311/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
312const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
313
314/// The expression a `...` introduces.
315///
316/// The parser marks the spread in two places — the element/property variant and an
317/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
318/// stepped through before the argument can be compiled.
319fn spread_argument(spread: &Expr) -> &Expr {
320    match &spread.kind {
321        ExprKind::Spread(inner) => inner,
322        _ => spread,
323    }
324}
325
326/// The flag byte `define_method` takes.
327///
328/// The low two bits pick value/getter/setter; bit 2 marks the property
329/// enumerable, which every object-literal method is.
330/// What kind of class constructor a function is being compiled as.
331///
332/// A constructor is not an ordinary method: a base one materialises `this` and refuses
333/// to run without `new`, and a derived one starts with `this` in the dead zone until
334/// `super()` produces it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum CtorKind {
337    /// Not a class constructor.
338    None,
339    /// A constructor of a class without `extends`.
340    Base,
341    /// A constructor of a class with `extends`.
342    Derived,
343}
344
345/// The flag byte `define_method` takes for a class member.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
348/// a class method is *not* — that is the whole difference from an object-literal method,
349/// and the reason `Object.keys(C.prototype)` stays empty.
350fn class_method_flags(kind: MethodKind) -> i32 {
351    match kind {
352        MethodKind::Constructor | MethodKind::Method => 0,
353        MethodKind::Get => 1,
354        MethodKind::Set => 2,
355    }
356}
357
358fn define_method_flags(kind: PropertyKind) -> i32 {
359    let base = match kind {
360        PropertyKind::Value | PropertyKind::Method => 0,
361        PropertyKind::Get => 1,
362        PropertyKind::Set => 2,
363    };
364    base | 4
365}
366
367/// Convert a numeric property key to the text an atom would be made from.
368///
369/// Only the range where Rust and JavaScript agree on the spelling is accepted.
370/// Both print the shortest representation that round-trips, so plain decimal
371/// digits match; they diverge at the extremes, where JavaScript switches to an
372/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
373/// differs from the reference, those keys are rejected.
374fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
375    if !value.is_finite() {
376        return Err(SyntaxError::new(
377            "a non-finite numeric property key is not supported by the compiler yet",
378            span,
379        ));
380    }
381    if value == value.trunc() && value.abs() < 1e21 {
382        return Ok(format!("{}", value as i64));
383    }
384    if value.abs() >= 1e-6 && value.abs() < 1e21 {
385        return Ok(format!("{value}"));
386    }
387    Err(SyntaxError::new(
388        "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
389        span,
390    ))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398    if let ExprKind::Logical {
399        op: inner_op,
400        left,
401        right,
402    } = &expr.kind
403        && *inner_op == op
404    {
405        collect_same_operator(op, left, out);
406        out.push(right);
407        return;
408    }
409    out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418    match op {
419        AssignOp::Or => Opcode::IfTrue,
420        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421        _ => Opcode::IfFalse,
422    }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428    /// `for (x in o)` — the keys of an object.
429    In,
430    /// `for (x of o)` — the values of an iterable.
431    Of,
432    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433    AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439    /// The guarded block.
440    Block = 0,
441    /// The handler body, excluding the catch parameter.
442    Catch = 1,
443    /// The finalizer block.
444    Finally = 2,
445    /// The catch parameter's own scope.
446    Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458    /// Source position of the block.
459    key: u64,
460    /// The block this one is nested in; `0` for the function scope.
461    parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466    /// The function's own source range, used to record its text for
467    /// `Function.prototype.toString`.
468    span: Option<(usize, usize)>,
469    name: String,
470    kind: FunctionKind,
471    strict: bool,
472    args: Vec<VarDef>,
473    vars: Vec<VarDef>,
474    closure_vars: Vec<ClosureVar>,
475    cpool: Vec<Constant>,
476    atoms: Vec<Atom>,
477    /// Every lexical scope, in creation order.
478    blocks: Vec<Block>,
479    /// The block currently being parsed or compiled.
480    current_block: u64,
481    /// The block a *nested* function was created in, so a capture made from here can be
482    /// resolved against the enclosing function's lexical scopes rather than against a
483    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484    /// function's own `let S` instead of the class body's `const S`.
485    created_in_block: u64,
486    /// The block each local was declared in, parallel to `vars`. `0` means the
487    /// function scope, where `var` bindings live.
488    var_block: Vec<u64>,
489    /// Set when the expression just compiled left no value on the stack.
490    ///
491    /// Only a store can do that: `put_field` consumes the object and the value, so
492    /// an assignment whose result is unused emits nothing extra. The expression
493    /// statement then has nothing to drop.
494    no_value: bool,
495    /// Whether a label was placed since the last instruction was emitted.
496    ///
497    /// The `put`/`get` fold is only valid when the two are adjacent in the final
498    /// stream; a label in between means a jump can land on the read, so the store has
499    /// to keep consuming its value. A flag is enough and avoids having to reason about
500    /// which index a label recorded.
501    label_since_insn: bool,
502    /// Whether the value of the expression being compiled is thrown away.
503    ///
504    /// Only an expression *statement* discards its value, and only the outermost
505    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507    /// the one construct whose bytecode depends on it.
508    discard_value: bool,
509    /// The block that holds the function body.
510    body_block: u64,
511    /// Head of each scope's binding chain, indexed by level. Filled in by
512    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513    block_heads: Vec<i32>,
514    /// Enclosing `break`/`continue` targets, innermost last.
515    jump_targets: Vec<JumpTarget>,
516    insns: Vec<Insn>,
517    labels: Vec<Option<usize>>,
518    /// Captured locals, which need a reference cell.
519    var_ref_count: u32,
520    line: u32,
521    column: u32,
522    /// Whether this is a script body. A script's top-level declarations create
523    /// global properties rather than locals, which is why they show up as
524    /// closure variables with `[global_decl]`.
525    is_script: bool,
526    /// Whether this is a module body.
527    ///
528    /// A module body is a script in every respect that matters here — no `arguments`,
529    /// no `this` of its own — but its top-level declarations are *module*-scoped
530    /// instead of global, which is what this flag changes.
531    is_module: bool,
532    /// Whether the function is an arrow, which never gets its own `arguments`.
533    is_arrow: bool,
534    /// The name a *named function expression* binds inside its own body.
535    /// How many parameters count towards `.length`.
536    defined_args: u32,
537    /// Parameters that are not a plain name, with the argument slot each came from.
538    param_prologue: Vec<(usize, Pattern)>,
539    /// What kind of class constructor this function is, if any.
540    ctor_kind: CtorKind,
541    /// Whether the class has instance fields, so the constructor has to run their
542    /// initialiser before it returns.
543    /// What the nested function about to be compiled should be told about its class.
544    class_ctor_pending: Option<CtorKind>,
545    /// Whether this function needs the hidden `this` local, because an arrow inside it
546    /// refers to `this`.
547    ///
548    /// An arrow has no `this` of its own, so the reference materialises the enclosing
549    /// function's receiver into a local and lets the arrow capture it as an ordinary
550    /// closure variable. Declaring the local is not enough on its own: the store that
551    /// fills it has to be prepended to the body, which is what this flag arranges.
552    needs_this_local: bool,
553    /// The same, for `arguments`.
554    needs_arguments_local: bool,
555    /// The same, for `new.target`.
556    needs_new_target_local: bool,
557    /// Whether the body already opens by filling a `this` local, which
558    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559    has_this_prologue: bool,
560    /// The same, for `<home_object>`: the object `super` resolves against.
561    ///
562    /// An arrow and a static block have no home object of their own — only the method or
563    /// initialiser they were written in does — so `super.x` inside one is a read of the
564    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565    /// by `special_object 4`, the same way `this` is.
566    needs_home_object_local: bool,
567    /// 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    /// Set while a with-guard is being emitted, so the guard's own accesses are not
586    /// wrapped in another guard.
587    emitting_with_guard: bool,
588    self_name: Option<String>,
589    /// Where the function body starts, in source order; see [`Function::body_start`].
590    body_start: (u32, u32),
591    /// Whether the body contains a *direct* `eval(...)` call.
592    ///
593    /// A direct eval sees every binding of the function that called it, including ones
594    /// no other code mentions. It also hands those bindings to any closure it creates,
595    /// which can outlive the function. Both need the bindings to live in cells, so this
596    /// flag makes the function treat all of them as captured.
597    has_direct_eval: bool,
598    /// Whether the parameter list contains a default expression, which is what gives
599    /// the function a second variable environment (see [`PARAM_SCOPE`]).
600    has_parameter_expressions: bool,
601    /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
602    simple_parameter_list: bool,
603    /// Whether the instructions being emitted belong to the parameter list.
604    ///
605    /// References made here must not see the body's `var`s: the body has not run yet,
606    /// and the reference's own model keeps the two scopes apart.
607    in_params: bool,
608    /// Whether an arrow created in this function's parameter list needs the parameter
609    /// scope's `arguments` binding.
610    needs_param_arguments: bool,
611    /// Whether this function was *created* inside a parameter list.
612    ///
613    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
614    /// arrow too. The name reference is the arrow's, but the scope it must not see
615    /// belongs to the function the arrow was born in.
616    created_in_params: bool,
617    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
618    ///
619    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
620    /// final while the body is still being compiled: a named function expression declares
621    /// its own name binding *after* the body, and that binding is exactly what
622    /// `eval("myfunc = 1")` has to find.
623    eval_sites: Vec<EvalSite>,
624    /// Direct `eval` call sites seen so far: where, and the block that was current.
625    pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
626    /// Whether this body contains `await`.
627    ///
628    /// For a *module* this decides whether its body is an async function: top-level
629    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
630    /// to survive to the compiled function rather than being a local of the compiler.
631    has_await: bool,
632    /// The module tables, when this body is a module.
633    ///
634    /// Only the top-level state ever has one: `export` and `import` are top-level
635    /// statements, so nothing nested can add to these tables.
636    module: Option<ModuleMeta>,
637    /// Whether the self-name prologue (`special_object 2` then the store) has been
638    /// emitted for this function.
639    ///
640    /// A *nested* function's lookup declares the binding early (see
641    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
642    /// prologue is still needed — the binding existing is not the same as it being
643    /// initialised.
644    self_name_initialized: bool,
645    /// Whether the code emitted so far leaves the program's result on the stack.
646    /// The reference tracks this for the hidden `<ret>` local of an eval script.
647    leaves_value: bool,
648    /// Statement nesting depth, used to tell top-level statements apart.
649    stmt_depth: u32,
650    /// Function declarations waiting to be instantiated at scope entry, as
651    /// (target slot, constant pool index). The reference emits these from
652    /// `instantiate_hoisted_definitions` rather than at the statement, because a
653    /// declaration is visible before it is reached.
654    hoisted: Vec<(u64, HoistTarget, u32)>,
655    /// Function declarations whose bodies are compiled only once the enclosing scope
656    /// has finished hoisting, as (owning block, declaration).
657    ///
658    /// Compiling a body at the declaration makes the result depend on source order: in
659    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
660    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
661    /// names first and the bodies second is what removes that dependence.
662    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
663    /// The source position of the node being compiled. Every instruction emitted
664    /// takes it, which is how the position table that feeds stack traces is built.
665    cur_pos: Option<Position>,
666    /// One position per entry in `insns`, index-aligned.
667    insn_pos: Vec<Option<Position>>,
668}
669
670/// Where a hoisted function declaration is stored.
671#[derive(Debug, Clone)]
672enum HoistTarget {
673    Arg(u32),
674    Loc(u32),
675    /// A global, which the resolver looks up by name.
676    Global(String),
677}
678
679impl FnState {
680    /// Whether this function suspends: a generator or an async function.
681    ///
682    /// A suspending function's `return` is a `return_async` and its body starts with an
683    /// `initial_yield`, so almost every statement that touches control flow asks this.
684    fn is_suspending(&self) -> bool {
685        self.kind.is_generator() || self.kind.is_async()
686    }
687
688    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
689        FnState {
690            span: None,
691            name: name.into(),
692            kind,
693            strict: false,
694            args: Vec::new(),
695            vars: Vec::new(),
696            closure_vars: Vec::new(),
697            cpool: Vec::new(),
698            atoms: Vec::new(),
699            blocks: Vec::new(),
700            current_block: 0,
701            created_in_block: NO_PARENT,
702            var_block: Vec::new(),
703            no_value: false,
704            label_since_insn: false,
705            discard_value: false,
706            body_block: 0,
707            block_heads: Vec::new(),
708            jump_targets: Vec::new(),
709            insns: Vec::new(),
710            labels: Vec::new(),
711            var_ref_count: 0,
712            line: 1,
713            column: 1,
714            is_script: false,
715            is_module: false,
716            is_arrow: false,
717            defined_args: 0,
718            param_prologue: Vec::new(),
719            ctor_kind: CtorKind::None,
720            class_ctor_pending: None,
721            needs_this_local: false,
722            needs_arguments_local: false,
723            needs_new_target_local: false,
724            has_this_prologue: false,
725            needs_home_object_local: false,
726            no_arguments_binding: false,
727            needs_active_func_local: false,
728            with_names: Vec::new(),
729            emitting_with_guard: false,
730            self_name: None,
731            has_direct_eval: false,
732            body_start: (0, 0),
733            has_parameter_expressions: false,
734            simple_parameter_list: true,
735            in_params: false,
736            needs_param_arguments: false,
737            created_in_params: false,
738            eval_sites: Vec::new(),
739            pending_eval_sites: Vec::new(),
740            has_await: false,
741            module: None,
742            self_name_initialized: false,
743            leaves_value: false,
744            stmt_depth: 0,
745            hoisted: Vec::new(),
746            deferred_funcs: Vec::new(),
747            cur_pos: None,
748            insn_pos: Vec::new(),
749        }
750    }
751
752    /// The scope a declaration lands in: a script's top-level declarations are
753    /// globals, everything else gets a slot.
754    /// Whether a binding declared *now* becomes a property of the global object.
755    ///
756    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
757    /// The `var` case is decided by the keyword rather than by the cursor position:
758    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
759    /// binding as a `var i` in the body, even though the head has its own block.
760    fn declares_globally(&self, def: &VarDef) -> bool {
761        // A module's top-level declarations are *module*-scoped: they live in the module
762        // record, never on the global object. Two modules can both declare `var x`
763        // without seeing each other, which is the whole point.
764        if self.is_module {
765            return false;
766        }
767        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
768    }
769}
770
771/// The compiler's entry point.
772pub struct Compiler {
773    /// The text being compiled, kept so each function can record its own slice for
774    /// `Function.prototype.toString`.
775    source: Option<String>,
776    module: bool,
777    /// Whether the program itself is the body of an `async` function.
778    ///
779    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
780    /// completion value is wrapped so a returned promise is not adopted.
781    async_body: bool,
782    /// Enclosing functions, outermost first. The last entry is the current one.
783    stack: Vec<FnState>,
784    /// The private names visible at this point, innermost class body last.
785    ///
786    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
787    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
788    /// all resolve against the same entries, and the parser accepts exactly that set
789    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
790    /// class's names the moment a method started.
791    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
792    /// Whether the expression [`Compiler::expr`] is about to compile is the one its
793    /// statement asked to discard.
794    ///
795    /// `FnState::discard_value` says "the statement's value is thrown away", which is only
796    /// ever true of the statement's own expression — an assignment nested inside it, as in
797    /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
798    /// keeping the answer here is what tells the two apart; without it the nested store
799    /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
800    /// function threw `undefined is not a function`.
801    discard_root: bool,
802}
803
804/// How a use site of a private name compiles.
805///
806/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
807/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
808/// of a setter-only accessor pair.
809#[derive(Clone, Copy, PartialEq, Eq)]
810enum PrivateKind {
811    /// `#x = 1`: an own property keyed by the symbol in the binding.
812    Field,
813    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
814    Method,
815    /// `get #a() {}`: the binding holds the getter, and a read calls it.
816    Getter,
817    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
818    /// the same `TypeError` as reading an uninitialised `const`.
819    Setter,
820}
821
822/// What the compiler knows about one `#name` where it is used.
823#[derive(Clone)]
824struct PrivateUse {
825    kind: PrivateKind,
826    /// `#a<set>` when the class defines a setter for this name.
827    ///
828    /// A second binding, not a second field of the first: the reference stores the setter
829    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
830    setter: Option<String>,
831}
832
833/// The class-scope bindings one class body needs, in declaration order.
834#[derive(Default)]
835struct ClassPlan {
836    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
837    /// at class entry, in member order.
838    bindings: Vec<String>,
839    /// The private names, for the use sites inside the body.
840    uses: std::collections::HashMap<String, PrivateUse>,
841    /// Computed field keys, by element index, so the emission pass does not have to redo the
842    /// per-half counter that names them.
843    computed: std::collections::HashMap<usize, String>,
844    /// Whether the instance initialiser has to add the brand to `this`.
845    instance_brand: bool,
846    /// Whether the constructor itself has to carry the brand.
847    static_brand: bool,
848}
849
850impl ClassPlan {
851    /// Walk a class body once and decide every class-scope binding it needs.
852    ///
853    /// Order is the reference's: a member's binding is created when the member is parsed, so
854    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
855    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
856    /// the disassembly stops matching even when every instruction is right.
857    fn build(class: &Class) -> ClassPlan {
858        let mut plan = ClassPlan::default();
859        let mut instance_keys = 0usize;
860        let mut static_keys = 0usize;
861        for (index, element) in class.elements.iter().enumerate() {
862            match element {
863                ClassElement::Method {
864                    key: PropName::Private(ident),
865                    kind,
866                    is_static,
867                    ..
868                } => {
869                    let name = format!("#{}", ident.name);
870                    let first = !plan.uses.contains_key(&name);
871                    if first {
872                        plan.bindings.push(name.clone());
873                        plan.uses.insert(
874                            name.clone(),
875                            PrivateUse {
876                                kind: match kind {
877                                    MethodKind::Get => PrivateKind::Getter,
878                                    MethodKind::Set => PrivateKind::Setter,
879                                    _ => PrivateKind::Method,
880                                },
881                                setter: None,
882                            },
883                        );
884                    }
885                    match kind {
886                        MethodKind::Set => {
887                            let binding = format!("{name}<set>");
888                            plan.bindings.push(binding.clone());
889                            if let Some(use_) = plan.uses.get_mut(&name) {
890                                use_.setter = Some(binding);
891                            }
892                        }
893                        // A getter is what makes the name readable, so a pair that started
894                        // as a setter becomes readable once the getter arrives.
895                        MethodKind::Get => {
896                            if let Some(use_) = plan.uses.get_mut(&name) {
897                                use_.kind = PrivateKind::Getter;
898                            }
899                        }
900                        _ => {}
901                    }
902                    if *is_static {
903                        plan.static_brand = true;
904                    } else {
905                        plan.instance_brand = true;
906                    }
907                }
908                ClassElement::Method {
909                    key: PropName::Computed(_),
910                    ..
911                } => {}
912                ClassElement::Method { .. } => {}
913                ClassElement::Field {
914                    key: PropName::Private(ident),
915                    ..
916                } => {
917                    let name = format!("#{}", ident.name);
918                    if !plan.uses.contains_key(&name) {
919                        plan.bindings.push(name.clone());
920                        plan.uses.insert(
921                            name,
922                            PrivateUse {
923                                kind: PrivateKind::Field,
924                                setter: None,
925                            },
926                        );
927                    }
928                }
929                ClassElement::Field {
930                    key: PropName::Computed(_),
931                    is_static,
932                    ..
933                } => {
934                    let index_in_half = if *is_static {
935                        static_keys += 1;
936                        static_keys - 1
937                    } else {
938                        instance_keys += 1;
939                        instance_keys - 1
940                    };
941                    let binding = computed_field_binding(index_in_half, *is_static);
942                    plan.bindings.push(binding.clone());
943                    plan.computed.insert(index, binding);
944                }
945                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
946            }
947        }
948        plan
949    }
950
951    /// How a private name used inside the body compiles, or `None` if no enclosing class
952    /// declares it.
953    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
954        compiler
955            .private_scopes
956            .iter()
957            .rev()
958            .find_map(|scope| scope.get(name))
959    }
960}
961
962impl Compiler {
963    /// The exact source text of a function, for `Function.prototype.toString`.
964    ///
965    /// §20.2.3.5 requires the *original* text: a function must stringify back to what
966    /// was written, comments and odd spacing included. Slicing the recorded span out of
967    /// the whole source is the only way to get that — rebuilding it from the AST would
968    /// normalise the text, and answering `[native code]` for a script function (which is
969    /// what this engine used to do) makes the result useless for feature detection and
970    /// for libraries that read their own source.
971    ///
972    /// Top-level bodies have no single expression span, so their `source` stays `None`
973    /// and `toString` falls back to the calling convention the spec allows.
974    fn function_source(
975        &self,
976        span: Option<(usize, usize)>,
977        line: u32,
978        column: u32,
979    ) -> Option<String> {
980        let source = self.source.as_ref()?;
981        let span = span?;
982        let bytes = source.as_bytes();
983        let start = span.0;
984        let end = span.1;
985        if start >= bytes.len() || end > bytes.len() || start >= end {
986            let _ = (line, column);
987            return None;
988        }
989        Some(source.get(start..end)?.to_string())
990    }
991}
992
993/// Compile a script.
994pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
995    Compiler::new(false).compile(program)
996}
997
998/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
999/// the original source.
1000///
1001/// The separate entry point rather than a parameter on [`compile_script`] because the
1002/// tests and the disassembler compile from an AST they built themselves and have no
1003/// source to give; they keep the `None` behaviour they already relied on.
1004pub fn compile_script_with_source(
1005    program: &Program,
1006    source: &str,
1007) -> Result<CompiledFunction, SyntaxError> {
1008    let mut compiler = Compiler::new(false);
1009    compiler.source = Some(source.to_string());
1010    compiler.compile(program)
1011}
1012
1013/// [`compile_script_with_source`] for a module.
1014pub fn compile_module_with_source(
1015    program: &Program,
1016    source: &str,
1017) -> Result<CompiledFunction, SyntaxError> {
1018    let mut compiler = Compiler::new(true);
1019    compiler.source = Some(source.to_string());
1020    compiler.compile(program)
1021}
1022
1023/// Compile a script whose top level is the body of an `async` function.
1024/// The body is an ordinary script in every other way — it still reports a completion value
1025/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1026/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1027/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1028/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1029/// documents.
1030pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1031    Compiler::for_suspensible_script().compile(program)
1032}
1033
1034/// Compile a module.
1035pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1036    Compiler::new(true).compile(program)
1037}
1038
1039/// Compile a direct `eval` body that inherits private names from its caller.
1040///
1041/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1042/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1043/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1044/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1045/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1046/// slot through the same `eval`-scope machinery every other inherited name uses.
1047///
1048/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1049/// body may `await`.
1050pub fn compile_eval_with_private(
1051    program: &Program,
1052    private: &[EvalPrivate],
1053    suspensible: bool,
1054) -> Result<CompiledFunction, SyntaxError> {
1055    let mut compiler = if suspensible {
1056        Compiler::for_suspensible_script()
1057    } else {
1058        Compiler::new(false)
1059    };
1060    if !private.is_empty() {
1061        let scope: std::collections::HashMap<String, PrivateUse> = private
1062            .iter()
1063            .map(|entry| {
1064                (
1065                    entry.name.clone(),
1066                    PrivateUse {
1067                        kind: match entry.kind {
1068                            EvalPrivateKind::Field => PrivateKind::Field,
1069                            EvalPrivateKind::Method => PrivateKind::Method,
1070                            EvalPrivateKind::Getter => PrivateKind::Getter,
1071                            EvalPrivateKind::Setter => PrivateKind::Setter,
1072                        },
1073                        setter: entry.setter.clone(),
1074                    },
1075                )
1076            })
1077            .collect();
1078        compiler.private_scopes.push(scope);
1079    }
1080    compiler.compile(program)
1081}
1082
1083impl Compiler {
1084    /// Create a compiler.
1085    pub fn new(module: bool) -> Compiler {
1086        Compiler {
1087            source: None,
1088            module,
1089            async_body: false,
1090            stack: Vec::new(),
1091            private_scopes: Vec::new(),
1092            discard_root: false,
1093        }
1094    }
1095
1096    /// Create a compiler for a script whose top level is an `async` function body.
1097    fn for_suspensible_script() -> Compiler {
1098        Compiler {
1099            source: None,
1100            module: false,
1101            async_body: true,
1102            stack: Vec::new(),
1103            private_scopes: Vec::new(),
1104            discard_root: false,
1105        }
1106    }
1107
1108    /// Compile a whole program into its top-level function.
1109    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1110        let mut state = FnState::new("<eval>", FunctionKind::Normal);
1111        // A module body is *not* a script: it has no completion value, so no hidden
1112        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1113        // is having no `arguments` of its own and no receiver — see `is_module`.
1114        state.is_script = !self.module;
1115        state.is_module = self.module;
1116        if self.module {
1117            state.module = Some(ModuleMeta::default());
1118        }
1119        state.strict = program.strict || self.module;
1120        state.line = program.span.start.line;
1121        state.column = program.span.start.column;
1122        // Locals are numbered in declaration order; `<ret>` is always slot 0.
1123        //
1124        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1125        // slot that only appears in one of the two arrays shifts every later
1126        // binding's block and silently loses the temporal-dead-zone marking for
1127        // the script's own blocks. A function frame has no `<ret>`, which is why
1128        // the misalignment only showed up at the top level.
1129        if !self.module {
1130            state.vars.push(VarDef::var("<ret>"));
1131            state.var_block.push(FUNCTION_SCOPE);
1132        }
1133        self.stack.push(state);
1134        // The body is its own scope, keyed by the position of the program.
1135        // The script body needs a key no statement can produce. Statement keys are
1136        // source offsets, and the program's own start offset is `0` — which is also
1137        // the offset of the first statement, so a top-level `{ let x }` or
1138        // `for (let i …)` used to share the body's block and lose its scope.
1139        let body_key = SCRIPT_BODY;
1140        self.push_block(body_key, NO_PARENT);
1141        self.state().body_block = body_key;
1142        // A module body opens with a re-entry guard. The host evaluates a module exactly
1143        // once, so the guard never fires in practice — but the reference emits it, and a
1144        // module function called a second time (through `eval` of its own source, say)
1145        // must not run its body again.
1146        let module_guard = self.module.then(|| self.new_label());
1147        if let Some(body) = module_guard {
1148            // The guard wraps the *hoisting* too: a second evaluation of the same module
1149            // body must not even re-create its function declarations.
1150            self.emit(Opcode::PushThis, &[]);
1151            self.emit_jump(Opcode::IfFalse, body, &[]);
1152        }
1153        self.hoist(&program.body, body_key)?;
1154        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1155        // come before the guard's `return_undef`: the reference's jump target sits past
1156        // both, and a second evaluation therefore re-creates nothing.
1157        self.emit_scope_enter(body_key);
1158        if let Some(body) = module_guard {
1159            self.emit(Opcode::ReturnUndef, &[]);
1160            self.place_label(body);
1161        }
1162        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1163        // eval'd body or a module gets its disposal epilogue like any other block.
1164        self.stmts(&program.body)?;
1165        if self.module {
1166            // A module has no completion value; its body simply ends.
1167            self.emit(Opcode::Undefined, &[]);
1168            self.emit(Opcode::ReturnAsync, &[]);
1169            // Top-level `await` makes the body an async function, so the host runs it as
1170            // a coroutine and waits. Without this the `await` opcode would suspend in a
1171            // body that nothing knows how to resume — which is what "a generator body ran
1172            // as an ordinary call" was reporting.
1173            if self.cur().has_await {
1174                self.state().kind = FunctionKind::Async;
1175            }
1176        } else if self.async_body {
1177            // An async body reports its completion value the same way, but through an
1178            // object: the function answers a promise, and resolving that promise *with*
1179            // the completion value would adopt a promise completion instead of reporting
1180            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1181            // resolve to `{value: <promise>}` rather than to `7`.
1182            //
1183            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1184            // value in an object so that promises can be safely returned").
1185            self.emit(Opcode::Object, &[]);
1186            self.emit(Opcode::Dup, &[]);
1187            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1188            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1189            self.emit(Opcode::Return, &[]);
1190            self.state().kind = FunctionKind::Async;
1191        } else {
1192            // The program's value is whatever the last expression statement stored in
1193            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1194            // case into a single `set_loc0`.
1195            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1196            self.emit(Opcode::Return, &[]);
1197        }
1198        Ok(self.finish_current())
1199    }
1200
1201    // -- emitting ----------------------------------------------------------
1202
1203    fn state(&mut self) -> &mut FnState {
1204        self.stack.last_mut().expect("a function is being compiled")
1205    }
1206
1207    fn cur(&self) -> &FnState {
1208        self.stack.last().expect("a function is being compiled")
1209    }
1210
1211    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1212        self.state().label_since_insn = false;
1213        let pos = self.cur().cur_pos;
1214        self.state().insns.push(Insn::Fixed {
1215            op,
1216            operands: operands.to_vec(),
1217        });
1218        self.state().insn_pos.push(pos);
1219    }
1220
1221    /// Reset the script's hidden return value to `undefined`.
1222    ///
1223    /// Called at the start of every statement that does not itself produce the
1224    /// program's value, which is how the reference keeps `if`/loop results from
1225    /// leaking into an eval result.
1226    fn reset_value(&mut self) {
1227        if !self.cur().is_script {
1228            return;
1229        }
1230        self.emit(Opcode::Undefined, &[]);
1231        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1232        self.state().leaves_value = false;
1233    }
1234
1235    /// Whether `name` is a local or argument slot rather than a global.
1236    fn is_slot(&self, name: &str) -> bool {
1237        self.cur().vars.iter().any(|v| v.name == name)
1238            || self.cur().args.iter().any(|a| a.name == name)
1239    }
1240
1241    /// `with (object) body`
1242    ///
1243    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1244    /// what makes the object reachable from a closure created inside the block, and it
1245    /// is also what lets an `eval` find it: the runtime collects the active `With`
1246    /// locals of every frame and resolves names against them before the realm.
1247    ///
1248    /// Inside the block every name reference is spelled as "look in the with objects
1249    /// first", innermost outwards, and falls through to the ordinary access. The test is
1250    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1251    /// Record asks.
1252    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1253        let name = self.next_with_name();
1254        // The object expression is evaluated *outside* the scope it introduces, so no
1255        // wrapper may be emitted for the names it mentions.
1256        let saved = std::mem::take(&mut self.state().with_names);
1257        self.expr(object)?;
1258        self.state().with_names = saved;
1259        self.emit(Opcode::ToObject, &[]);
1260        self.declare_hidden_local(&name, VarKind::With);
1261        // Pushed before the store so the store itself is not guarded by an *outer*
1262        // `with` — the object being stored is the new one, not something to look up.
1263        self.state().with_names.push(name.clone());
1264        self.emit_var(VarAction::Put, &name);
1265        let result = self.stmt(body);
1266        self.state().with_names.pop();
1267        result
1268    }
1269
1270    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1271    fn next_with_name(&self) -> String {
1272        let depth = self.cur().with_names.len();
1273        if depth == 0 {
1274            "<with>".to_string()
1275        } else {
1276            format!("<with{depth}>")
1277        }
1278    }
1279
1280    /// Declare a hidden local that must stay a *local* even in a script.
1281    ///
1282    /// A script's `var` is a property of the global object, but the `with` object is not
1283    /// part of the source program's name space at all — it only exists for the compiler
1284    /// and the runtime — so it goes straight into the frame's slot list.
1285    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1286        let state = self.state();
1287        if state.vars.iter().any(|v| v.name == name) {
1288            return;
1289        }
1290        state.var_block.push(FUNCTION_SCOPE);
1291        state.vars.push(VarDef {
1292            kind,
1293            ..VarDef::var(name)
1294        });
1295    }
1296
1297    /// Emit a name access, guarded by every active `with` object.
1298    ///
1299    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1300    /// the read itself; the outer guards and the plain access are what the `if_false`
1301    /// jumps to, so the innermost object wins.
1302    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1303        let names = self.cur().with_names.clone();
1304        let done = self.new_label();
1305        let mut starts = Vec::new();
1306        // Innermost object first: the last `with` opened is the one that shadows the
1307        // others, so its guard has to be the first chance to satisfy the name.
1308        for with_name in names.iter().rev() {
1309            let next = self.new_label();
1310            // `in` takes the key then the object.
1311            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1312            self.emit_var(VarAction::Get, with_name);
1313            self.emit(Opcode::In, &[]);
1314            self.emit_jump(Opcode::IfFalse, next, &[]);
1315            starts.push(next);
1316            match action {
1317                // A store keeps the value under the receiver, which is where
1318                // `put_field` expects it.
1319                VarAction::Put | VarAction::PutInit => {
1320                    self.emit_var(VarAction::Get, with_name);
1321                    self.emit(Opcode::Swap, &[]);
1322                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1323                }
1324                _ => {
1325                    self.emit_var(VarAction::Get, with_name);
1326                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1327                    self.emit(Opcode::GetArrayEl, &[]);
1328                }
1329            }
1330            self.emit_jump(Opcode::Goto, done, &[]);
1331            self.place_label(next);
1332        }
1333        self.emit_var(action, name);
1334        self.place_label(done);
1335    }
1336
1337    fn emit_var(&mut self, action: VarAction, name: &str) {
1338        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1339        // stores and keeps the value in one instruction. The reference does this
1340        // in a post-pass; folding it at emit time keeps instruction indices
1341        // stable, which matters because labels are recorded as indices.
1342        //
1343        // Only slots have a `set_` form: a global is stored with `put_var` and
1344        // read with `get_var`, and the reference does not fold those.
1345        //
1346        // A label between the two cancels the fold. `set_x v` leaves the value on
1347        // the stack, which is only equivalent when the read immediately follows the
1348        // store; when a jump target sits in between, the store must *consume* the
1349        // value and the read must fetch it afresh. A loop head is exactly that
1350        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1351        // condition re-reads it — and folding across the label would make the
1352        // condition compare whatever the previous iteration left on the stack.
1353        if action == VarAction::Get {
1354            let is_slot = self.is_slot(name);
1355            let at_label = std::mem::take(&mut self.state().label_since_insn);
1356            //
1357            // `arguments` is excluded because the reference treats it as a special
1358            // binding: it is initialised once and read many times, and folding its
1359            // initialisation into a `set_` would leave the object on the stack where
1360            // the reference leaves nothing.
1361            if is_slot
1362                && name != "arguments"
1363                && !at_label
1364                && let Some(Insn::Var {
1365                    action: previous,
1366                    name: previous_name,
1367                    ..
1368                }) = self.state().insns.last_mut()
1369                && *previous == VarAction::Put
1370                && previous_name == name
1371            {
1372                *previous = VarAction::Set;
1373                return;
1374            }
1375        }
1376        // Inside a `with`, every name lookup consults the with objects first. The
1377        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1378        let guarded = !self.cur().with_names.is_empty()
1379            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1380            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1381            && !self.state().emitting_with_guard;
1382        if guarded {
1383            self.state().emitting_with_guard = true;
1384            self.emit_with_guarded(action, name);
1385            self.state().emitting_with_guard = false;
1386            return;
1387        }
1388        let block = self.cur().current_block;
1389        self.state().label_since_insn = false;
1390        let pos = self.cur().cur_pos;
1391        let in_params = self.cur().in_params;
1392        self.state().insns.push(Insn::Var {
1393            action,
1394            name: name.to_string(),
1395            block,
1396            in_params,
1397        });
1398        self.state().insn_pos.push(pos);
1399    }
1400
1401    fn new_label(&mut self) -> Label {
1402        let state = self.state();
1403        state.labels.push(None);
1404        Label(state.labels.len() as u32 - 1)
1405    }
1406
1407    fn place_label(&mut self, label: Label) {
1408        let index = self.cur().insns.len();
1409        self.state().label_since_insn = true;
1410        self.state().labels[label.0 as usize] = Some(index);
1411    }
1412
1413    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1414        let mut operands = vec![Op::Label(label)];
1415        operands.extend_from_slice(extra);
1416        self.emit(op, &operands);
1417    }
1418
1419    // -- scopes ------------------------------------------------------------
1420
1421    /// Start a new lexical scope inside `parent`.
1422    fn push_block(&mut self, key: u64, parent: u64) {
1423        let state = self.state();
1424        if !state.blocks.iter().any(|b| b.key == key) {
1425            state.blocks.push(Block { key, parent });
1426        }
1427        state.current_block = key;
1428    }
1429
1430    /// Emit the code that runs when a lexical scope is entered.
1431    ///
1432    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1433    /// so entering its block marks it uninitialised. Hoisted function
1434    /// declarations are created here instead, which is why a call before the
1435    /// declaration still works.
1436    ///
1437    /// The order is not obvious: bindings are emitted in *reverse* declaration
1438    /// order, because the reference walks its scope chain, which is built by
1439    /// prepending.
1440    fn emit_scope_enter(&mut self, block: u64) {
1441        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1442        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1443        // so entering an outer scope threw away every nested block's function
1444        // declarations: `function h(){ { function k(){} } return k; }` answered
1445        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1446        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1447        // in a block is also a `var` of the enclosing function), and it is what makes the
1448        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1449        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1450        let mut rest = Vec::with_capacity(hoisted.len());
1451        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1452        for (owner, target, pool_index) in hoisted.drain(..) {
1453            if owner == block {
1454                mine.push((target, pool_index));
1455            } else {
1456                rest.push((owner, target, pool_index));
1457            }
1458        }
1459        self.state().hoisted = rest;
1460        mine.sort_by_key(|(target, _)| match target {
1461            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1462            HoistTarget::Global(_) => u32::MAX,
1463        });
1464        for (target, pool_index) in mine {
1465            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1466            match target {
1467                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1468                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1469                HoistTarget::Global(name) => {
1470                    // A global binding lives in a reference cell, so the store
1471                    // goes through `put_var_ref` while reads use `get_var`.
1472                    let block = self.cur().current_block;
1473                    let pos = self.cur().cur_pos;
1474                    let in_params = self.cur().in_params;
1475                    self.state().insns.push(Insn::Var {
1476                        action: VarAction::PutRef,
1477                        name,
1478                        block,
1479                        in_params,
1480                    });
1481                    self.state().insn_pos.push(pos);
1482                }
1483            }
1484        }
1485        for index in self.block_vars_reversed(block) {
1486            self.emit(
1487                Opcode::SetLocUninitialized,
1488                &[Op::Slot(Slot::Loc(index as u32))],
1489            );
1490        }
1491    }
1492
1493    /// Emit the code that runs when a lexical scope is exited.
1494    ///
1495    /// A captured binding has to be closed: detaching its reference cell freezes
1496    /// the value the binding had when the block ended, which is what a closure
1497    /// created inside the block must keep seeing.
1498    fn emit_scope_leave(&mut self, block: u64) {
1499        for index in self.block_vars_reversed(block) {
1500            if self.cur().vars[index].is_captured {
1501                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1502            }
1503        }
1504    }
1505
1506    /// Locals declared in `block`, in reverse declaration order.
1507    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1508        let state = self.cur();
1509        let mut out: Vec<usize> = (0..state.vars.len())
1510            .filter(|index| {
1511                state.var_block.get(*index).copied() == Some(block)
1512                    && state.vars[*index].is_lexical
1513                    // A derived constructor's `this` is lexical but is not initialised by
1514                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1515                    // was emitted with the constructor's own prologue.
1516                    && state.vars[*index].name != "this"
1517            })
1518            .collect();
1519        out.reverse();
1520        out
1521    }
1522
1523    /// Declare a local, even at the top level of a script.
1524    ///
1525    /// A `catch` parameter is always a local: the reference puts it in the
1526    /// function's own variable list (`1: catch e`), never in the global object,
1527    /// because it only exists while the handler runs.
1528    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1529        let state = self.state();
1530        let index = state.vars.len() as u32;
1531        // A `catch` parameter belongs to a scope even though it is not lexical: the
1532        // runtime instantiates it per handler entry, but it never sits in the
1533        // temporal dead zone.
1534        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1535            state.current_block
1536        } else {
1537            0
1538        };
1539        state.var_block.push(block);
1540        state.vars.push(def);
1541        index
1542    }
1543
1544    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1545        if self.cur().is_module
1546            && self.cur().current_block == self.cur().body_block
1547            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1548        {
1549            // Only the body's own block: a `let` inside a module-level `{}` is still an
1550            // ordinary local of that block, not a module variable.
1551            //
1552            // A `using` binding is excluded on purpose, and the reference excludes it in
1553            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1554            // "'using' variables are currently not exported in modules"): a module-level
1555            // `using` is an ordinary *local* of the module body function, not a module
1556            // cell. Two things follow, and both are what the reference does — `export {a}`
1557            // of a `using` binding is "exported variable 'a' does not exist", and
1558            // disposal works, because the disposal epilogue addresses locals by slot.
1559            //
1560            // The hidden dispose-method variable is excluded for a stronger reason: it is
1561            // *always* a local (`add_scope_var` in the reference), and it must sit
1562            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1563            return self.declare_module(name, &def);
1564        }
1565        if self.cur().declares_globally(&def) {
1566            self.declare_global(name, &def);
1567            return 0;
1568        }
1569        let state = self.state();
1570        let index = state.vars.len() as u32;
1571        let block = if def.is_lexical {
1572            state.current_block
1573        } else {
1574            0
1575        };
1576        state.var_block.push(block);
1577        state.vars.push(def);
1578        index
1579    }
1580
1581    /// Declare a `using` binding and its cached dispose method, returning both slots.
1582    ///
1583    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1584    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1585    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1586        let mut def = VarDef::lexical(name);
1587        def.kind = VarKind::Using;
1588        let value = self.declare(name, def);
1589        let mut method = VarDef::lexical(using_method_name(name));
1590        method.kind = VarKind::UsingMethod;
1591        let method_slot = self.declare(&using_method_name(name), method);
1592        (value, method_slot)
1593    }
1594
1595    /// The slot a `using` binding's dispose method lives in.
1596    fn using_method_slot(&self, name: &str) -> Option<u32> {
1597        let hidden = using_method_name(name);
1598        self.cur()
1599            .vars
1600            .iter()
1601            .position(|var| var.name == hidden)
1602            .map(|index| index as u32)
1603    }
1604
1605    // -- statements --------------------------------------------------------
1606
1607    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1608        self.stmt_labelled(stmt, &[])
1609    }
1610
1611    /// Compile a statement that a chain of labels names.
1612    ///
1613    /// Only a loop consumes `labels`; every other statement ignores them (the
1614    /// parser has already rejected a label on a statement that cannot use it).
1615    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1616        // Only a *top-level* expression statement supplies the program's value.
1617        let saved = self.cur().leaves_value;
1618        self.state().leaves_value =
1619            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1620        self.state().stmt_depth += 1;
1621        let result = self.stmt_inner(stmt, labels);
1622        self.state().stmt_depth -= 1;
1623        // A nested statement never contributes the program's value, so the flag
1624        // the wrapper set above is what survives.
1625        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1626        self.state().leaves_value = produced;
1627        let _ = saved;
1628        result
1629    }
1630
1631    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1632        match &stmt.kind {
1633            StmtKind::Empty | StmtKind::Debugger => {}
1634            StmtKind::Expr(expr) => {
1635                // The statement's first token is a position the reference records: an
1636                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1637                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1638                // is why an error from a construct with no position of its own (`[...it]`
1639                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1640                let saved = self.cur().cur_pos;
1641                self.state().cur_pos = Some(expr.span.start);
1642                // An expression statement's value is thrown away — except in a
1643                // script, where it becomes the program's result. `assign` reads this
1644                // and clears it, so a nested assignment still produces a value.
1645                self.state().discard_value = !self.cur().is_script;
1646                let result = self.expr(expr);
1647                self.state().discard_value = false;
1648                result?;
1649                if std::mem::take(&mut self.state().no_value) {
1650                    // A store whose value was discarded left nothing to drop.
1651                } else if self.cur().is_script {
1652                    // The program's value lands in the hidden `<ret>` local.
1653                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1654                } else {
1655                    self.emit(Opcode::Drop, &[]);
1656                }
1657                // Restored last: the trailing `drop` is part of the statement, and in the
1658                // reference it simply inherits whatever the expression last recorded.
1659                self.state().cur_pos = saved;
1660            }
1661            StmtKind::Block(body) => {
1662                // The block's declarations were hoisted with its enclosing
1663                // statement list, so there is nothing left to declare here.
1664                let key = stmt.span.start.offset as u64;
1665                let parent = self.cur().current_block;
1666                self.push_block(key, parent);
1667                self.emit_scope_enter(key);
1668                // A block is where a `using` region lives, so its statements have to go
1669                // through `stmts`: that is what emits the disposal epilogue.
1670                self.stmts(body)?;
1671                self.emit_scope_leave(key);
1672                self.state().current_block = parent;
1673            }
1674            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1675            // A function declaration was already instantiated when its scope was
1676            // entered, so the statement itself emits nothing.
1677            StmtKind::FuncDecl(_) => {}
1678            StmtKind::If { test, cons, alt } => {
1679                self.reset_value();
1680                let else_label = self.new_label();
1681                let end_label = self.new_label();
1682                self.expr(test)?;
1683                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1684                self.stmt(cons)?;
1685                if alt.is_some() {
1686                    self.emit_jump(Opcode::Goto, end_label, &[]);
1687                }
1688                self.place_label(else_label);
1689                if let Some(alt) = alt {
1690                    self.stmt(alt)?;
1691                    self.place_label(end_label);
1692                }
1693            }
1694            StmtKind::While { test, body } => {
1695                self.reset_value();
1696                let top = self.new_label();
1697                let end = self.new_label();
1698                self.place_label(top);
1699                self.expr(test)?;
1700                // The condition's false branch and `break` share one target,
1701                // which is why a `while` loop needs only one end label.
1702                self.emit_jump(Opcode::IfFalse, end, &[]);
1703                self.loop_body(body, labels, top, end)?;
1704                self.emit_jump(Opcode::Goto, top, &[]);
1705                self.place_label(end);
1706            }
1707            StmtKind::DoWhile { body, test } => {
1708                self.reset_value();
1709                let top = self.new_label();
1710                let cont = self.new_label();
1711                let end = self.new_label();
1712                self.place_label(top);
1713                // `continue` in a `do…while` runs the test, so it lands on `cont`
1714                // rather than on the loop head.
1715                self.loop_body(body, labels, cont, end)?;
1716                self.place_label(cont);
1717                self.expr(test)?;
1718                self.emit_jump(Opcode::IfTrue, top, &[]);
1719                self.place_label(end);
1720            }
1721            StmtKind::For {
1722                init,
1723                test,
1724                update,
1725                body,
1726            } => {
1727                self.reset_value();
1728                let for_key = stmt.span.start.offset as u64;
1729                let for_parent = self.cur().current_block;
1730                self.push_block(for_key, for_parent);
1731                self.emit_scope_enter(for_key);
1732                if let Some(init) = init {
1733                    match init {
1734                        ForInit::VarDecl(decl) => {
1735                            self.var_decl(decl)?;
1736                        }
1737                        ForInit::Expr(expr) => {
1738                            // The head's value is discarded. Saying so lets an
1739                            // assignment store with `put` instead of `dup`+`put`, which
1740                            // is what the reference emits — and the difference matters:
1741                            // a `dup`/`drop` pair around the store gives the peephole a
1742                            // chance to fold the store into the *condition's* read.
1743                            self.state().discard_value = true;
1744                            let result = self.expr(expr);
1745                            self.state().discard_value = false;
1746                            result?;
1747                            if !std::mem::take(&mut self.state().no_value) {
1748                                self.emit(Opcode::Drop, &[]);
1749                            }
1750                        }
1751                    }
1752                }
1753                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1754                // so a closure made in the body captures that iteration's value
1755                // instead of sharing one. The reference expresses this with
1756                // `close_loc`, which swaps in a new reference cell holding the
1757                // current value; the three points below are the ones it uses — after
1758                // the initialiser, before the update, and after the loop.
1759                let loop_bindings = match init {
1760                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1761                        let mut names: Vec<String> = Vec::new();
1762                        for declarator in &decl.declarators {
1763                            let mut idents = Vec::new();
1764                            declarator.target.bound_names(&mut idents);
1765                            names.extend(idents.into_iter().map(|ident| ident.name));
1766                        }
1767                        names
1768                    }
1769                    _ => Vec::new(),
1770                };
1771                // The reference also closes right after the initialiser, so the first
1772                // iteration's closures get their own cell rather than sharing the one
1773                // the initialiser wrote into.
1774                for name in &loop_bindings {
1775                    let pos = self.cur().cur_pos;
1776                    self.state().insns.push(Insn::CloseCaptured {
1777                        name: name.clone(),
1778                        block: for_key,
1779                    });
1780                    self.state().insn_pos.push(pos);
1781                }
1782                let top = self.new_label();
1783                let cont = self.new_label();
1784                let end = self.new_label();
1785                self.place_label(top);
1786                if let Some(test) = test {
1787                    self.expr(test)?;
1788                    self.emit_jump(Opcode::IfFalse, end, &[]);
1789                }
1790                // `continue` runs the update expression first, so it lands on
1791                // `cont`, which sits just before the update.
1792                self.loop_body(body, labels, cont, end)?;
1793                self.place_label(cont);
1794                // Each iteration ends with a fresh cell, so the closures the body just
1795                // created keep the cell they captured and the update writes to a new
1796                // one. Without this every closure in the loop shares one binding.
1797                let binding_block = for_key;
1798                for name in &loop_bindings {
1799                    let pos = self.cur().cur_pos;
1800                    self.state().insns.push(Insn::CloseCaptured {
1801                        name: name.clone(),
1802                        block: binding_block,
1803                    });
1804                    self.state().insn_pos.push(pos);
1805                }
1806                if let Some(update) = update {
1807                    self.state().discard_value = true;
1808                    let result = self.expr(update);
1809                    self.state().discard_value = false;
1810                    result?;
1811                    if !std::mem::take(&mut self.state().no_value) {
1812                        self.emit(Opcode::Drop, &[]);
1813                    }
1814                }
1815                self.emit_jump(Opcode::Goto, top, &[]);
1816                self.place_label(end);
1817                self.emit_scope_leave(for_key);
1818                self.state().current_block = for_parent;
1819            }
1820            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1821            StmtKind::Throw(expr) => {
1822                self.expr(expr)?;
1823                self.emit(Opcode::Throw, &[]);
1824            }
1825            StmtKind::Break(_) | StmtKind::Continue(_) => {
1826                // Labels and loops are wired up in a later milestone; a bare
1827                // break/continue jumps to the innermost enclosing target, which
1828                // the loop helpers register.
1829                self.control_transfer(stmt)?;
1830            }
1831            StmtKind::Labeled { label, body } => {
1832                self.labeled(label, body, stmt)?;
1833            }
1834            StmtKind::Switch {
1835                discriminant,
1836                cases,
1837            } => {
1838                self.switch(discriminant, cases, stmt)?;
1839            }
1840            StmtKind::Try {
1841                block,
1842                handler,
1843                finalizer,
1844            } => {
1845                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1846            }
1847            StmtKind::ForIn { left, right, body } => {
1848                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1849            }
1850            StmtKind::ForOf {
1851                left,
1852                right,
1853                body,
1854                is_await,
1855            } => {
1856                let kind = if *is_await {
1857                    ForLoopKind::AwaitOf
1858                } else {
1859                    ForLoopKind::Of
1860                };
1861                self.for_in_of(stmt, left, right, body, kind, labels)?;
1862            }
1863            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1864            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1865            // `import` emits nothing: hoisting already bound its names, and the host
1866            // fills their cells before the body runs.
1867            StmtKind::Import(_) => {}
1868            StmtKind::Export(decl) => self.export_stmt(decl)?,
1869        }
1870        Ok(())
1871    }
1872
1873    /// Compile `return`, running every enclosing finalizer on the way out.
1874    ///
1875    /// `nip_catch` is what makes this possible: it discards everything on the stack
1876    /// down to and including the `catch` offset while keeping the return value on
1877    /// top, so the frame the finalizer sees has the same shape as on the normal
1878    /// path.
1879    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1880        let mut has_value = value.is_some();
1881        if let Some(expr) = value {
1882            // `return f(x)` is a tail call *only* when nothing has to happen to the
1883            // value afterwards. A `finally` or an open iterator in scope forces the
1884            // normal path, because the cleanup has to run after the call returns —
1885            // which is exactly what a tail call refuses to do.
1886            let plain = self
1887                .cur()
1888                .jump_targets
1889                .iter()
1890                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1891            if plain && self.expr_if_tail_call(expr)? {
1892                // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
1893                // happen here as well.
1894                self.note_direct_eval(expr);
1895                return Ok(());
1896            }
1897            self.expr(expr)?;
1898        }
1899        // `return v` in an *async generator* awaits `v` before anything else happens —
1900        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1901        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1902        // exactly that reason ("the await must be done before handling the finally in case
1903        // it raises an exception").
1904        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1905            self.emit(Opcode::Await, &[]);
1906            self.state().has_await = true;
1907        }
1908        has_value = self.emit_unwind_for_return(has_value);
1909        // A generator or async function does not return to its caller: it either
1910        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1911        // `return_async` is the "finished" half, and it reads the value off the stack
1912        // rather than carrying it, which is what the resume machinery expects.
1913        if self.cur().is_suspending() {
1914            if !has_value {
1915                self.emit(Opcode::Undefined, &[]);
1916            }
1917            self.emit(Opcode::ReturnAsync, &[]);
1918            return Ok(());
1919        }
1920        if has_value {
1921            self.emit(Opcode::Return, &[]);
1922        } else {
1923            self.emit(Opcode::ReturnUndef, &[]);
1924        }
1925        Ok(())
1926    }
1927
1928    /// Close an iterator: the reference's `emit_iterator_close`.
1929    ///
1930    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1931    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1932    /// sequence, and three details in it are load-bearing:
1933    ///
1934    /// * the iterator object is compared against `undefined` first, because a loop that
1935    ///   ran to completion clears that slot rather than closing an exhausted iterator;
1936    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1937    /// * `preserve_completion` keeps whatever was underneath (the return value of the
1938    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
1939    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1940        if !is_async {
1941            if preserve_completion {
1942                self.emit(Opcode::Rot3r, &[]);
1943                self.emit(Opcode::Undefined, &[]);
1944            }
1945            self.emit(Opcode::IteratorClose, &[]);
1946            return;
1947        }
1948        if preserve_completion {
1949            // `iter next completion -> completion iter`
1950            self.emit(Opcode::Nip, &[]);
1951            self.emit(Opcode::Swap, &[]);
1952        } else {
1953            // `iter next catch_offset -> iter`
1954            self.emit(Opcode::Drop, &[]);
1955            self.emit(Opcode::Drop, &[]);
1956        }
1957        let done = self.new_label();
1958        let no_return = self.new_label();
1959        self.emit(Opcode::Dup, &[]);
1960        self.emit(Opcode::IsUndefined, &[]);
1961        self.emit_jump(Opcode::IfTrue, done, &[]);
1962        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1963        self.emit(Opcode::Dup, &[]);
1964        self.emit(Opcode::IsUndefinedOrNull, &[]);
1965        self.emit_jump(Opcode::IfTrue, no_return, &[]);
1966        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1967        self.emit(Opcode::Await, &[]);
1968        self.state().has_await = true;
1969        self.emit_jump(Opcode::Goto, done, &[]);
1970        self.place_label(no_return);
1971        self.emit(Opcode::Drop, &[]);
1972        self.place_label(done);
1973        self.emit(Opcode::Drop, &[]);
1974    }
1975
1976    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1977    /// return, and report whether a value is now on the stack for it to carry.
1978    ///
1979    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1980    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1981    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1982    /// running `finally` blocks the body was sitting inside.
1983    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1984        let targets = self.cur().jump_targets.clone();
1985        for target in targets.iter().rev() {
1986            if target.finally_label.is_none() && !target.has_iterator {
1987                continue;
1988            }
1989            if !has_value {
1990                // The cleanup expects a value to pass through; with nothing to
1991                // return, `undefined` stands in.
1992                self.emit(Opcode::Undefined, &[]);
1993                has_value = true;
1994            }
1995            self.emit(Opcode::NipCatch, &[]);
1996            if target.has_iterator {
1997                // Rewind to the loop's own slots and hand the close a dummy catch offset:
1998                // the loop is being abandoned, so there is nothing left to catch.
1999                self.emit_iterator_close(target.is_async_iterator, true);
2000            } else if let Some(finally) = target.finally_label {
2001                self.emit_jump(Opcode::Gosub, finally, &[]);
2002            }
2003        }
2004        has_value
2005    }
2006
2007    /// Compile a statement list, stopping at the first statement that cannot
2008    /// fall through.
2009    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2010        for (index, stmt) in body.iter().enumerate() {
2011            // A `using` declaration is not just a binding: everything after it, to the end
2012            // of the list, runs inside its disposal region. Compiling the rest of the list
2013            // recursively is what gives nested regions their innermost-first order.
2014            if Self::using_declaration(stmt).is_some() {
2015                return self.using_region(stmt, &body[index + 1..]);
2016            }
2017            self.stmt(stmt)?;
2018            if Self::terminates(stmt) {
2019                break;
2020            }
2021        }
2022        Ok(())
2023    }
2024
2025    /// The declaration a `using` statement carries, if it is one.
2026    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2027        match &stmt.kind {
2028            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2029            _ => None,
2030        }
2031    }
2032
2033    /// Compile `decl` and then the rest of its block, disposing when the block ends.
2034    ///
2035    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2036    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2037    /// exception — and this engine already funnels all of those through `catch` plus
2038    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2039    /// `return` and `break` dispose without knowing anything about `using`.
2040    ///
2041    /// ```text
2042    ///   <declaration>              value -> x, method -> x+1
2043    ///   catch CATCH                <- an exception in the rest lands here
2044    /// REST:
2045    ///   <the rest of the block>
2046    ///   drop                       <- the catch offset, on the fall-through path
2047    ///   undefined; gosub DISPOSE; drop
2048    ///   goto END
2049    /// CATCH:
2050    ///   using_dispose x            <- merges the failure into the pending exception
2051    ///   throw
2052    /// DISPOSE:
2053    ///   using_dispose_init
2054    ///   using_dispose x
2055    ///   using_dispose_end          <- rethrows if a dispose failed
2056    ///   ret
2057    /// END:
2058    /// ```
2059    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2060        let Some(decl) = Self::using_declaration(stmt) else {
2061            unreachable!("using_region is only called for a using declaration");
2062        };
2063        // `using` binds exactly one name and has no pattern form, which the parser
2064        // enforces; the region still has to know *which* slot to dispose.
2065        let name = decl
2066            .declarators
2067            .first()
2068            .and_then(|declarator| match &declarator.target.kind {
2069                PatternKind::Ident(ident) => Some(ident.name.clone()),
2070                _ => None,
2071            });
2072        self.stmt(stmt)?;
2073        let Some(name) = name else {
2074            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2075            // must not make the compiler panic.
2076            return self.stmts(rest);
2077        };
2078        let Some(value_slot) = self.using_value_slot(&name) else {
2079            // Declared globally, which the parser rules out for a script; a module's
2080            // top level is a scope, and there the disposal stays a known gap.
2081            return self.stmts(rest);
2082        };
2083        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2084        // exit path already disposed.
2085        let live = !rest.last().is_some_and(Self::terminates);
2086        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2087    }
2088
2089    /// The slot a `using` binding's value lives in.
2090    fn using_value_slot(&self, name: &str) -> Option<u32> {
2091        self.cur()
2092            .vars
2093            .iter()
2094            .position(|var| var.name == name && var.kind == VarKind::Using)
2095            .map(|index| index as u32)
2096    }
2097
2098    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2099    ///
2100    /// Shared between a `using` statement — which owns the rest of its block — and a
2101    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2102    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2103    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2104    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2105    /// target with a `finally_label` is what makes `return` and `break` dispose without
2106    /// knowing anything about `using`.
2107    ///
2108    /// ```text
2109    ///   catch CATCH                <- an exception inside lands here
2110    ///   <inside>
2111    ///   drop                       <- the catch offset, on the fall-through path
2112    ///   undefined; gosub DISPOSE; drop
2113    ///   goto END
2114    /// CATCH:
2115    ///   using_dispose slot         <- merges the failure into the pending exception
2116    ///   throw
2117    /// DISPOSE:
2118    ///   using_dispose_init
2119    ///   using_dispose slot
2120    ///   using_dispose_end          <- rethrows if a dispose failed
2121    ///   ret
2122    /// END:
2123    /// ```
2124    fn using_region_around(
2125        &mut self,
2126        value_slot: u32,
2127        live: bool,
2128        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2129    ) -> Result<(), SyntaxError> {
2130        let catch_label = self.new_label();
2131        let end_label = self.new_label();
2132        let dispose_label = self.new_label();
2133
2134        self.emit_jump(Opcode::Catch, catch_label, &[]);
2135        self.push_jump_target(JumpTarget {
2136            names: Vec::new(),
2137            break_label: None,
2138            continue_label: None,
2139            // The catch offset is the one thing on the stack that leaving has to remove.
2140            drop_count: 1,
2141            finally_label: Some(dispose_label),
2142            is_regular_stmt: false,
2143            has_iterator: false,
2144            is_async_iterator: false,
2145        });
2146        inside(self)?;
2147        self.pop_jump_target();
2148
2149        if live {
2150            self.emit(Opcode::Drop, &[]);
2151            self.emit(Opcode::Undefined, &[]);
2152            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2153            self.emit(Opcode::Drop, &[]);
2154            self.emit_jump(Opcode::Goto, end_label, &[]);
2155        }
2156
2157        // An exception unwinds to here with the thrown value on the stack, which is exactly
2158        // the shape `using_dispose` expects as its error state.
2159        self.place_label(catch_label);
2160        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2161        self.emit(Opcode::Throw, &[]);
2162
2163        self.place_label(dispose_label);
2164        // Inside the subroutine the return value and the `gosub` return address are both
2165        // live, and neither an outer finalizer nor another region may run before this one
2166        // has finished.
2167        self.push_jump_target(JumpTarget {
2168            names: Vec::new(),
2169            break_label: None,
2170            continue_label: None,
2171            drop_count: 2,
2172            finally_label: None,
2173            is_regular_stmt: false,
2174            has_iterator: false,
2175            is_async_iterator: false,
2176        });
2177        self.emit(Opcode::UsingDisposeInit, &[]);
2178        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2179        self.emit(Opcode::UsingDisposeEnd, &[]);
2180        self.pop_jump_target();
2181        self.emit(Opcode::Ret, &[]);
2182        self.place_label(end_label);
2183        Ok(())
2184    }
2185
2186    /// Declare every name a statement list introduces, before compiling any of
2187    /// it, so a reference that appears textually before a declaration still
2188    /// resolves.
2189    ///
2190    /// Declarations are walked in source order because that is the order the
2191    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2192    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2193    /// declarations hoist out to the function scope; lexical names belong to the
2194    /// block they were written in, which `block` records.
2195    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2196        let saved = self.cur().current_block;
2197        self.state().current_block = block;
2198        let result = self.hoist_list(body);
2199        // Only now is every binding of this scope known, so the deferred function
2200        // bodies can be compiled against the finished list. Compiled at its own
2201        // declaration instead, a body that names a `var` written further down would
2202        // have resolved that name as a global.
2203        if result.is_ok() {
2204            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2205            let mut outcome = Ok(());
2206            for (owner, func) in deferred {
2207                let previous = self.cur().current_block;
2208                self.state().current_block = owner;
2209                outcome = self.func_decl(&func);
2210                self.state().current_block = previous;
2211                if outcome.is_err() {
2212                    break;
2213                }
2214            }
2215            self.state().current_block = saved;
2216            return outcome;
2217        }
2218        // `current_block` is restored by the caller for a block statement, since
2219        // it needs it set while compiling; only clean up on the hoist path.
2220        self.state().current_block = saved;
2221        result
2222    }
2223
2224    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2225        for stmt in body {
2226            self.hoist_stmt(stmt)?;
2227        }
2228        Ok(())
2229    }
2230
2231    /// Whether a statement always transfers control away, making everything after
2232    /// it in the same list unreachable.
2233    ///
2234    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2235    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2236    fn terminates(stmt: &Stmt) -> bool {
2237        matches!(
2238            stmt.kind,
2239            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2240        )
2241    }
2242
2243    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2244        match &stmt.kind {
2245            StmtKind::VarDecl(decl) => {
2246                for declarator in &decl.declarators {
2247                    let mut names = Vec::new();
2248                    declarator.target.bound_names(&mut names);
2249                    for name in names {
2250                        let text = name.name.clone();
2251                        if decl.kind == VarDeclKind::Var {
2252                            let def = VarDef::var(text.clone());
2253                            self.declare_var(&text, def);
2254                        } else if decl.kind.is_using() {
2255                            // Two adjacent slots: the resource, then the dispose method
2256                            // snapshotted at declaration. `using_dispose` reads them as a
2257                            // pair `(slot, slot + 1)`, so nothing may be declared between
2258                            // them — which is why both are declared here, in one step,
2259                            // rather than the method being added at emission time.
2260                            self.declare_using(&text);
2261                        } else {
2262                            let def = if decl.kind == VarDeclKind::Const {
2263                                VarDef::constant(text.clone())
2264                            } else {
2265                                VarDef::lexical(text.clone())
2266                            };
2267                            self.declare(&text, def);
2268                        }
2269                    }
2270                }
2271            }
2272            StmtKind::FuncDecl(func) => {
2273                if let Some(name) = &func.name {
2274                    // A function declaration is a `var` binding that happens to
2275                    // hold a function, not a lexical one.
2276                    let def = VarDef::var(name.name.clone());
2277                    self.declare_var(&name.name.clone(), def);
2278                }
2279                // The function object is created when the scope is entered, so it
2280                // exists before the declaration is reached. Its body is compiled
2281                // *after* this scope's hoisting finishes, so a name it uses resolves
2282                // even when the `var` that declares it comes later in the source.
2283                let owner = self.cur().current_block;
2284                self.state().deferred_funcs.push((owner, func.clone()));
2285            }
2286            StmtKind::ClassDecl(class) => {
2287                if let Some(name) = &class.name {
2288                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2289                }
2290            }
2291            // A module's imports are bound before any of its code runs, and its exports
2292            // declare the very bindings they export — so both hoist the declarations
2293            // their `StmtKind` arm will later emit code for.
2294            StmtKind::Import(decl) => self.hoist_import(decl)?,
2295            StmtKind::Export(decl) => self.hoist_export(decl)?,
2296            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2297            StmtKind::If { cons, alt, .. } => {
2298                self.hoist_stmt(cons)?;
2299                if let Some(alt) = alt {
2300                    self.hoist_stmt(alt)?;
2301                }
2302            }
2303            StmtKind::While { body, .. }
2304            | StmtKind::DoWhile { body, .. }
2305            | StmtKind::Labeled { body, .. }
2306            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2307            StmtKind::For { init, body, .. } => {
2308                // A `for` head gets its own scope even when it declares nothing,
2309                // because `let` in the head is scoped to the loop.
2310                let key = stmt.span.start.offset as u64;
2311                let parent = self.cur().current_block;
2312                self.push_block(key, parent);
2313                if let Some(init) = init
2314                    && let ForInit::VarDecl(decl) = init
2315                {
2316                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2317                }
2318                self.hoist_stmt(body)?;
2319                self.state().current_block = parent;
2320            }
2321            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2322                let key = stmt.span.start.offset as u64;
2323                let parent = self.cur().current_block;
2324                self.push_block(key, parent);
2325                if let ForHead::VarDecl(decl) = left {
2326                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2327                }
2328                self.hoist_stmt(body)?;
2329                self.state().current_block = parent;
2330            }
2331            StmtKind::Try {
2332                block,
2333                handler,
2334                finalizer,
2335            } => {
2336                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2337                let try_parent = self.cur().current_block;
2338                if let Some(handler) = handler {
2339                    // The catch parameter belongs to the function scope, not to a
2340                    // block: it is a `catch` binding rather than a `let`, so it is
2341                    // never in the temporal dead zone and `emit_scope_enter` must
2342                    // not mark it uninitialised. It still has to be declared before
2343                    // the handler body is hoisted, so it takes the slot the
2344                    // reference gives it (bindings are numbered in source order).
2345                    if let Some(pattern) = &handler.param {
2346                        // The parameter gets its own scope, so entering the handler
2347                        // does not have to re-declare it. It is not lexical, so it
2348                        // is never marked uninitialised.
2349                        let key = Self::try_block_key(stmt, TryPart::Param);
2350                        let parent = self.cur().current_block;
2351                        self.push_block(key, parent);
2352                        // A destructuring parameter binds several names, one slot each,
2353                        // in the order they are written. The reference declares those as
2354                        // `let`s rather than as one `catch` binding — its dump prints
2355                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2356                        // so the kind follows the shape of the parameter.
2357                        //
2358                        // Neither form is in the dead zone: the stores run as the handler
2359                        // is entered, so both use the unchecked `put_loc`.
2360                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2361                        let mut names = Vec::new();
2362                        pattern.bound_names(&mut names);
2363                        for name in names {
2364                            let def = VarDef {
2365                                name: name.name.clone(),
2366                                is_const: false,
2367                                is_lexical: destructures,
2368                                kind: if destructures {
2369                                    crate::bytecode::VarKind::LexicalCatch
2370                                } else {
2371                                    crate::bytecode::VarKind::Catch
2372                                },
2373                                is_captured: false,
2374                                scope_level: 0,
2375                                scope_next: None,
2376                            };
2377                            self.declare_local(&name.name.clone(), def);
2378                        }
2379                        // The handler body nests inside the parameter's scope, so the
2380                        // body's bindings chain on to the parameter (the reference
2381                        // prints `let y [next:1]`, pointing at `e`).
2382                        self.state().current_block = key;
2383                    }
2384                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2385                    // Back to the block the `try` itself lives in, so the finalizer
2386                    // is a sibling of the handler rather than nested in it.
2387                    self.state().current_block = try_parent;
2388                }
2389                if let Some(finalizer) = finalizer {
2390                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2391                }
2392            }
2393            StmtKind::Switch { cases, .. } => {
2394                let key = stmt.span.start.offset as u64;
2395                let parent = self.cur().current_block;
2396                self.push_block(key, parent);
2397                for case in cases {
2398                    self.hoist_list(&case.body)?;
2399                }
2400                self.state().current_block = parent;
2401            }
2402            _ => {}
2403        }
2404        Ok(())
2405    }
2406
2407    /// Hoist a nested statement list, which is its own lexical scope.
2408    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2409        let parent = self.cur().current_block;
2410        self.push_block(key, parent);
2411        self.hoist_list(body)?;
2412        self.state().current_block = parent;
2413        Ok(())
2414    }
2415
2416    /// A block key for one part of a `try` statement.
2417    ///
2418    /// The three parts are three separate scopes, so they cannot share the key a
2419    /// statement's own offset would give them: the try block, the handler body and
2420    /// the finalizer would then look like one scope, and their `let` bindings would
2421    /// be marked uninitialised only on entering the first of them.
2422    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2423        (stmt.span.start.offset as u64) * 4 + part as u64
2424    }
2425
2426    /// Declare a `var`: it lives in the function's own scope, not the block's.
2427    fn declare_var(&mut self, name: &str, def: VarDef) {
2428        if self.cur().is_module {
2429            self.declare_module(name, &def);
2430            return;
2431        }
2432        if self.cur().declares_globally(&def) {
2433            self.declare_global(name, &def);
2434            return;
2435        }
2436        let state = self.state();
2437        // A binding of the *parameter* scope does not count: the body's `var` of the
2438        // same name is a different binding and needs a slot of its own.
2439        if state.vars.iter().enumerate().any(|(index, v)| {
2440            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2441        }) {
2442            return;
2443        }
2444        // A `var` belongs to the function scope, never to the enclosing block.
2445        state.var_block.push(FUNCTION_SCOPE);
2446        state.vars.push(def);
2447    }
2448
2449    /// Declare `name` as a binding of the parameter scope, returning its slot.
2450    fn declare_param_var(&mut self, name: &str) -> u32 {
2451        declare_param_var_at(self.state(), name)
2452    }
2453
2454    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2455    ///
2456    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2457    /// so each points at the one declared before it and the oldest ends the chain with
2458    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2459    /// runtime walks when it instantiates them.
2460    fn declare_param_binding(&mut self, name: &str) -> u32 {
2461        let state = self.state();
2462        let previous = state
2463            .vars
2464            .iter()
2465            .enumerate()
2466            .rev()
2467            .find(|(index, var)| {
2468                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2469            })
2470            .map(|(index, _)| index as i32);
2471        let index = state.vars.len() as u32;
2472        state.var_block.push(PARAM_SCOPE);
2473        let mut def = VarDef::lexical(name);
2474        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2475        // the function's, and its bindings are initialised one by one rather than all at
2476        // once — which is exactly what the dead zone needs.
2477        def.scope_level = 1;
2478        def.scope_next = Some(previous.unwrap_or(-2));
2479        state.vars.push(def);
2480        index
2481    }
2482
2483    /// The slot of a parameter-list binding, if the list has one by that name.
2484    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2485        let state = self.cur();
2486        state
2487            .vars
2488            .iter()
2489            .enumerate()
2490            .position(|(index, var)| {
2491                var.name == name
2492                    && var.is_lexical
2493                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2494            })
2495            .map(|index| index as u32)
2496    }
2497
2498    /// Every parameter-list binding, in declaration order.
2499    fn param_binding_names(&self) -> Vec<String> {
2500        let state = self.cur();
2501        state
2502            .vars
2503            .iter()
2504            .enumerate()
2505            .filter(|(index, var)| {
2506                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2507            })
2508            .map(|(_, var)| var.name.clone())
2509            .collect()
2510    }
2511
2512    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2513    fn body_var_slot(&self, name: &str) -> Option<u32> {
2514        let state = self.cur();
2515        state
2516            .vars
2517            .iter()
2518            .enumerate()
2519            .find(|(index, var)| {
2520                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2521            })
2522            .map(|(index, _)| index as u32)
2523    }
2524
2525    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2526    /// one.
2527    ///
2528    /// With parameter expressions the reference creates two: an unmapped one in the
2529    /// argument scope, for the defaults and anything they close over, and the body's own.
2530    /// They are separate bindings, which is what makes
2531    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2532    /// report 1 from `p` and 2 from the body.
2533    fn provide_param_arguments(&mut self) {
2534        if !self.cur().has_parameter_expressions {
2535            return;
2536        }
2537        let mentioned = self.cur().needs_param_arguments
2538            || self
2539                .cur()
2540                .insns
2541                .iter()
2542                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2543        if !mentioned {
2544            return;
2545        }
2546        let slot = self.declare_param_var("arguments");
2547        let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2548            0
2549        } else {
2550            1
2551        };
2552        self.prepend_initialiser_to(
2553            slot,
2554            Insn::Fixed {
2555                op: Opcode::SpecialObject,
2556                operands: vec![Op::Int(magic)],
2557            },
2558        );
2559    }
2560
2561    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2562    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2563        let current = self.stack.len() - 1;
2564        let init = [
2565            producer,
2566            Insn::Fixed {
2567                op: Opcode::PutLoc,
2568                operands: vec![Op::Slot(Slot::Loc(slot))],
2569            },
2570        ];
2571        let inserted = init.len();
2572        for (index, instruction) in init.into_iter().enumerate() {
2573            self.stack[current].insns.insert(index, instruction);
2574        }
2575        for placed in self.stack[current].labels.iter_mut().flatten() {
2576            *placed += inserted;
2577        }
2578        self.state().label_since_insn = false;
2579    }
2580
2581    /// Give the function an `arguments` binding if its body mentions one.
2582    ///
2583    /// The check runs on the *instruction* stream rather than the AST: by this point
2584    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2585    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2586    /// would renumber every later local slot and stop the bytecode matching the
2587    /// reference, which only adds the binding when the body uses it.
2588    ///
2589    /// `arguments` is a local, initialised at the top of the body by
2590    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2591    fn provide_arguments(&mut self) {
2592        let current = self.stack.len() - 1;
2593        if self.stack[current].is_script || self.stack[current].is_module {
2594            // A module has no `arguments` binding; referring to it is a ReferenceError,
2595            // which is exactly what an unbound name produces.
2596            return;
2597        }
2598        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2599        // function, which is why `() => arguments` sees the caller's arguments.
2600        if self.stack[current].is_arrow {
2601            if self.mentions("arguments") {
2602                self.ensure_enclosing_arguments();
2603            }
2604            return;
2605        }
2606        // Only a *body* mention needs the body's binding: the parameter list has one of
2607        // its own (see [`Compiler::provide_param_arguments`]).
2608        //
2609        // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2610        // `Var`, so without this the body got no binding at all — the name resolved to
2611        // the global object and `delete` answered `true` for a binding that cannot be
2612        // deleted. The reference answers `false`.
2613        let mentioned = self.cur().insns.iter().any(|insn| match insn {
2614            Insn::Var {
2615                name, in_params, ..
2616            } => name == "arguments" && !*in_params,
2617            Insn::DeleteVar { name } => name == "arguments",
2618            _ => false,
2619        });
2620        // A mention that resolves to the body's *own* lexical `arguments` is not a request
2621        // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2622        // implicit binding is not created at all. Providing it anyway was worse than useless:
2623        // its prologue store resolved past the shadowing `let` and landed on the **global**,
2624        // so `function f(p = eval("var arguments")) { let arguments; }` defined
2625        // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2626        // test262's `fn-body-cntns-arguments-lex-bind` family).
2627        //
2628        // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2629        // var *is* the binding, and the implicit arguments object is initialised into it at
2630        // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2631        // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2632        // `typeof arguments` `"undefined"`.
2633        if self
2634            .cur()
2635            .vars
2636            .iter()
2637            .any(|var| var.name == "arguments" && var.needs_check())
2638        {
2639            return;
2640        }
2641        if !mentioned && !self.cur().needs_arguments_local {
2642            return;
2643        }
2644        // The request may have come only from a parameter-list arrow, in which case the
2645        // parameter scope's binding already answers for it and the body needs none.
2646        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2647            return;
2648        }
2649        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2650        //
2651        // With parameter expressions the list and the body are separate environments, so
2652        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2653        // arguments object is unmapped whatever the mode, which is why the reference emits
2654        // `special_object 0` here even in sloppy code.
2655        // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2656        // object unmapped whatever the mode — §10.4.4 keys the decision on
2657        // `IsSimpleParameterList`, not on strictness alone.
2658        let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2659            0
2660        } else {
2661            1
2662        };
2663        // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2664        // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2665        // The only storage both sides can see is a reference cell, so every parameter the
2666        // object maps gets one — even a parameter no closure captured. Without this the
2667        // slot holds a plain copy and the mapping has nothing to write through.
2668        if magic == 1 {
2669            for arg in &mut self.stack[current].args {
2670                arg.is_captured = true;
2671            }
2672        }
2673        self.prepend_binding("arguments", magic);
2674    }
2675
2676    /// Whether a *body* instruction refers to `arguments`.
2677    fn body_mentions_arguments(&self) -> bool {
2678        self.cur()
2679            .insns
2680            .iter()
2681            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2682    }
2683
2684    /// Whether the function body's instruction stream refers to `name`.
2685    fn mentions(&self, name: &str) -> bool {
2686        let current = self.stack.len() - 1;
2687        // A binding of the parameter scope does not answer for the body: the body's own
2688        // `arguments` (or self-name) still has to be provided for it.
2689        if self.stack[current]
2690            .vars
2691            .iter()
2692            .enumerate()
2693            .any(|(index, v)| {
2694                v.name == name
2695                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2696            })
2697        {
2698            return false;
2699        }
2700        self.stack[current]
2701            .insns
2702            .iter()
2703            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2704    }
2705
2706    /// Bind the name a named function expression uses to refer to itself.
2707    ///
2708    /// The value is `special_object 2`, the function currently running, so the binding
2709    /// is the closure itself and not a copy. It is a local of this function, which is
2710    /// what keeps `g` out of the enclosing scope.
2711    /// Give the function a local `this`, for an arrow inside it to capture.
2712    fn provide_this_local(&mut self) {
2713        let current = self.stack.len() - 1;
2714        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2715            return;
2716        }
2717        if !self.stack[current]
2718            .vars
2719            .iter()
2720            .any(|var| var.name == "this")
2721        {
2722            self.declare_hidden_local("this", VarKind::Normal);
2723        }
2724        self.prepend_initialiser(
2725            "this",
2726            Insn::Fixed {
2727                op: Opcode::PushThis,
2728                operands: vec![],
2729            },
2730        );
2731    }
2732
2733    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2734    /// to read through `super`.
2735    fn provide_home_object_local(&mut self) {
2736        let current = self.stack.len() - 1;
2737        if !self.stack[current].needs_home_object_local {
2738            return;
2739        }
2740        if !self.stack[current]
2741            .vars
2742            .iter()
2743            .any(|var| var.name == HOME_OBJECT)
2744        {
2745            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2746        }
2747        self.prepend_initialiser(
2748            HOME_OBJECT,
2749            Insn::Fixed {
2750                op: Opcode::SpecialObject,
2751                operands: vec![Op::Int(4)],
2752            },
2753        );
2754    }
2755
2756    fn provide_self_name(&mut self) {
2757        let current = self.stack.len() - 1;
2758        let Some(name) = self.stack[current].self_name.clone() else {
2759            return;
2760        };
2761        if self.stack[current].self_name_initialized {
2762            return;
2763        }
2764        // Either the body refers to the name, or a nested function already forced the
2765        // binding into existence while being resolved. A direct `eval` can name it
2766        // without mentioning it, so its presence is a third reason: in strict mode
2767        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2768        // that only happens if the binding exists.
2769        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2770        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2771            return;
2772        }
2773        self.stack[current].self_name_initialized = true;
2774        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2775    }
2776
2777    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2778    ///
2779    /// Prepending shifts every label that has been placed, so they are all moved by
2780    /// the number of instructions inserted.
2781    fn prepend_binding(&mut self, name: &str, magic: i32) {
2782        self.prepend_binding_with(name, magic, VarKind::Normal);
2783    }
2784
2785    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2786    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2787        let current = self.stack.len() - 1;
2788        // A function-expression's own name is immutable in strict mode, which is what
2789        // makes `f = 1` inside a strict body throw instead of being dropped.
2790        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2791        self.declare_var(
2792            name,
2793            VarDef {
2794                kind,
2795                is_const,
2796                ..VarDef::var(name)
2797            },
2798        );
2799        let init = [
2800            Insn::Fixed {
2801                op: Opcode::SpecialObject,
2802                operands: vec![Op::Int(magic)],
2803            },
2804            Insn::Var {
2805                // An initialisation, not an assignment: sloppy mode drops stores to a
2806                // function-expression's own name, and the prologue is what puts the
2807                // value there in the first place.
2808                action: if kind == VarKind::FunctionName {
2809                    VarAction::PutInit
2810                } else {
2811                    VarAction::Put
2812                },
2813                name: name.to_string(),
2814                block: 0,
2815                in_params: false,
2816            },
2817        ];
2818        let inserted = init.len();
2819        for (index, instruction) in init.into_iter().enumerate() {
2820            self.stack[current].insns.insert(index, instruction);
2821        }
2822        for placed in self.stack[current].labels.iter_mut().flatten() {
2823            *placed += inserted;
2824        }
2825        // A store sits at the insertion point now, so the `put`/`get` fold must not
2826        // reach across it.
2827        self.stack[current].label_since_insn = true;
2828    }
2829
2830    /// Record a top-level script declaration as a global.
2831    ///
2832    /// A script's top-level `var`/`let`/`function` create properties of the
2833    /// global object, not slots in the script's frame, so they show up as closure
2834    /// variables instead.
2835    fn declare_global(&mut self, name: &str, def: &VarDef) {
2836        let state = self.state();
2837        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2838            // The name was already referenced, from a function compiled before this
2839            // declaration was reached — `function a(){ b() } function b(){}` resolves
2840            // `b` while `b` is still unknown, and that guess has to be corrected here.
2841            // Leaving it as a plain global meant the declaration was never registered,
2842            // so the binding did not exist at run time and `a()` threw
2843            // `b is not defined`.
2844            if matches!(existing.closure_type, ClosureType::Global) {
2845                existing.closure_type = ClosureType::GlobalDecl;
2846                existing.is_const = def.is_const;
2847                existing.is_lexical = def.is_lexical;
2848            }
2849            return;
2850        }
2851        state.closure_vars.push(ClosureVar {
2852            name: name.to_string(),
2853            is_const: def.is_const,
2854            is_lexical: def.is_lexical,
2855            closure_type: ClosureType::GlobalDecl,
2856            var_idx: 0,
2857        });
2858    }
2859
2860    /// Record a module-level declaration as a module variable.
2861    ///
2862    /// The binding is a closure variable of the module body, so reads and writes are
2863    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2864    /// *who fills the cell*: the module record does, before the body runs, and an import
2865    /// points its cell at the exporting module's, which is what makes bindings live and
2866    /// cycles work.
2867    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2868        let state = self.state();
2869        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2870            // The name may have been referenced before this declaration was hoisted,
2871            // which resolved it as a plain global. Correct that here, the way
2872            // `declare_global` does.
2873            if matches!(existing.closure_type, ClosureType::Global) {
2874                existing.closure_type = ClosureType::ModuleDecl;
2875                existing.is_const = def.is_const;
2876                existing.is_lexical = def.is_lexical;
2877            }
2878            return 0;
2879        }
2880        state.closure_vars.push(ClosureVar {
2881            name: name.to_string(),
2882            is_const: def.is_const,
2883            is_lexical: def.is_lexical,
2884            closure_type: ClosureType::ModuleDecl,
2885            var_idx: 0,
2886        });
2887        0
2888    }
2889
2890    /// Declare a module variable and answer its closure-variable index.
2891    ///
2892    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2893    /// module variable is not one. The import table needs the real index instead, because
2894    /// that is the position the host writes the cell into.
2895    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2896        self.declare_module(name, def);
2897        self.cur()
2898            .closure_vars
2899            .iter()
2900            .position(|c| c.name == name)
2901            .map(|index| index as u32)
2902            .unwrap_or(0)
2903    }
2904
2905    /// Declare one imported binding as a module variable.
2906    ///
2907    /// Returns the closure-variable index, which is what the import table records: the
2908    /// host writes the exporter's cell into that slot before the body runs.
2909    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2910        let state = self.state();
2911        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2912            // Keep the slot, fix the kind: the name may already have been referenced.
2913            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2914            state.closure_vars[index].is_const = is_const;
2915            return index as u32;
2916        }
2917        state.closure_vars.push(ClosureVar {
2918            name: name.to_string(),
2919            // An imported binding cannot be assigned: `x = 1` on an import is a
2920            // `TypeError` at run time, which the const flag is what produces.
2921            is_const: true,
2922            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2923            // the cell an import is in its dead zone, and reading it there must say so
2924            // rather than answer `undefined`.
2925            is_lexical: true,
2926            closure_type: ClosureType::ModuleImport,
2927            var_idx: 0,
2928        });
2929        state.closure_vars.len() as u32 - 1
2930    }
2931
2932    /// Emit the code an `export` needs.
2933    ///
2934    /// Only `export default <expr>` has any: everything else is a table entry whose
2935    /// binding is declared elsewhere. The expression is stored into the hidden
2936    /// `*default*` variable rather than returned, because the module body has no value
2937    /// to speak of.
2938    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2939        match &decl.kind {
2940            ExportKind::Declaration(stmt) => self.stmt(stmt),
2941            ExportKind::Default(expr) => {
2942                // `export default class Foo {}`: evaluate the declaration (which binds
2943                // `Foo`), then copy its value into the hidden `*default*` binding, because a
2944                // class declaration is a *statement* and `expr` cannot be compiled as one.
2945                if let ExprKind::Class(class) = &expr.kind
2946                    && class.name.is_some()
2947                {
2948                    self.stmt(&Stmt {
2949                        kind: StmtKind::ClassDecl(class.clone()),
2950                        span: expr.span,
2951                    })?;
2952                    let Some(name) = &class.name else {
2953                        return Ok(());
2954                    };
2955                    self.emit_var(VarAction::Get, &name.name);
2956                    let index = self.declare_export_default();
2957                    self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2958                    return Ok(());
2959                }
2960                // A named default function/class is already a module binding; the export
2961                // points at it and there is nothing to evaluate.
2962                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
2963                    return Ok(());
2964                }
2965                self.expr(expr)?;
2966                // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
2967                // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
2968                // name is observable — `imported.default.name` — and without this an
2969                // anonymous `export default class {}` arrived with the empty name.
2970                self.set_name_if_anonymous(expr, &Wtf8::new("default"));
2971                let index = self.declare_export_default();
2972                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2973                Ok(())
2974            }
2975            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2976        }
2977    }
2978
2979    /// A module name as the string it denotes.
2980    fn module_name_text(name: &ModuleName) -> &str {
2981        match name {
2982            ModuleName::Ident(ident) => &ident.name,
2983            ModuleName::Str(text) => text,
2984        }
2985    }
2986
2987    /// Bind `import`'s local names and record where each one comes from.
2988    ///
2989    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2990    /// binding's cell will be filled before the body runs. The cell lands in the module's
2991    /// environment at a fixed index, and the host fills it from the exporter's cell —
2992    /// which is why a cyclic import can bind before the other module has evaluated.
2993    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2994        let request = self.module_request(&decl.source, &decl.attributes);
2995        for specifier in &decl.specifiers {
2996            let (local, name, is_star) = match specifier {
2997                ImportSpecifier::Default(ident) => {
2998                    (ident.name.clone(), "default".to_string(), false)
2999                }
3000                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3001                ImportSpecifier::Named { imported, local } => (
3002                    local.name.clone(),
3003                    Self::module_name_text(imported).to_string(),
3004                    false,
3005                ),
3006            };
3007            // `import * as ns` is *not* a live binding of another module's variable —
3008            // it is a value of its own, which is why the reference declares it like a
3009            // module variable and the host stores the namespace object in that cell.
3010            let var_idx = if is_star {
3011                // `const`: a namespace object is a value, and the binding is immutable.
3012                self.declare_module_var(&local, &VarDef::constant(local.clone()))
3013            } else {
3014                self.declare_import(&local, true)
3015            };
3016            self.module_meta().imports.push(ImportEntry {
3017                module: request,
3018                name,
3019                var_idx,
3020                is_star,
3021            });
3022        }
3023        Ok(())
3024    }
3025
3026    /// Record what an `export` offers, declaring the binding it exports.
3027    ///
3028    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3029    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3030        match &decl.kind {
3031            ExportKind::Declaration(stmt) => {
3032                // The inner declaration keeps its own hoisting, then every name it binds
3033                // becomes an export of the same name.
3034                self.hoist_stmt(stmt)?;
3035                let mut names = Vec::new();
3036                Self::declared_names(stmt, &mut names);
3037                for name in names {
3038                    let var_idx = self.module_binding_index(&name);
3039                    self.exports_local(&name, var_idx);
3040                }
3041            }
3042            ExportKind::Default(expr) => {
3043                // The reference puts a default export in a hidden `*default*` variable,
3044                // so `export default function f(){}` can export a *value* while `f` stays
3045                // a binding of the module.
3046                if let ExprKind::Function(func) = &expr.kind
3047                    && let Some(name) = &func.name
3048                {
3049                    let text = name.name.clone();
3050                    self.hoist_stmt(&Stmt {
3051                        kind: StmtKind::FuncDecl(func.clone()),
3052                        span: expr.span,
3053                    })?;
3054                    let var_idx = self.module_binding_index(&text);
3055                    self.module_meta().exports.push(ExportEntry::Local {
3056                        export_name: "default".to_string(),
3057                        var_idx,
3058                    });
3059                    return Ok(());
3060                }
3061                if let ExprKind::Class(class) = &expr.kind
3062                    && class.name.is_some()
3063                {
3064                    // `export default class Foo {}` binds `Foo` in the module scope **and**
3065                    // stores the class into the hidden `*default*` binding — it is a
3066                    // declaration *and* a value, unlike `export default class {}` which is
3067                    // only a value.
3068                    //
3069                    // Pointing the `default` export straight at `Foo` looked simpler and was
3070                    // wrong twice over: `module_binding_index` did not find the lexical
3071                    // binding the hoist had just made, so it declared a second one that
3072                    // nothing ever wrote, and `export_stmt` then had no code to emit for the
3073                    // declaration either. `imported.default` came out `undefined` and `Foo`
3074                    // was not in scope inside its own module.
3075                    self.hoist_stmt(&Stmt {
3076                        kind: StmtKind::ClassDecl(class.clone()),
3077                        span: expr.span,
3078                    })?;
3079                    let var_idx = self.declare_export_default();
3080                    self.exports_local("default", var_idx);
3081                    return Ok(());
3082                }
3083                let var_idx = self.declare_export_default();
3084                self.module_meta().exports.push(ExportEntry::Local {
3085                    export_name: "default".to_string(),
3086                    var_idx,
3087                });
3088            }
3089            ExportKind::Named {
3090                specifiers,
3091                source,
3092                attributes,
3093            } => match source {
3094                Some(source) => {
3095                    let request = self.module_request(source, attributes);
3096                    for specifier in specifiers {
3097                        self.module_meta().exports.push(ExportEntry::Indirect {
3098                            export_name: Self::module_name_text(&specifier.exported).to_string(),
3099                            module: request,
3100                            import_name: Self::module_name_text(&specifier.local).to_string(),
3101                        });
3102                    }
3103                }
3104                None => {
3105                    for specifier in specifiers {
3106                        let local = Self::module_name_text(&specifier.local).to_string();
3107                        let export_name = Self::module_name_text(&specifier.exported).to_string();
3108                        // `export { x }` where `x` is itself an **import** re-exports the
3109                        // binding the import names, not a binding of this module
3110                        // (§16.2.1.6.3: a local export whose local name is imported resolves
3111                        // through the imported module). Recording it as a local made two
3112                        // modules that both forward one import look like two different
3113                        // bindings, and the name was reported ambiguous
3114                        // (`import-and-export-propagates-binding`;
3115                        // `namespace-unambiguous-if-import-star-as-and-export`).
3116                        let closure_names: Vec<String> = self
3117                            .cur()
3118                            .closure_vars
3119                            .iter()
3120                            .map(|var| var.name.clone())
3121                            .collect();
3122                        let forwarded = self
3123                            .module_meta()
3124                            .imports
3125                            .iter()
3126                            .filter(|entry| {
3127                                closure_names
3128                                    .get(entry.var_idx as usize)
3129                                    .is_some_and(|name| *name == local)
3130                            })
3131                            .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3132                            .find(|(_, name, is_star)| !is_star || name.is_empty());
3133                        if let Some((request, name, is_star)) = forwarded {
3134                            // A namespace import has no export *name* of its own; the
3135                            // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3136                            // which is what the marker below records.
3137                            let import_name = if is_star {
3138                                "*namespace*".to_string()
3139                            } else {
3140                                name
3141                            };
3142                            self.module_meta().exports.push(ExportEntry::Indirect {
3143                                export_name,
3144                                module: request,
3145                                import_name,
3146                            });
3147                            continue;
3148                        }
3149                        let var_idx = self.module_binding_index(&local);
3150                        self.module_meta().exports.push(ExportEntry::Local {
3151                            export_name,
3152                            var_idx,
3153                        });
3154                    }
3155                }
3156            },
3157            ExportKind::All {
3158                source,
3159                exported,
3160                attributes,
3161            } => {
3162                let request = self.module_request(source, attributes);
3163                match exported {
3164                    Some(name) => {
3165                        self.module_meta().exports.push(ExportEntry::StarAs {
3166                            export_name: Self::module_name_text(name).to_string(),
3167                            module: request,
3168                        });
3169                    }
3170                    None => {
3171                        self.module_meta()
3172                            .exports
3173                            .push(ExportEntry::Star { module: request });
3174                    }
3175                }
3176            }
3177        }
3178        Ok(())
3179    }
3180
3181    /// The names a declaration binds, which is what `export <decl>` exports.
3182    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3183        match &stmt.kind {
3184            StmtKind::VarDecl(decl) => {
3185                for declarator in &decl.declarators {
3186                    let mut names = Vec::new();
3187                    declarator.target.bound_names(&mut names);
3188                    out.extend(names.into_iter().map(|name| name.name));
3189                }
3190            }
3191            StmtKind::FuncDecl(func) => {
3192                if let Some(name) = &func.name {
3193                    out.push(name.name.clone());
3194                }
3195            }
3196            StmtKind::ClassDecl(class) => {
3197                if let Some(name) = &class.name {
3198                    out.push(name.name.clone());
3199                }
3200            }
3201            _ => {}
3202        }
3203    }
3204
3205    /// The closure-variable index of a module binding, declaring it if the name was
3206    /// exported without being declared here.
3207    ///
3208    /// `export { x }` where `x` is not declared in the module is a link-time
3209    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3210    fn module_binding_index(&mut self, name: &str) -> u32 {
3211        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3212            return index as u32;
3213        }
3214        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3215    }
3216
3217    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3218        self.module_meta().exports.push(ExportEntry::Local {
3219            export_name: export_name.to_string(),
3220            var_idx,
3221        });
3222    }
3223
3224    /// The hidden `*default*` binding `export default <expr>` stores into.
3225    fn declare_export_default(&mut self) -> u32 {
3226        const DEFAULT: &str = "*default*";
3227        if let Some(index) = self
3228            .cur()
3229            .closure_vars
3230            .iter()
3231            .position(|c| c.name == DEFAULT)
3232        {
3233            return index as u32;
3234        }
3235        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3236    }
3237
3238    /// The module tables, which only the top-level state has.
3239    fn module_meta(&mut self) -> &mut ModuleMeta {
3240        self.state()
3241            .module
3242            .as_mut()
3243            .expect("module tables are only touched while compiling a module")
3244    }
3245
3246    /// The index of `specifier`'s request, adding it if it is new.
3247    ///
3248    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3249    /// JSON and once as text is two modules with two different contents, which is exactly
3250    /// what `hello_module.js` does.
3251    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3252        let attributes: Vec<(String, String)> = attributes
3253            .iter()
3254            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3255            .collect();
3256        let meta = self.module_meta();
3257        if let Some(index) = meta
3258            .requests
3259            .iter()
3260            .position(|request| request.specifier == specifier && request.attributes == attributes)
3261        {
3262            return index as u32;
3263        }
3264        meta.requests.push(ModuleRequest {
3265            specifier: specifier.to_string(),
3266            attributes,
3267        });
3268        meta.requests.len() as u32 - 1
3269    }
3270
3271    /// Compile a loop body with a `break`/`continue` target pushed for it.
3272    fn loop_body(
3273        &mut self,
3274        body: &Stmt,
3275        labels: &[String],
3276        continue_label: Label,
3277        break_label: Label,
3278    ) -> Result<(), SyntaxError> {
3279        self.push_jump_target(JumpTarget {
3280            names: labels.to_vec(),
3281            break_label: Some(break_label),
3282            continue_label: Some(continue_label),
3283            // A loop leaves nothing of its own on the value stack.
3284            drop_count: 0,
3285            finally_label: None,
3286            is_regular_stmt: false,
3287            has_iterator: false,
3288            is_async_iterator: false,
3289        });
3290        let result = self.stmt(body);
3291        self.pop_jump_target();
3292        result
3293    }
3294
3295    fn push_jump_target(&mut self, target: JumpTarget) {
3296        self.state().jump_targets.push(target);
3297    }
3298
3299    fn pop_jump_target(&mut self) {
3300        self.state().jump_targets.pop();
3301    }
3302
3303    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3304        let (label, is_break) = match &stmt.kind {
3305            StmtKind::Break(label) => (label.as_ref(), true),
3306            StmtKind::Continue(label) => (label.as_ref(), false),
3307            _ => unreachable!("control_transfer is only called for break and continue"),
3308        };
3309
3310        // Walk outward from the innermost construct. Everything considered before
3311        // the match is a construct control is leaving, and leaving it has a cost:
3312        // its stack slots go, and its finalizer runs.
3313        let targets = self.cur().jump_targets.clone();
3314        for target in targets.iter().rev() {
3315            let destination = match (label, is_break) {
3316                // An unlabelled `break` skips a labelled non-loop statement: `break`
3317                // may name one, but the bare form only means "leave the loop".
3318                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3319                (None, false) => target.continue_label,
3320                (Some(name), true) => target
3321                    .break_label
3322                    .filter(|_| target.names.contains(&name.name)),
3323                (Some(name), false) => target
3324                    .continue_label
3325                    .filter(|_| target.names.contains(&name.name)),
3326            };
3327
3328            if let Some(destination) = destination {
3329                self.emit_jump(Opcode::Goto, destination, &[]);
3330                return Ok(());
3331            }
3332
3333            // Closing the iterator consumes the three slots the loop keeps on the
3334            // stack (iterator, next method, catch offset), so those are not dropped
3335            // again below.
3336            let mut remaining = target.drop_count;
3337            if target.has_iterator {
3338                self.emit_iterator_close(target.is_async_iterator, false);
3339                remaining = remaining.saturating_sub(3);
3340            }
3341            for _ in 0..remaining {
3342                self.emit(Opcode::Drop, &[]);
3343            }
3344            if let Some(finally) = target.finally_label {
3345                // The finalizer runs as a subroutine and is handed a dummy return
3346                // value, which is dropped afterwards to keep the stack the depth it
3347                // had before.
3348                self.emit(Opcode::Undefined, &[]);
3349                self.emit_jump(Opcode::Gosub, finally, &[]);
3350                self.emit(Opcode::Drop, &[]);
3351            }
3352        }
3353
3354        // The parser rejects a break/continue with no target, so reaching here
3355        // means the compiler's own bookkeeping is wrong.
3356        Err(SyntaxError::new(
3357            if is_break {
3358                "break has no enclosing loop or switch"
3359            } else {
3360                "continue has no enclosing loop"
3361            },
3362            stmt.span,
3363        ))
3364    }
3365
3366    /// Compile a labelled statement.
3367    ///
3368    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3369    /// that loop's targets, so the chain is collected and handed to the loop. A
3370    /// label on a non-loop statement only provides a `break` target, because
3371    /// `continue` may not target it.
3372    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3373        let mut names = vec![label.name.clone()];
3374        let mut inner = body;
3375        while let StmtKind::Labeled {
3376            label: next,
3377            body: deeper,
3378        } = &inner.kind
3379        {
3380            names.push(next.name.clone());
3381            inner = deeper;
3382        }
3383        if Self::is_loop(inner) {
3384            return self.stmt_labelled(inner, &names);
3385        }
3386        let end = self.new_label();
3387        self.push_jump_target(JumpTarget {
3388            names,
3389            break_label: Some(end),
3390            continue_label: None,
3391            drop_count: 0,
3392            finally_label: None,
3393            is_regular_stmt: true,
3394            has_iterator: false,
3395            is_async_iterator: false,
3396        });
3397        let result = self.stmt(inner);
3398        self.pop_jump_target();
3399        result?;
3400        self.place_label(end);
3401        let _ = stmt;
3402        Ok(())
3403    }
3404
3405    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3406    fn is_loop(stmt: &Stmt) -> bool {
3407        matches!(
3408            stmt.kind,
3409            StmtKind::While { .. }
3410                | StmtKind::DoWhile { .. }
3411                | StmtKind::For { .. }
3412                | StmtKind::ForIn { .. }
3413                | StmtKind::ForOf { .. }
3414        )
3415    }
3416
3417    /// Compile `switch`.
3418    ///
3419    /// The discriminant is evaluated once and stays on the value stack while the
3420    /// clauses compare against copies of it, so it is dropped at the end — which is
3421    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3422    /// clause's body jumps over the *next* clause's tests straight into its body.
3423    ///
3424    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3425    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3426    /// the end of the switch when there is no `default`. That failure path can point
3427    /// backwards (`default` written first), so the runs and their labels are worked
3428    /// out before any code is emitted.
3429    fn switch(
3430        &mut self,
3431        discriminant: &Expr,
3432        cases: &[SwitchCase],
3433        stmt: &Stmt,
3434    ) -> Result<(), SyntaxError> {
3435        self.reset_value();
3436        // The discriminant is evaluated outside the switch's block scope, before
3437        // any `case` clause exists.
3438        self.expr(discriminant)?;
3439
3440        let switch_key = stmt.span.start.offset as u64;
3441        let switch_parent = self.cur().current_block;
3442        self.push_block(switch_key, switch_parent);
3443        self.emit_scope_enter(switch_key);
3444
3445        let break_label = self.new_label();
3446        self.push_jump_target(JumpTarget {
3447            names: Vec::new(),
3448            break_label: Some(break_label),
3449            // `switch` is a valid `break` target but not a `continue` target.
3450            continue_label: None,
3451            // The discriminant stays on the value stack for the whole statement, so
3452            // a `break` aimed further out has to discard it.
3453            drop_count: 1,
3454            finally_label: None,
3455            is_regular_stmt: false,
3456            has_iterator: false,
3457            is_async_iterator: false,
3458        });
3459
3460        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3461        // its label to the clause after it, so both tests reach the same body.
3462        let mut runs: Vec<(usize, usize)> = Vec::new();
3463        let mut scan = 0;
3464        while scan < cases.len() {
3465            if cases[scan].test.is_some() {
3466                let mut last = scan;
3467                while last + 1 < cases.len()
3468                    && cases[last].test.is_some()
3469                    && cases[last].body.is_empty()
3470                    && cases[last + 1].test.is_some()
3471                {
3472                    last += 1;
3473                }
3474                runs.push((scan, last));
3475                scan = last + 1;
3476            } else {
3477                scan += 1;
3478            }
3479        }
3480
3481        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3482        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3483        let default_at = cases.iter().position(|case| case.test.is_none());
3484        // Where the last run sends control when nothing matched.
3485        let miss_target = match default_at {
3486            Some(index) => body_labels[index],
3487            None => break_label,
3488        };
3489
3490        // When `default` comes first, control has to jump over it to reach the
3491        // tests. It only needs to when some clause actually has a test; otherwise
3492        // the default body is the entry point.
3493        let mut entry = None;
3494        if default_at == Some(0) && !runs.is_empty() {
3495            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3496            entry = Some(run_labels[0]);
3497        }
3498
3499        let mut index = 0;
3500        let mut run = 0;
3501        let result = (|| -> Result<(), SyntaxError> {
3502            while index < cases.len() {
3503                if cases[index].test.is_some() {
3504                    let (first, last) = runs[run];
3505                    // Reaching these tests from the preceding body is a
3506                    // fallthrough, which continues inside the body and skips them.
3507                    if index > 0 {
3508                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3509                    }
3510                    if let Some(label) = entry.take() {
3511                        self.place_label(label);
3512                    }
3513                    self.place_label(run_labels[run]);
3514
3515                    for (offset, case) in cases[first..=last].iter().enumerate() {
3516                        let test = case.test.as_ref().unwrap();
3517                        self.emit(Opcode::Dup, &[]);
3518                        self.expr(test)?;
3519                        self.emit(Opcode::StrictEq, &[]);
3520                        if first + offset < last {
3521                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3522                        } else {
3523                            // Hand over to the next run's tests, or give up.
3524                            let next = match runs.get(run + 1) {
3525                                Some(_) => run_labels[run + 1],
3526                                None => miss_target,
3527                            };
3528                            self.emit_jump(Opcode::IfFalse, next, &[]);
3529                        }
3530                    }
3531
3532                    self.place_label(body_labels[index]);
3533                    for case in &cases[first..=last] {
3534                        self.stmts(&case.body)?;
3535                    }
3536                    index = last + 1;
3537                    run += 1;
3538                } else {
3539                    // `default`: control arrives here either by falling through or
3540                    // because every test missed.
3541                    self.place_label(body_labels[index]);
3542                    self.stmts(&cases[index].body)?;
3543                    index += 1;
3544                }
3545            }
3546            Ok(())
3547        })();
3548
3549        if result.is_ok() {
3550            self.place_label(break_label);
3551            // Discard the discriminant now that no test needs it.
3552            self.emit(Opcode::Drop, &[]);
3553        }
3554
3555        self.pop_jump_target();
3556        self.emit_scope_leave(switch_key);
3557        self.state().current_block = switch_parent;
3558        result
3559    }
3560
3561    /// Compile `try`/`catch`/`finally`.
3562    ///
3563    /// The shape is an exception table built out of `catch` instructions, each of
3564    /// which records where control goes if the instructions that follow raise:
3565    ///
3566    /// ```text
3567    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3568    ///   <guarded block>
3569    ///   drop                   <- discard the catch offset
3570    ///   undefined; gosub FINALLY; drop
3571    ///   goto END
3572    /// HANDLER:
3573    ///   <bind the catch parameter>
3574    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3575    ///   <handler body>
3576    ///   drop; undefined; gosub FINALLY; drop; goto END
3577    /// CATCH2:
3578    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3579    /// FINALLY:
3580    ///   <finalizer>
3581    ///   ret                    <- return to the `gosub`
3582    /// END:
3583    /// ```
3584    ///
3585    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3586    /// of the finalizer serves the normal path, the handler path and the
3587    /// propagating-exception path.
3588    ///
3589    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3590    /// runs with `ret_value` on the stack, and the normal path has no value to
3591    /// keep, so it pushes one to keep the stack depth identical on every path.
3592    fn try_stmt(
3593        &mut self,
3594        stmt: &Stmt,
3595        block: &[Stmt],
3596        handler: &Option<CatchClause>,
3597        finalizer: Option<&[Stmt]>,
3598    ) -> Result<(), SyntaxError> {
3599        self.reset_value();
3600
3601        let catch_label = self.new_label();
3602        let catch2_label = self.new_label();
3603        let finally_label = self.new_label();
3604        let end_label = self.new_label();
3605
3606        self.emit_jump(Opcode::Catch, catch_label, &[]);
3607
3608        // The guarded block. `break` may not target it, so its entry exists purely
3609        // to unwind: a jump out has to discard the catch offset and run the
3610        // finalizer.
3611        self.push_jump_target(JumpTarget {
3612            names: Vec::new(),
3613            break_label: None,
3614            continue_label: None,
3615            drop_count: 1,
3616            finally_label: Some(finally_label),
3617            is_regular_stmt: false,
3618            has_iterator: false,
3619            is_async_iterator: false,
3620        });
3621
3622        let block_key = Self::try_block_key(stmt, TryPart::Block);
3623        let block_parent = self.cur().current_block;
3624        self.push_block(block_key, block_parent);
3625        self.emit_scope_enter(block_key);
3626        self.stmts(block)?;
3627        self.emit_scope_leave(block_key);
3628        self.state().current_block = block_parent;
3629        // A guarded block that ends in a `return`/`throw` never reaches the
3630        // epilogue, so the reference does not emit one.
3631        self.pop_jump_target();
3632        let block_live = !block.last().is_some_and(Self::terminates);
3633
3634        if block_live {
3635            self.emit(Opcode::Drop, &[]);
3636            self.emit(Opcode::Undefined, &[]);
3637            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3638            self.emit(Opcode::Drop, &[]);
3639            self.emit_jump(Opcode::Goto, end_label, &[]);
3640        }
3641
3642        if let Some(handler) = handler {
3643            self.place_label(catch_label);
3644            // The thrown value is on top of the stack: bind it, or discard it for
3645            // `catch { }`.
3646            match &handler.param {
3647                Some(pattern) => {
3648                    // The stores resolve the names, so they have to run inside the
3649                    // parameter's own scope; otherwise a same-named `catch` further out
3650                    // could win. A `catch` binding is never in the dead zone, so the store
3651                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3652                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3653                    let param_parent = self.cur().current_block;
3654                    self.push_block(param_key, param_parent);
3655                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3656                    self.state().current_block = param_parent;
3657                }
3658                None => self.emit(Opcode::Drop, &[]),
3659            }
3660            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3661
3662            self.push_jump_target(JumpTarget {
3663                names: Vec::new(),
3664                break_label: None,
3665                continue_label: None,
3666                drop_count: 1,
3667                finally_label: Some(finally_label),
3668                is_regular_stmt: false,
3669                has_iterator: false,
3670                is_async_iterator: false,
3671            });
3672            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3673            let catch_parent = self.cur().current_block;
3674            self.push_block(catch_key, catch_parent);
3675            self.emit_scope_enter(catch_key);
3676            self.stmts(&handler.body)?;
3677            self.emit_scope_leave(catch_key);
3678            self.state().current_block = catch_parent;
3679            self.pop_jump_target();
3680            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3681
3682            if handler_live {
3683                self.emit(Opcode::Drop, &[]);
3684                self.emit(Opcode::Undefined, &[]);
3685                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3686                self.emit(Opcode::Drop, &[]);
3687                self.emit_jump(Opcode::Goto, end_label, &[]);
3688            }
3689
3690            // An error raised inside the handler still has to run the finalizer.
3691            self.place_label(catch2_label);
3692            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3693            self.emit(Opcode::Throw, &[]);
3694        } else {
3695            // `try`/`finally` with no handler: the finalizer runs, then the error
3696            // keeps propagating.
3697            self.place_label(catch_label);
3698            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3699            self.emit(Opcode::Throw, &[]);
3700        }
3701
3702        self.place_label(finally_label);
3703        // Inside the finalizer, leaving has a different cost: the return value and
3704        // the `gosub` return address are both on the stack, and neither finalizer nor
3705        // any outer one may run before the block has finished.
3706        self.push_jump_target(JumpTarget {
3707            names: Vec::new(),
3708            break_label: None,
3709            continue_label: None,
3710            drop_count: 2,
3711            finally_label: None,
3712            is_regular_stmt: false,
3713            has_iterator: false,
3714            is_async_iterator: false,
3715        });
3716        if let Some(finalizer) = finalizer {
3717            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3718            let finally_parent = self.cur().current_block;
3719            self.push_block(finally_key, finally_parent);
3720            self.emit_scope_enter(finally_key);
3721            self.stmts(finalizer)?;
3722            self.emit_scope_leave(finally_key);
3723            self.state().current_block = finally_parent;
3724        }
3725        self.pop_jump_target();
3726        self.emit(Opcode::Ret, &[]);
3727        self.place_label(end_label);
3728        Ok(())
3729    }
3730
3731    /// Compile `for`/`in` and `for`/`of`.
3732    ///
3733    /// Both keep an enumeration record on the value stack for the whole loop, which
3734    /// is what makes leaving early expensive: the record has to be dropped, or the
3735    /// iterator closed. The layout is
3736    ///
3737    /// ```text
3738    ///   <iterated expression>
3739    ///   for_in_start | for_of_start      <- pushes the record
3740    ///   goto TEST
3741    /// NEXT:
3742    ///   <bind the loop variable>
3743    ///   <body>
3744    /// TEST:
3745    ///   for_in_next | for_of_next 0
3746    ///   if_false NEXT                    <- not finished: next iteration
3747    ///   drop                             <- finished: discard the leftover value
3748    /// BREAK:
3749    ///   drop | iterator_close            <- the one cleanup `break` also uses
3750    /// ```
3751    ///
3752    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3753    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3754    /// of its own, and only a jump that passes *through* the loop pays for its record.
3755    fn for_in_of(
3756        &mut self,
3757        stmt: &Stmt,
3758        left: &ForHead,
3759        right: &Expr,
3760        body: &Stmt,
3761        kind: ForLoopKind,
3762        labels: &[String],
3763    ) -> Result<(), SyntaxError> {
3764        self.reset_value();
3765
3766        let loop_key = stmt.span.start.offset as u64;
3767        let loop_parent = self.cur().current_block;
3768        self.push_block(loop_key, loop_parent);
3769        self.emit_scope_enter(loop_key);
3770
3771        // The iterated expression is evaluated inside the loop's scope, after the
3772        // bindings exist in the temporal dead zone.
3773        self.expr(right)?;
3774
3775        let next = self.new_label();
3776        let test = self.new_label();
3777        let break_target = self.new_label();
3778
3779        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3780        match kind {
3781            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3782            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3783            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3784        }
3785        self.emit_jump(Opcode::Goto, test, &[]);
3786
3787        self.push_jump_target(JumpTarget {
3788            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3789            // loop had no label to break to, and the compiler reported "break has no
3790            // enclosing loop" for a loop that was plainly enclosing it.
3791            names: labels.to_vec(),
3792            break_label: Some(break_target),
3793            continue_label: Some(test),
3794            // Passing through the loop has to dispose of its record. A `for`/`of`
3795            // record is three slots, and closing the iterator consumes all of them.
3796            drop_count: if has_iterator { 3 } else { 1 },
3797            finally_label: None,
3798            is_regular_stmt: false,
3799            has_iterator,
3800            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3801        });
3802
3803        self.place_label(next);
3804        self.bind_loop_variable(left)?;
3805
3806        // The reference marks the body with its own label here. Nothing jumps to it
3807        // once the loop is laid out, but it is not decoration: a label between the
3808        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3809        // `set_loc v` when the body starts by reading the loop variable.
3810        let body_label = self.new_label();
3811        self.place_label(body_label);
3812        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3813        // region rather than the whole loop: the resource is the element that this
3814        // iteration produced.
3815        let using_slot = match left {
3816            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3817                decl.declarators
3818                    .first()
3819                    .and_then(|declarator| match &declarator.target.kind {
3820                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3821                        _ => None,
3822                    })
3823            }
3824            _ => None,
3825        };
3826        match using_slot {
3827            Some(slot) => {
3828                let live = !Self::terminates(body);
3829                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3830            }
3831            None => self.stmt(body)?,
3832        }
3833
3834        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3835        // binding each iteration**, so a closure the body creates keeps that iteration's
3836        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3837        // a new reference cell holding the current value.
3838        //
3839        // The position is the *end* of the body, not the start: closing before the body
3840        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3841        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3842        for name in Self::loop_binding_names(left) {
3843            let pos = self.cur().cur_pos;
3844            self.state().insns.push(Insn::CloseCaptured {
3845                name,
3846                block: loop_key,
3847            });
3848            self.state().insn_pos.push(pos);
3849        }
3850        self.place_label(test);
3851        match kind {
3852            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3853            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3854            ForLoopKind::AwaitOf => {
3855                // The reference's shape: step, `await` the result, then unpack it.
3856                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3857                self.emit(Opcode::Await, &[]);
3858                self.state().has_await = true;
3859                self.emit(Opcode::IteratorGetValueDone, &[]);
3860            }
3861        }
3862        self.emit_jump(Opcode::IfFalse, next, &[]);
3863        // The loop is finished; `for_xx_next` left an `undefined` behind.
3864        self.emit(Opcode::Drop, &[]);
3865
3866        self.pop_jump_target();
3867        self.place_label(break_target);
3868        if has_iterator {
3869            // A loop that ran to completion finds its iterator slot already cleared (see
3870            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3871            // `break` that jumped here.
3872            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3873        } else {
3874            self.emit(Opcode::Drop, &[]);
3875        }
3876
3877        self.emit_scope_leave(loop_key);
3878        self.state().current_block = loop_parent;
3879        Ok(())
3880    }
3881
3882    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3883    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3884    fn loop_binding_names(left: &ForHead) -> Vec<String> {
3885        let ForHead::VarDecl(decl) = left else {
3886            return Vec::new();
3887        };
3888        if decl.kind == VarDeclKind::Var {
3889            return Vec::new();
3890        }
3891        let mut names = Vec::new();
3892        for declarator in &decl.declarators {
3893            let mut idents = Vec::new();
3894            declarator.target.bound_names(&mut idents);
3895            names.extend(idents.into_iter().map(|ident| ident.name));
3896        }
3897        names
3898    }
3899
3900    /// Store the value `for_xx_next` left on the stack into the loop variable.
3901    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3902        // A declaration *initialises* the binding, which is what takes a `let` out of
3903        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3904        // binding declared elsewhere is an ordinary write and keeps its check.
3905        let (pattern, action) = match left {
3906            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3907            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3908        };
3909        match &pattern.kind {
3910            PatternKind::Ident(name) => {
3911                // `for (using x of …)` validates and snapshots each iteration's value
3912                // before the body runs, which is what makes a non-disposable element fail
3913                // on the iteration that produced it rather than at the end of the loop.
3914                if let ForHead::VarDecl(decl) = left
3915                    && decl.kind.is_using()
3916                {
3917                    let method_slot = self
3918                        .using_method_slot(&name.name)
3919                        .expect("a using binding was declared during hoisting");
3920                    self.emit(
3921                        Opcode::UsingCheck,
3922                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3923                    );
3924                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3925                }
3926                self.emit_var(action, &name.name);
3927                Ok(())
3928            }
3929            // Every other target stores through the same path an assignment pattern
3930            // uses, which is what makes `for (a[0] in obj)` write each key into the
3931            // property instead of refusing the loop outright.
3932            _ => self.destructure(
3933                pattern,
3934                match left {
3935                    ForHead::VarDecl(decl) => Some(decl.kind),
3936                    ForHead::Assign(_) => None,
3937                },
3938            ),
3939        }
3940    }
3941
3942    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3943        for declarator in &decl.declarators {
3944            let Some(init) = &declarator.init else {
3945                // `var x;` stays `undefined`. A lexical binding is different: it
3946                // has to be *initialised* to leave the temporal dead zone, so the
3947                // compiler supplies an explicit `undefined`.
3948                if decl.kind.is_lexical() {
3949                    // A lexical binding has to be *initialised* to leave the temporal
3950                    // dead zone, and a destructuring one is no different — `let {a}`
3951                    // with no initialiser is a syntax error, but `let [a] = []` still
3952                    // needs `a` to be initialised from an empty source, which the
3953                    // pattern does on its own.
3954                    self.emit(Opcode::Undefined, &[]);
3955                    self.destructure(&declarator.target, Some(decl.kind))?;
3956                }
3957                continue;
3958            };
3959            match &declarator.target.kind {
3960                PatternKind::Ident(name) => {
3961                    self.expr(init)?;
3962                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3963                    if decl.kind.is_using() {
3964                        // `using_check` validates the value and snapshots its dispose
3965                        // method: `value -> value, method`. The snapshot is what makes a
3966                        // later change to `Symbol.dispose` irrelevant, and validating here
3967                        // is what keeps the body from running at all when the value is not
3968                        // disposable.
3969                        let method_slot = self
3970                            .using_method_slot(&name.name)
3971                            .expect("a using binding was declared during hoisting");
3972                        self.emit(
3973                            Opcode::UsingCheck,
3974                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3975                        );
3976                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3977                        self.emit_var(VarAction::PutInit, &name.name);
3978                        continue;
3979                    }
3980                    // A declaration statement produces no value, so nothing is
3981                    // duplicated onto the stack.
3982                    match decl.kind {
3983                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3984                        _ => self.emit_var(VarAction::PutInit, &name.name),
3985                    }
3986                }
3987                _ => {
3988                    // A destructuring declaration keeps nothing on the stack: the
3989                    // pattern consumes the initialiser.
3990                    self.expr(init)?;
3991                    self.destructure(&declarator.target, Some(decl.kind))?;
3992                }
3993            }
3994        }
3995        Ok(())
3996    }
3997
3998    /// Bind a destructuring pattern from the value on top of the stack.
3999    ///
4000    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4001    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4002    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4003    /// *assignment*, where a member expression is a legal target and the store is an
4004    /// ordinary property write.
4005    ///
4006    /// The value is consumed. An assignment expression's own result is the right-hand
4007    /// side, which the caller keeps separately — the spec does not make the pattern's
4008    /// last store produce it.
4009    fn destructure(
4010        &mut self,
4011        pattern: &Pattern,
4012        decl: Option<VarDeclKind>,
4013    ) -> Result<(), SyntaxError> {
4014        match &pattern.kind {
4015            PatternKind::Ident(name) => {
4016                match decl {
4017                    Some(VarDeclKind::Var) | None => {
4018                        self.emit_var(VarAction::Put, &name.name);
4019                    }
4020                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4021                }
4022                Ok(())
4023            }
4024            PatternKind::Assign { target, default } => {
4025                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4026                // keeps `null`.
4027                //
4028                // The shape is the reference's: test for `undefined`, and when the value is
4029                // present fall **through** to a single store both paths share. The
4030                // alternatives — branching to the store on each side — need a second store
4031                // and a jump between them, which is what the dump used to show.
4032                let has_value = self.new_label();
4033                self.emit(Opcode::Dup, &[]);
4034                self.emit(Opcode::IsUndefined, &[]);
4035                self.emit_jump(Opcode::IfFalse, has_value, &[]);
4036                self.emit(Opcode::Drop, &[]);
4037                self.expr(default)?;
4038                // `var {f = function(){}} = {}` names the function `f`, like a plain
4039                // `var f = function(){}` does. Both pattern forms do it:
4040                // `BindingInitialization` names the value for a *binding* target, and since
4041                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4042                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4043                // no name to give, which is why only an identifier qualifies.
4044                if let PatternKind::Ident(name) = &target.kind {
4045                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4046                }
4047                self.place_label(has_value);
4048                self.destructure(target, decl)
4049            }
4050            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4051            PatternKind::Object { properties, rest } => {
4052                self.destructure_object(properties, rest, decl, pattern)
4053            }
4054            PatternKind::Member(member) if decl.is_none() => {
4055                // An assignment pattern may store into a property. The value is on the
4056                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4057                // put the three in the order `put_array_el`/`put_field` expect.
4058                self.expr(&member.object)?;
4059                match &member.property {
4060                    MemberProp::Ident(name) => {
4061                        // `value obj` -> `obj value`, the order `put_field` takes.
4062                        // Nothing needs to be left behind: a pattern element's value is
4063                        // consumed by its own store.
4064                        self.emit(Opcode::Swap, &[]);
4065                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4066                    }
4067                    MemberProp::Computed(index) => {
4068                        self.expr(index)?;
4069                        // `value obj key` -> `obj key value`.
4070                        self.emit(Opcode::Rot3l, &[]);
4071                        self.emit(Opcode::PutArrayEl, &[]);
4072                    }
4073                    MemberProp::Private(name) => {
4074                        // `value obj` -> `obj value`, and the store half of the assignment is
4075                        // the same one `obj.#x = value` uses — only without `insert2`,
4076                        // because a pattern element's value is not wanted back.
4077                        let binding = format!("#{}", name.name);
4078                        let (kind, setter) = self.private_use(&binding, member.span)?;
4079                        self.emit(Opcode::Swap, &[]);
4080                        self.private_store(&binding, kind, setter.as_deref())?;
4081                    }
4082                }
4083                Ok(())
4084            }
4085            PatternKind::Rest(inner) => self.destructure(inner, decl),
4086            PatternKind::Invalid(expr) => {
4087                Err(SyntaxError::new("invalid assignment target", expr.span))
4088            }
4089            _ => Err(SyntaxError::new(
4090                "this destructuring target is not supported by the compiler yet",
4091                pattern.span,
4092            )),
4093        }
4094    }
4095
4096    /// `[…]` on the left: drain an iterator, binding one target per element.
4097    fn destructure_array(
4098        &mut self,
4099        elements: &[Option<PatternElement>],
4100        rest: &Option<Box<RestElement>>,
4101        decl: Option<VarDeclKind>,
4102    ) -> Result<(), SyntaxError> {
4103        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4104        // pattern accepts any iterable and closes the iterator when the pattern ends
4105        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4106        // first because it is on top.
4107        self.emit(Opcode::ForOfStart, &[]);
4108        for element in elements {
4109            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4110            self.emit(Opcode::Drop, &[]);
4111            match element {
4112                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
4113                Some(PatternElement::Property { span, .. }) => {
4114                    return Err(SyntaxError::new(
4115                        "a property pattern is not a valid array element",
4116                        *span,
4117                    ));
4118                }
4119                // An elision skips the value, which is already on the stack.
4120                None => self.emit(Opcode::Drop, &[]),
4121            }
4122        }
4123        if let Some(rest) = rest {
4124            // The remaining values go into a fresh array. The target and its running
4125            // index stay on the stack above the iterator, which is what the operand of
4126            // `for_of_next` accounts for: two values sit above the iterator triple.
4127            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4128            self.emit(Opcode::Push0, &[]);
4129            let top = self.new_label();
4130            self.place_label(top);
4131            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
4132            let done = self.new_label();
4133            self.emit_jump(Opcode::IfTrue, done, &[]);
4134            self.emit(Opcode::DefineArrayEl, &[]);
4135            self.emit(Opcode::Inc, &[]);
4136            self.emit_jump(Opcode::Goto, top, &[]);
4137            self.place_label(done);
4138            self.emit(Opcode::Drop, &[]);
4139            self.emit(Opcode::Drop, &[]);
4140            self.destructure_rest(rest, decl)?;
4141        }
4142        self.emit(Opcode::IteratorClose, &[]);
4143        Ok(())
4144    }
4145
4146    /// `{…}` on the left: read properties off one boxed source object.
4147    fn destructure_object(
4148        &mut self,
4149        properties: &[Option<PatternElement>],
4150        rest: &Option<Box<RestElement>>,
4151        decl: Option<VarDeclKind>,
4152        pattern: &Pattern,
4153    ) -> Result<(), SyntaxError> {
4154        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4155        // aside for the rest element below.
4156        self.emit(Opcode::ToObject, &[]);
4157        let mut taken: Vec<Wtf8> = Vec::new();
4158        // A computed key's *value* is only known at run time, so with a rest element the
4159        // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4160        // local array that every key is written into as the pattern is walked — literal
4161        // keys by name, computed ones by the value the expression produced. Without this,
4162        // `let { [k]: a, ...rest } = o` was refused outright.
4163        let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4164        let key_log = if needs_key_log {
4165            let name = "<rest_exclude>";
4166            self.declare_hidden_local(name, VarKind::Normal);
4167            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4168            self.emit_var(VarAction::Put, name);
4169            Some(name)
4170        } else {
4171            None
4172        };
4173        for property in properties {
4174            let Some(PatternElement::Property {
4175                key, value, span, ..
4176            }) = property
4177            else {
4178                return Err(SyntaxError::new(
4179                    "a bare pattern is not a valid object property",
4180                    properties
4181                        .iter()
4182                        .flatten()
4183                        .map(|element| match element {
4184                            PatternElement::Pattern(pattern) => pattern.span,
4185                            PatternElement::Property { span, .. } => *span,
4186                        })
4187                        .next()
4188                        .unwrap_or(pattern.span),
4189                ));
4190            };
4191            // Every read needs the source twice: to read from, and to keep for the next
4192            // property. `get_field2` is that duplicate-and-read in one instruction, but it
4193            // leaves the copy *under* the value, so it is only usable when whatever
4194            // consumes the value tolerates that. See [`reads_with_get_field2`].
4195            let nested = reads_with_get_field2(decl, value);
4196            if !nested {
4197                self.emit(Opcode::Dup, &[]);
4198            }
4199            let slot = taken.len();
4200            match key {
4201                PropName::Literal(literal) => {
4202                    let name = self.property_key_text(literal, *span)?;
4203                    taken.push(name.clone());
4204                    if let Some(log) = &key_log {
4205                        // `arr index key -> arr`: the key is written into the log before
4206                        // the read, so the order of observable operations is unchanged.
4207                        self.emit_var(VarAction::Get, log);
4208                        self.push_number(slot as f64);
4209                        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4210                        self.emit(Opcode::PutArrayEl, &[]);
4211                    }
4212                    self.emit(
4213                        if nested {
4214                            Opcode::GetField2
4215                        } else {
4216                            Opcode::GetField
4217                        },
4218                        &[Op::Atom(Atom::from_wtf8(&name))],
4219                    );
4220                }
4221                PropName::Computed(index) => {
4222                    self.expr(index)?;
4223                    // `key key`: one stays on the stack for the read, the other goes into
4224                    // the exclusion log. The index is a compile-time constant, so no counter
4225                    // local is needed.
4226                    if let Some(log) = &key_log {
4227                        taken.push(Wtf8::default());
4228                        self.emit(Opcode::Dup, &[]);
4229                        self.emit_var(VarAction::Get, log);
4230                        self.emit(Opcode::Swap, &[]);
4231                        self.push_number(slot as f64);
4232                        self.emit(Opcode::Swap, &[]);
4233                        self.emit(Opcode::PutArrayEl, &[]);
4234                    }
4235                    self.emit(Opcode::GetArrayEl, &[]);
4236                }
4237                PropName::Private(_) => {
4238                    return Err(SyntaxError::new(
4239                        "private fields are not supported by the compiler yet",
4240                        value.span,
4241                    ));
4242                }
4243            }
4244            self.destructure(value, decl)?;
4245        }
4246        match rest {
4247            Some(rest) => {
4248                // `target src exclude`: the exclusion list is an array of the keys the
4249                // literal part already took, so the rest object gets only the others.
4250                self.emit(Opcode::Object, &[]);
4251                self.emit(Opcode::Swap, &[]);
4252                match &key_log {
4253                    // Built while walking the pattern; see `needs_key_log`.
4254                    Some(log) => {
4255                        self.emit_var(VarAction::Get, log);
4256                    }
4257                    None => {
4258                        for name in &taken {
4259                            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4260                        }
4261                        self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4262                    }
4263                }
4264                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4265                self.emit(Opcode::Drop, &[]);
4266                self.emit(Opcode::Drop, &[]);
4267                self.destructure_rest(rest, decl)?;
4268            }
4269            // The source was only kept for a rest element.
4270            None => self.emit(Opcode::Drop, &[]),
4271        }
4272        Ok(())
4273    }
4274
4275    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4276    fn destructure_rest(
4277        &mut self,
4278        rest: &RestElement,
4279        decl: Option<VarDeclKind>,
4280    ) -> Result<(), SyntaxError> {
4281        match rest {
4282            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4283            // `[...a.b] = c` stores into a property.
4284            RestElement::Member(member) => {
4285                let pattern = Pattern {
4286                    kind: PatternKind::Member(member.clone()),
4287                    span: member.span,
4288                };
4289                self.destructure(&pattern, decl)
4290            }
4291        }
4292    }
4293
4294    /// Compile a function declaration and queue it for instantiation at scope
4295    /// entry.
4296    ///
4297    /// A declaration is visible before the statement that declares it, so the
4298    /// code that creates the function object belongs at the top of the enclosing
4299    /// scope, not at the declaration.
4300    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4301        let name = func.name.as_ref().expect("a declaration has a name");
4302        let function = self.compile_function(func)?;
4303        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4304        let target = self.hoist_target(&name.name);
4305        let block = self.cur().current_block;
4306        self.state().hoisted.push((block, target, pool_index));
4307        Ok(())
4308    }
4309
4310    /// Where a name lives, for a hoisted declaration.
4311    fn hoist_target(&self, name: &str) -> HoistTarget {
4312        let state = self.cur();
4313        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4314            return HoistTarget::Arg(index as u32);
4315        }
4316        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4317            return HoistTarget::Loc(index as u32);
4318        }
4319        // A global function declaration is not a slot at all.
4320        HoistTarget::Global(name.to_string())
4321    }
4322
4323    // -- expressions -------------------------------------------------------
4324
4325    /// Compile one expression, recording where its instructions sit.
4326    ///
4327    /// The position is the node's operator when it has one and its first token
4328    /// otherwise, and it is restored on the way out so a parent's own instructions —
4329    /// which are emitted *after* its children — are blamed on the parent. Without the
4330    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4331    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4332        // `discard_value` belongs to the *statement* that is about to be compiled, so it
4333        // may only be honoured by that statement's own top-level expression. Taking it here
4334        // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4335        // the argument list is a different expression — it must still leave its value on the
4336        // stack. Without this the argument vanished, and `call` then consumed the callee as
4337        // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4338        // function).
4339        self.discard_root = std::mem::take(&mut self.state().discard_value);
4340        let saved = self.cur().cur_pos;
4341        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4342        // the operator a node exists for, and a variable *read*, which the reference
4343        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4344        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4345        // start, a parenthesised group, an anonymous function expression — leaves the
4346        // previous position in place, because a table entry the reference never writes is
4347        // one we must not write either: the instruction that inherits a position (the
4348        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4349        // report a more recent token than the reference does.
4350        let pos = expr.op_pos.or(match &expr.kind {
4351            ExprKind::Ident(ident) => Some(ident.span.start),
4352            _ => None,
4353        });
4354        match pos {
4355            Some(pos) => self.state().cur_pos = Some(pos),
4356            // A node the reference records nothing for: its own instructions stay
4357            // unpositioned, so they inherit whatever was written last — which is what an
4358            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4359            // enclosing position instead would blame them on a token the reference has not
4360            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4361            // a template's `to_propkey` the interpolation.
4362            None => self.state().cur_pos = None,
4363        }
4364        // Note a direct `eval` call before compiling it, because the *whole* function
4365        // is affected: an eval can name any binding the function declares, so every one
4366        // of them has to live in a cell for a closure it creates to capture it.
4367        self.note_direct_eval(expr);
4368        let result = self.expr_inner(expr);
4369        self.discard_root = false;
4370        self.state().cur_pos = saved;
4371        result
4372    }
4373
4374    /// Record which bindings are in scope at a direct `eval` call.
4375    ///
4376    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4377    /// resolves names from a string at run time, so the only chance to pin down *which*
4378    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4379    /// its block is the current block, an enclosing one, or the function scope.
4380    fn materialize_eval_sites(&mut self) {
4381        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4382        for (span, site_block, in_params, private, arguments_allowed) in pending {
4383            self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4384        }
4385    }
4386
4387    /// Resolve the bindings visible at one `eval` call.
4388    fn resolve_eval_site(
4389        &mut self,
4390        span: Span,
4391        site_block: u64,
4392        site_in_params: bool,
4393        private_names: Vec<EvalPrivate>,
4394        arguments_allowed: bool,
4395    ) {
4396        /// How near a binding is: function distance first, then block depth, then the
4397        /// later declaration (which shadows the earlier one in the same block).
4398        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4399
4400        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4401        // walked, innermost function first: a direct `eval` sees every enclosing
4402        // function's bindings, and none of them can be resolved at run time because the
4403        // runtime only has names to go on.
4404        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4405        let deepest = self.stack.len() - 1;
4406        for (level, state) in self.stack.iter().enumerate().rev() {
4407            let owner = (deepest - level) as u32;
4408            // The innermost function's block is the one the call sat in, which is not
4409            // the block the compiler is in now; the enclosing functions are still at
4410            // the point where this one was created.
4411            let here = if level == deepest {
4412                site_block
4413            } else {
4414                state.current_block
4415            };
4416            // The chain of live blocks, innermost first, with a depth for each. The walk
4417            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4418            // block can start at source offset zero.
4419            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4420            let mut block = here;
4421            while let Some(parent) = state
4422                .blocks
4423                .iter()
4424                .find(|candidate| candidate.key == block)
4425                .map(|candidate| candidate.parent)
4426                .filter(|parent| *parent != NO_PARENT)
4427                .filter(|parent| parent != &block)
4428            {
4429                live.push((parent, live.len()));
4430                block = parent;
4431            }
4432            let depth_of = |key: u64| {
4433                live.iter()
4434                    .find(|(candidate, _)| *candidate == key)
4435                    .map(|(_, depth)| *depth)
4436                    // The function scope is the outermost depth there is. A binding of a
4437                    // block this site is not inside lands here too, which pushes it
4438                    // behind every live one — the right answer: it is out of scope.
4439                    .unwrap_or(live.len())
4440            };
4441            for (index, arg) in state.args.iter().enumerate() {
4442                bindings.push((
4443                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4444                    EvalVisible {
4445                        name: arg.name.clone(),
4446                        is_arg: true,
4447                        index: index as u32,
4448                        owner,
4449                    },
4450                ));
4451            }
4452            // A parameter list cannot see the body, so a body `var` is not a binding the
4453            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4454            // not let that eval write the body's `c`.
4455            let hides_body = if level == deepest {
4456                site_in_params
4457            } else {
4458                state.created_in_params
4459            };
4460            for (index, var) in state.vars.iter().enumerate() {
4461                let block = state
4462                    .var_block
4463                    .get(index)
4464                    .copied()
4465                    .unwrap_or(FUNCTION_SCOPE);
4466                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4467                    continue;
4468                }
4469                bindings.push((
4470                    (
4471                        owner as usize,
4472                        depth_of(block),
4473                        std::cmp::Reverse(index as u32),
4474                    ),
4475                    EvalVisible {
4476                        name: var.name.clone(),
4477                        is_arg: false,
4478                        index: index as u32,
4479                        owner,
4480                    },
4481                ));
4482            }
4483        }
4484        // Innermost function first, then innermost block, then the later declaration
4485        // (which shadows the earlier one within a block).
4486        bindings.sort_by_key(|(priority, _)| *priority);
4487        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4488        self.state().eval_sites.push(EvalSite {
4489            line: span.start.line,
4490            column: span.start.column,
4491            bindings,
4492            private_names,
4493            arguments_allowed,
4494        });
4495    }
4496
4497    /// The private names visible from the compiler's current position, innermost last.
4498    ///
4499    /// A direct `eval` inherits these because private names are lexically scoped
4500    /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
4501    /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
4502    /// shadowing `ClassPlan::find` gives a use site inside the body.
4503    fn visible_private_names(&self) -> Vec<EvalPrivate> {
4504        let mut out: Vec<EvalPrivate> = Vec::new();
4505        for scope in &self.private_scopes {
4506            for (name, use_) in scope {
4507                if out.iter().any(|entry| &entry.name == name) {
4508                    continue;
4509                }
4510                out.push(EvalPrivate {
4511                    name: name.clone(),
4512                    kind: match use_.kind {
4513                        PrivateKind::Field => EvalPrivateKind::Field,
4514                        PrivateKind::Method => EvalPrivateKind::Method,
4515                        PrivateKind::Getter => EvalPrivateKind::Getter,
4516                        PrivateKind::Setter => EvalPrivateKind::Setter,
4517                    },
4518                    setter: use_.setter.clone(),
4519                });
4520            }
4521        }
4522        out
4523    }
4524
4525    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4526    ///
4527    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4528    /// a bare identifier callee counts.
4529    /// Record everything a direct `eval` call site has to tell the runtime.
4530    ///
4531    /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
4532    /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
4533    /// entirely. Missing the tail-call path is not hypothetical — it is why
4534    /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
4535    /// names were otherwise wired through.
4536    fn note_direct_eval(&mut self, expr: &Expr) {
4537        if !Self::is_direct_eval(expr) {
4538            return;
4539        }
4540        // Every enclosing function is affected too: the eval sees the whole scope chain,
4541        // and a closure it creates can capture a binding of any of them.
4542        // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
4543        // because the closure the eval builds outlives the loop iteration.
4544        for state in &mut self.stack {
4545            state.has_direct_eval = true;
4546        }
4547        let block = self.cur().current_block;
4548        let in_params = self.cur().in_params;
4549        // The private names are snapshotted **here**, at the call site, not when the sites
4550        // are materialised: materialisation happens once the whole function is compiled, by
4551        // which point every class scope has been popped and the answer would always be
4552        // empty.
4553        let private = self.visible_private_names();
4554        // An arrow has no `arguments` of its own and inherits the restriction from the
4555        // nearest real function: `x = () => { () => eval('arguments') }` is still a
4556        // class field initializer's arrow, and still has no `arguments` to see.
4557        let arguments_allowed = !self
4558            .stack
4559            .iter()
4560            .rev()
4561            .find(|state| !state.is_arrow)
4562            .is_some_and(|state| state.no_arguments_binding);
4563        self.state().pending_eval_sites.push((
4564            expr.span,
4565            block,
4566            in_params,
4567            private,
4568            arguments_allowed,
4569        ));
4570    }
4571
4572    fn is_direct_eval(expr: &Expr) -> bool {
4573        matches!(
4574            &expr.kind,
4575            ExprKind::Call { callee, .. }
4576                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4577        )
4578    }
4579
4580    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4581        match &expr.kind {
4582            ExprKind::Number(value) => self.push_number(*value),
4583            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4584            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4585            ExprKind::Null => self.emit(Opcode::Null, &[]),
4586            ExprKind::String(text) => self.push_string(text),
4587            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4588            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4589            ExprKind::This => self.this_expression(),
4590            ExprKind::NewTarget => self.new_target_expression(),
4591            ExprKind::Paren(inner) => self.expr(inner)?,
4592            ExprKind::Binary { op, left, right } => {
4593                self.expr(left)?;
4594                self.expr(right)?;
4595                self.emit(binary_opcode(*op), &[]);
4596            }
4597            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4598            ExprKind::Unary {
4599                op: UnaryOp::Minus,
4600                argument,
4601            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4602                let ExprKind::Number(value) = argument.unparen().kind else {
4603                    unreachable!("matched above")
4604                };
4605                // The reference folds a negative literal only when the negation is
4606                // exact in the integer range: `-1` becomes `push_minus1` and
4607                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4608                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4609                // `-Infinity`, not `Infinity` — and folding a fraction would change
4610                // which instruction the reference emits.
4611                let negated = -value;
4612                // `-2147483648` is deliberately excluded: its magnitude is one past
4613                // `i32::MAX`, so the reference sends it through the constant pool and
4614                // negates at run time instead.
4615                if value > 0.0
4616                    && negated == negated.trunc()
4617                    && negated >= -(i32::MAX as f64)
4618                    && negated < 0.0
4619                {
4620                    self.push_number(negated);
4621                } else {
4622                    self.push_number(value);
4623                    self.emit(Opcode::Neg, &[]);
4624                }
4625            }
4626            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4627            ExprKind::Conditional { test, cons, alt } => {
4628                let else_label = self.new_label();
4629                let end_label = self.new_label();
4630                self.expr(test)?;
4631                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4632                self.expr(cons)?;
4633                self.emit_jump(Opcode::Goto, end_label, &[]);
4634                self.place_label(else_label);
4635                self.expr(alt)?;
4636                self.place_label(end_label);
4637            }
4638            ExprKind::Assign { op, target, value } => {
4639                let discard = std::mem::take(&mut self.discard_root);
4640                self.assign(*op, target, value, discard)?
4641            }
4642            ExprKind::Update {
4643                op,
4644                argument,
4645                prefix,
4646            } => self.update(*op, argument, *prefix)?,
4647            ExprKind::Sequence(items) => {
4648                for (index, item) in items.iter().enumerate() {
4649                    self.expr(item)?;
4650                    if index + 1 != items.len() {
4651                        self.emit(Opcode::Drop, &[]);
4652                    }
4653                }
4654            }
4655            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4656            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4657            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4658            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4659            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4660            ExprKind::Template(template) => self.template_literal(template)?,
4661            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4662            ExprKind::New { callee, arguments } => {
4663                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4664                // The `dup` is not redundant: `call_constructor` takes the
4665                // constructor twice, once as the target and once as `new.target`,
4666                // which is what makes `new.target === C` inside the body.
4667                self.expr(callee)?;
4668                self.emit(Opcode::Dup, &[]);
4669                let args = arguments.as_deref().unwrap_or(&[]);
4670                if Self::has_spread(args) {
4671                    // `C C array`: the duplicated callee is already both the target
4672                    // and `new.target`, so no reordering is needed before `apply 1`.
4673                    self.argument_array(args)?;
4674                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4675                    return Ok(());
4676                }
4677                for argument in args {
4678                    self.expr(argument)?;
4679                }
4680                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4681            }
4682            ExprKind::Class(class) => self.class_definition(class, true)?,
4683            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4684            ExprKind::Yield { argument, delegate } => {
4685                self.yield_expression(argument.as_deref(), *delegate)?
4686            }
4687            ExprKind::Await(argument) => self.await_expression(argument)?,
4688            ExprKind::RegExp { pattern, flags } => {
4689                // A literal is compiled *here*, at parse time, not when the line runs. The
4690                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4691                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4692                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4693                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4694                // to be rejected before any code runs.
4695                //
4696                // This is the whole reason the engine lives in its own crate rather than
4697                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4698                // (`pure` depends on `compile`), but both need this.
4699                // The lexer already rejected an unknown or repeated flag, so an unparsable
4700                // flag string here would be a bug in the lexer rather than in the script;
4701                // fall back to the default flags instead of inventing a second message.
4702                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4703                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4704                    SyntaxError::new(
4705                        format!("invalid regular expression: {}", error.message),
4706                        expr.span,
4707                    )
4708                })?;
4709                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4710                // would mean serialising the syntax tree into the function's constant pool,
4711                // and a literal is created once per evaluation of its expression anyway.
4712                let _ = parsed;
4713                // The pattern and its flags travel as two string constants; `regexp` builds
4714                // the object. A dedicated opcode (rather than a call to the constructor) is
4715                // what the reference does too, so that a literal never goes through the
4716                // public `RegExp` function and its string-coercion rules.
4717                self.push_string(&Wtf8::new(pattern));
4718                self.push_string(&Wtf8::new(flags));
4719                self.emit(Opcode::Regexp, &[]);
4720            }
4721            ExprKind::Arrow(func) => {
4722                let function = self.compile_function(func)?;
4723                let index = self.push_constant(Constant::Function(Box::new(function)));
4724                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4725            }
4726            ExprKind::Function(func) => {
4727                let function = self.compile_function_with_name(func, true)?;
4728                let index = self.push_constant(Constant::Function(Box::new(function)));
4729                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4730            }
4731            // `import.meta`: the host fills a per-module object at link time.
4732            ExprKind::ImportMeta => {
4733                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4734            }
4735            // `import("x")` compiles to a two-slot push followed by one opcode: the
4736            // specifier, then the options object. Both are evaluated, in that order, because
4737            // §13.3.10.1 numbers them that way and their side effects are observable — the
4738            // absent second argument is a literal `undefined`, which evaluates to nothing.
4739            ExprKind::ImportCall(specifier, options) => {
4740                self.expr(specifier)?;
4741                match options {
4742                    Some(options) => self.expr(options)?,
4743                    None => {
4744                        self.emit(Opcode::Undefined, &[]);
4745                    }
4746                }
4747                self.emit(Opcode::Import, &[]);
4748            }
4749            ExprKind::PrivateIn { name, object } => {
4750                // `#x in o`: the object, then the binding, then one opcode which decides what
4751                // to do with the second operand. A field's binding holds a symbol and the
4752                // answer is an own-property test; a method's holds a function and the answer
4753                // is a brand check — both live in `private_in`, so the compiler emits the
4754                // same instruction for either.
4755                self.expr(object)?;
4756                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4757                self.emit(Opcode::PrivateIn, &[]);
4758            }
4759            _ => {
4760                return Err(SyntaxError::new(
4761                    "this expression form is not supported by the compiler yet",
4762                    expr.span,
4763                ));
4764            }
4765        }
4766        Ok(())
4767    }
4768
4769    /// Build one array holding the evaluated call arguments, which is how a call
4770    /// containing a spread is compiled: the reference does the same, building the
4771    /// list on the stack and handing it to `apply`.
4772    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4773        let elements: Vec<Option<ArrayElement>> = arguments
4774            .iter()
4775            .map(|argument| match &argument.unparen().kind {
4776                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4777                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4778            })
4779            .collect();
4780        self.array_literal(&elements, Span::default())
4781    }
4782
4783    /// Whether any argument is a spread, which is what selects the `apply` form.
4784    fn has_spread(arguments: &[Expr]) -> bool {
4785        arguments
4786            .iter()
4787            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4788    }
4789
4790    /// Compile `a${x}b`.
4791    ///
4792    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4793    /// string when the template starts with a substitution), then for each
4794    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4795    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4796    /// way `ToString` would while leaving the result a string for `add` to
4797    /// concatenate.
4798    ///
4799    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4800    /// chunk always lands where a value is pushed and `push_atom_value` is the
4801    /// instruction the reference uses for it; the empty first chunk has its own
4802    /// zero-byte form.
4803    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4804        let first = template.quasis.first();
4805        match first.and_then(|quasi| quasi.cooked.clone()) {
4806            Some(text) if !text.is_empty() => {
4807                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4808            }
4809            // Either the template begins with a substitution, or the chunk is
4810            // empty — in both cases the chain needs a string to start from.
4811            _ => self.emit(Opcode::PushEmptyString, &[]),
4812        }
4813        for (index, expression) in template.expressions.iter().enumerate() {
4814            self.expr(expression)?;
4815            self.emit(Opcode::ToPropkey, &[]);
4816            self.emit(Opcode::Add, &[]);
4817            if let Some(text) = template
4818                .quasis
4819                .get(index + 1)
4820                .and_then(|quasi| quasi.cooked.clone())
4821                && !text.is_empty()
4822            {
4823                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4824                self.emit(Opcode::Add, &[]);
4825            }
4826        }
4827        Ok(())
4828    }
4829
4830    /// Compile an object literal.
4831    ///
4832    /// The object is built in place: `object` pushes it, and each property leaves it
4833    /// on the stack with one field more, so no temporary is needed and later
4834    /// properties can overwrite earlier ones.
4835    ///
4836    /// The instruction depends on *how* the property was written, not on what kind
4837    /// of value it holds:
4838    ///
4839    /// | source | instruction |
4840    /// |---|---|
4841    /// | `{ a: v }` | `define_field a` |
4842    /// | `{ __proto__: v }` | `set_proto` |
4843    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4844    /// | `{ m() {} }` | `define_method m,4` |
4845    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4846    /// | `{ [k]() {} }` | `define_method_computed 4` |
4847    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4848    ///
4849    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4850    /// key itself, which is why the trailing `drop` is absent there too.
4851    /// `tag`…``: a call whose first argument is the call site's template object.
4852    ///
4853    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4854    /// array beside it, so `String.raw` can read the source text back. It is a constant
4855    /// because its contents never change; the reference builds one per call site and
4856    /// reuses it, while this builds one per evaluation, which only `tag` code that
4857    /// compares template objects across calls could tell apart.
4858    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4859        let cooked = quasi
4860            .quasis
4861            .iter()
4862            .map(|chunk| chunk.cooked.clone())
4863            .collect();
4864        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4865        let index = self.push_constant(Constant::Template { cooked, raw });
4866        let count = quasi.expressions.len() + 1;
4867        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4868        if let ExprKind::Member {
4869            object, property, ..
4870        } = &tag.unparen().kind
4871        {
4872            self.expr(object)?;
4873            match property {
4874                MemberProp::Ident(name) => {
4875                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4876                }
4877                MemberProp::Computed(key) => {
4878                    self.expr(key)?;
4879                    self.emit(Opcode::GetArrayEl2, &[]);
4880                }
4881                MemberProp::Private(name) => {
4882                    let binding = format!("#{}", name.name);
4883                    let (kind, _) = self.private_use(&binding, tag.span)?;
4884                    self.private_callee(&binding, kind)?;
4885                }
4886            }
4887            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4888            for expression in &quasi.expressions {
4889                self.expr(expression)?;
4890            }
4891            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4892            return Ok(());
4893        }
4894        self.expr(tag)?;
4895        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4896        for expression in &quasi.expressions {
4897            self.expr(expression)?;
4898        }
4899        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4900        Ok(())
4901    }
4902
4903    fn object_literal(
4904        &mut self,
4905        properties: &[ObjectProperty],
4906        span: Span,
4907    ) -> Result<(), SyntaxError> {
4908        self.emit(Opcode::Object, &[]);
4909        for property in properties {
4910            match property {
4911                ObjectProperty::Spread(value) => {
4912                    // `copy_data_properties` takes the target, the source and an
4913                    // exclusion list; a literal `null` means "exclude nothing".
4914                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4915                    // exclusion list by stack offset.
4916                    self.expr(spread_argument(value))?;
4917                    self.emit(Opcode::Null, &[]);
4918                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4919                    self.emit(Opcode::Drop, &[]);
4920                    self.emit(Opcode::Drop, &[]);
4921                }
4922                ObjectProperty::Property {
4923                    key,
4924                    value,
4925                    kind,
4926                    shorthand,
4927                    span: property_span,
4928                } => match key {
4929                    PropName::Computed(key_expr) => {
4930                        self.expr(key_expr)?;
4931                        match kind {
4932                            PropertyKind::Value => {
4933                                self.emit(Opcode::ToPropkey, &[]);
4934                                self.expr(value)?;
4935                                self.set_name_if_anonymous_computed(value);
4936                                self.emit(Opcode::DefineArrayEl, &[]);
4937                                // `define_array_el` leaves the object and the key;
4938                                // the key is no longer needed.
4939                                self.emit(Opcode::Drop, &[]);
4940                            }
4941                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4942                                self.emit_method_function(value)?;
4943                                self.emit(
4944                                    Opcode::DefineMethodComputed,
4945                                    &[Op::Int(define_method_flags(*kind))],
4946                                );
4947                            }
4948                        }
4949                    }
4950                    PropName::Literal(key) => {
4951                        let name = self.property_key_text(key, *property_span)?;
4952                        match kind {
4953                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4954                                self.emit_method_function(value)?;
4955                                self.emit(
4956                                    Opcode::DefineMethod,
4957                                    &[
4958                                        Op::Atom(Atom::from_wtf8(&name)),
4959                                        Op::Int(define_method_flags(*kind)),
4960                                    ],
4961                                );
4962                            }
4963                            PropertyKind::Value => {
4964                                self.expr(value)?;
4965                                // `{__proto__: x}` sets the prototype instead of
4966                                // creating a property; the shorthand `{__proto__}`
4967                                // is an ordinary property and does not.
4968                                if name == "__proto__" && !shorthand {
4969                                    self.emit(Opcode::SetProto, &[]);
4970                                } else {
4971                                    self.set_name_if_anonymous(value, &name);
4972                                    self.emit(
4973                                        Opcode::DefineField,
4974                                        &[Op::Atom(Atom::from_wtf8(&name))],
4975                                    );
4976                                }
4977                            }
4978                        }
4979                    }
4980                    PropName::Private(_) => {
4981                        return Err(SyntaxError::new(
4982                            "private names are not valid in object literals",
4983                            *property_span,
4984                        ));
4985                    }
4986                },
4987            }
4988        }
4989        let _ = span;
4990        Ok(())
4991    }
4992
4993    /// Emit the function a method/accessor property defines.
4994    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4995        self.expr(value)
4996    }
4997
4998    /// The name a literal property key contributes.
4999    ///
5000    /// String keys are used as written. A numeric key is converted the way
5001    /// `ToString` would convert it, because the atom is made from that spelling:
5002    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5003    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5004        match key {
5005            PropKey::Str(text) => Ok(text.clone()),
5006            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5007        }
5008    }
5009
5010    /// Compile an optional chain.
5011    ///
5012    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5013    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5014    /// `undefined`. So the chain is compiled with one end label and every guard
5015    /// jumps to it. The parser hands us the extent of that spine as an
5016    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5017    /// exactly the scope the label has to cover.
5018    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5019        let end = self.new_label();
5020        self.chain_link(inner, end)?;
5021        self.place_label(end);
5022        Ok(())
5023    }
5024
5025    /// A member access or call reached from outside any optional chain.
5026    ///
5027    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5028    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5029    /// still created because [`Self::chain_link`] takes it, and placing it at the
5030    /// end is a no-op that keeps a single code path.
5031    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5032        let end = self.new_label();
5033        self.chain_link(expr, end)?;
5034        self.place_label(end);
5035        Ok(())
5036    }
5037
5038    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5039    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5040        match &expr.kind {
5041            ExprKind::Member {
5042                object,
5043                property,
5044                optional,
5045            } => {
5046                // `super.x` is not a lookup on a value: it starts at the home object's
5047                // prototype and keeps `this` as the receiver, so it cannot go through
5048                // `chain_link` and the ordinary field read.
5049                if matches!(object.unparen().kind, ExprKind::SuperProp) {
5050                    self.super_base();
5051                    match property {
5052                        MemberProp::Ident(name) => self.emit(
5053                            Opcode::PushAtomValue,
5054                            &[Op::Atom(Atom::from_text(&name.name))],
5055                        ),
5056                        MemberProp::Computed(index) => self.expr(index)?,
5057                        MemberProp::Private(_) => {
5058                            return Err(SyntaxError::new(
5059                                "private fields are not supported by the compiler yet",
5060                                expr.span,
5061                            ));
5062                        }
5063                    }
5064                    self.emit(Opcode::GetSuperValue, &[]);
5065                    return Ok(());
5066                }
5067                self.chain_link(object, end)?;
5068                if *optional {
5069                    self.optional_guard(end);
5070                }
5071                match property {
5072                    // `.length` has its own opcode. The reference emits it for every
5073                    // object, not just arrays, so a name-based rule is right and
5074                    // cheaper than the generic field read.
5075                    MemberProp::Ident(name) if name.name == "length" => {
5076                        self.emit(Opcode::GetLength, &[]);
5077                    }
5078                    MemberProp::Ident(name) => {
5079                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5080                    }
5081                    MemberProp::Computed(index) => {
5082                        self.expr(index)?;
5083                        self.emit(Opcode::GetArrayEl, &[]);
5084                    }
5085                    MemberProp::Private(name) => {
5086                        // The binding comes from the class scope, so a read from outside the
5087                        // class cannot name it at all. `?.` checks the object, not the field:
5088                        // `o?.#x` guards on `o` being nullish.
5089                        let binding = format!("#{}", name.name);
5090                        let (kind, _) = self.private_use(&binding, expr.span)?;
5091                        self.private_load(&binding, kind, expr.span)?;
5092                    }
5093                }
5094                Ok(())
5095            }
5096            ExprKind::Call {
5097                callee,
5098                arguments,
5099                optional,
5100            } => {
5101                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5102                // cannot: it reads the function and then calls it with no
5103                // receiver at all. The reference's answer is to keep the object
5104                // under the function value — `get_field2` reads a field and leaves
5105                // its base in place — and to use `call_method`, which takes the
5106                // receiver from the stack. Missing this does not just cost an
5107                // instruction, it loses the `this` binding.
5108                if let ExprKind::Member {
5109                    object,
5110                    property,
5111                    optional: member_optional,
5112                } = &callee.unparen().kind
5113                {
5114                    // `super.m()` reads the method off the home object's prototype but
5115                    // calls it with `this`, so the receiver goes under the read instead of
5116                    // being replaced by it.
5117                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
5118                        self.super_base();
5119                        match property {
5120                            MemberProp::Ident(name) => self.emit(
5121                                Opcode::PushAtomValue,
5122                                &[Op::Atom(Atom::from_text(&name.name))],
5123                            ),
5124                            MemberProp::Computed(index) => self.expr(index)?,
5125                            MemberProp::Private(_) => {
5126                                return Err(SyntaxError::new(
5127                                    "private fields are not supported by the compiler yet",
5128                                    expr.span,
5129                                ));
5130                            }
5131                        }
5132                        // The two-output form would drop the receiver; this one replaces
5133                        // the prototype and the key, leaving `this` underneath.
5134                        self.emit(Opcode::GetArrayEl, &[]);
5135                        if Self::has_spread(arguments) {
5136                            self.argument_array(arguments)?;
5137                            self.emit(Opcode::Perm3, &[]);
5138                            self.emit(Opcode::Apply, &[Op::Int(0)]);
5139                            return Ok(());
5140                        }
5141                        for argument in arguments {
5142                            self.expr(argument)?;
5143                        }
5144                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5145                        return Ok(());
5146                    }
5147                    self.chain_link(object, end)?;
5148                    if *member_optional {
5149                        self.optional_guard(end);
5150                    }
5151                    match property {
5152                        MemberProp::Ident(name) => {
5153                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5154                        }
5155                        MemberProp::Computed(index) => {
5156                            self.expr(index)?;
5157                            // The key is not needed after the read, so this is the
5158                            // two-output form: object, value.
5159                            self.emit(Opcode::GetArrayEl2, &[]);
5160                        }
5161                        MemberProp::Private(name) => {
5162                            // The receiver is already under the callee, which is exactly the
5163                            // shape `call_method` and `apply` want — so nothing is dropped.
5164                            let binding = format!("#{}", name.name);
5165                            let (kind, _) = self.private_use(&binding, expr.span)?;
5166                            self.private_callee(&binding, kind)?;
5167                        }
5168                    }
5169                    if Self::has_spread(arguments) {
5170                        // Stack is `obj func`; the array goes on top, then `perm3`
5171                        // reorders to the `func this array` that `apply` wants.
5172                        self.argument_array(arguments)?;
5173                        self.emit(Opcode::Perm3, &[]);
5174                        self.emit(Opcode::Apply, &[Op::Int(0)]);
5175                        return Ok(());
5176                    }
5177                    for argument in arguments {
5178                        self.expr(argument)?;
5179                    }
5180                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5181                    return Ok(());
5182                }
5183                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5184                // with `get_field2` so the base stays under it, and on the short-circuit
5185                // path pushes an extra `undefined` as a placeholder receiver — the call
5186                // then throws, which is what calling a missing optional chain should do.
5187                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5188                    && let ExprKind::Member {
5189                        object,
5190                        property,
5191                        optional: member_optional,
5192                    } = &inner.unparen().kind
5193                {
5194                    let call = self.new_label();
5195                    // A guard target of its own: the outer `end` skips the whole
5196                    // expression, and a short-circuited receiver still has to reach the
5197                    // call so that calling it throws.
5198                    let short = self.new_label();
5199                    self.chain_link(object, end)?;
5200                    if *member_optional {
5201                        self.optional_guard(short);
5202                    }
5203                    match property {
5204                        MemberProp::Ident(name) => {
5205                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5206                        }
5207                        MemberProp::Computed(index) => {
5208                            self.expr(index)?;
5209                            self.emit(Opcode::GetArrayEl2, &[]);
5210                        }
5211                        MemberProp::Private(name) => {
5212                            let binding = format!("#{}", name.name);
5213                            let (kind, _) = self.private_use(&binding, expr.span)?;
5214                            self.private_callee(&binding, kind)?;
5215                        }
5216                    }
5217                    self.emit_jump(Opcode::Goto, call, &[]);
5218                    self.place_label(short);
5219                    self.emit(Opcode::Undefined, &[]);
5220                    self.place_label(call);
5221                    if Self::has_spread(arguments) {
5222                        self.argument_array(arguments)?;
5223                        self.emit(Opcode::Perm3, &[]);
5224                        self.emit(Opcode::Apply, &[Op::Int(0)]);
5225                        return Ok(());
5226                    }
5227                    for argument in arguments {
5228                        self.expr(argument)?;
5229                    }
5230                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5231                    return Ok(());
5232                }
5233                self.chain_link(callee, end)?;
5234                if *optional {
5235                    self.optional_guard(end);
5236                }
5237                if Self::has_spread(arguments) {
5238                    // `func array -> func undefined array`, which is the plain-call
5239                    // form of `apply`: the receiver is `undefined`.
5240                    self.argument_array(arguments)?;
5241                    self.emit(Opcode::Undefined, &[]);
5242                    self.emit(Opcode::Swap, &[]);
5243                    self.emit(Opcode::Apply, &[Op::Int(0)]);
5244                    return Ok(());
5245                }
5246                for argument in arguments {
5247                    self.expr(argument)?;
5248                }
5249                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5250                Ok(())
5251            }
5252            _ => self.expr(expr),
5253        }
5254    }
5255
5256    /// Compile `expr` as a tail call when it is one, reporting whether it was.
5257    ///
5258    /// `tail_call` reuses the current frame instead of pushing a new one, so a
5259    /// tail-recursive function runs in constant stack space. It also has to be the
5260    /// *last* thing the function does, which is why only a `return` reaches here.
5261    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5262        let ExprKind::Call {
5263            callee,
5264            arguments,
5265            optional: false,
5266        } = &expr.unparen().kind
5267        else {
5268            return Ok(false);
5269        };
5270        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5271        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5272        // as an ordinary call costs the one frame the optimisation was saving and keeps the
5273        // semantics — the alternative was reaching the spread expression below and failing
5274        // with "this expression form is not supported", which is how `return super.m(...a)`
5275        // stopped compiling. Checked before anything is emitted, because the decision cannot
5276        // be taken back once `super_base` or a `get_field2` is on the stack.
5277        if Self::has_spread(arguments) {
5278            return Ok(false);
5279        }
5280        let end = self.new_label();
5281        if let ExprKind::Member {
5282            object,
5283            property,
5284            optional: false,
5285        } = &callee.unparen().kind
5286        {
5287            // `super.m()` in tail position is still an ordinary method call with `this`
5288            // as the receiver; only the read of the method differs.
5289            if matches!(object.unparen().kind, ExprKind::SuperProp) {
5290                self.super_base();
5291                match property {
5292                    MemberProp::Ident(name) => self.emit(
5293                        Opcode::PushAtomValue,
5294                        &[Op::Atom(Atom::from_text(&name.name))],
5295                    ),
5296                    MemberProp::Computed(index) => self.expr(index)?,
5297                    MemberProp::Private(_) => return Ok(false),
5298                }
5299                self.emit(Opcode::GetArrayEl, &[]);
5300                for argument in arguments {
5301                    self.expr(argument)?;
5302                }
5303                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5304                self.place_label(end);
5305                return Ok(true);
5306            }
5307            self.chain_link(object, end)?;
5308            match property {
5309                MemberProp::Ident(name) => {
5310                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5311                }
5312                MemberProp::Computed(index) => {
5313                    self.expr(index)?;
5314                    self.emit(Opcode::GetArrayEl2, &[]);
5315                }
5316                MemberProp::Private(_) => return Ok(false),
5317            }
5318            for argument in arguments {
5319                self.expr(argument)?;
5320            }
5321            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5322            self.place_label(end);
5323            return Ok(true);
5324        }
5325        self.chain_link(callee, end)?;
5326        for argument in arguments {
5327            self.expr(argument)?;
5328        }
5329        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5330        self.place_label(end);
5331        Ok(true)
5332    }
5333
5334    /// The `?.` guard: keep the value if it is neither null nor undefined,
5335    /// otherwise replace it with `undefined` and leave the whole chain.
5336    fn optional_guard(&mut self, end: Label) {
5337        let cont = self.new_label();
5338        self.emit(Opcode::Dup, &[]);
5339        self.emit(Opcode::IsUndefinedOrNull, &[]);
5340        self.emit_jump(Opcode::IfFalse, cont, &[]);
5341        self.emit(Opcode::Drop, &[]);
5342        self.emit(Opcode::Undefined, &[]);
5343        self.emit_jump(Opcode::Goto, end, &[]);
5344        self.place_label(cont);
5345    }
5346
5347    fn push_number(&mut self, value: f64) {
5348        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5349        // goes into the constant pool.
5350        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5351            let int = value as i32;
5352            if (-1..=7).contains(&int) {
5353                self.emit(Opcode::PushI32, &[Op::Int(int)]);
5354                return;
5355            }
5356            if (-128..=127).contains(&int) {
5357                self.emit(Opcode::PushI8, &[Op::Int(int)]);
5358                return;
5359            }
5360            if (-32768..=32767).contains(&int) {
5361                self.emit(Opcode::PushI16, &[Op::Int(int)]);
5362                return;
5363            }
5364            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5365            return;
5366        }
5367        let index = self.push_constant(Constant::Number(value));
5368        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5369    }
5370
5371    /// Push a `BigInt` literal.
5372    ///
5373    /// A value that fits an `i32` uses the immediate form, which is what the reference
5374    /// emits too; anything larger goes into the constant pool, because the operand of
5375    /// `push_bigint` is only four bytes wide.
5376    fn push_bigint(&mut self, digits: &str, radix: u32) {
5377        if radix == 10
5378            && let Ok(value) = digits.parse::<i64>()
5379            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5380        {
5381            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5382            return;
5383        }
5384        let index = self.push_constant(Constant::BigInt {
5385            digits: digits.to_string(),
5386            radix,
5387        });
5388        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5389    }
5390
5391    fn push_string(&mut self, text: &Wtf8) {
5392        if text.is_empty() {
5393            self.emit(Opcode::PushEmptyString, &[]);
5394            return;
5395        }
5396        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5397    }
5398
5399    /// Name an anonymous function from the binding it is assigned to.
5400    ///
5401    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5402    /// runtime cannot know without being told: the function object is created
5403    /// before the store. `set_name` carries the name across.
5404    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5405        if value.is_anonymous_function_definition() {
5406            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5407        }
5408    }
5409
5410    /// The same, for a computed key: the name comes from the value on the stack
5411    /// rather than from an atom, so a different instruction carries it.
5412    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5413        if value.is_anonymous_function_definition() {
5414            self.emit(Opcode::SetNameComputed, &[]);
5415        }
5416    }
5417
5418    /// Compile a function body that exists only in the compiler's head — a class's
5419    /// implicit constructor or its field initialiser.
5420    ///
5421    /// Everything structural is the same as a written function: a fresh `FnState`, its
5422    /// own body block, and resolution while the frame is still on the stack. Only the
5423    /// statements differ.
5424    fn compile_synthetic_function(
5425        &mut self,
5426        name: &str,
5427        strict: bool,
5428        span: Span,
5429        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5430    ) -> Result<CompiledFunction, SyntaxError> {
5431        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5432        state.span = Some((span.start.offset as usize, span.end.offset as usize));
5433        state.strict = strict;
5434        state.created_in_block = self.cur().current_block;
5435        state.with_names = self.cur().with_names.clone();
5436        state.line = span.start.line;
5437        state.column = span.start.column;
5438        let depth = self.stack.len();
5439        self.stack.push(state);
5440        let body_key = span.start.offset as u64;
5441        self.push_block(body_key, NO_PARENT);
5442        self.state().body_block = body_key;
5443        let result = (|| {
5444            self.emit_scope_enter(body_key);
5445            body(self)?;
5446            if self.end_is_reachable() {
5447                self.emit(Opcode::ReturnUndef, &[]);
5448            }
5449            Ok(())
5450        })();
5451        if result.is_err() {
5452            self.stack.truncate(depth);
5453            return result.map(|()| unreachable!());
5454        }
5455        Ok(self.finish_current())
5456    }
5457
5458    /// The implicit return of a class constructor.
5459    ///
5460    /// A constructor that falls off the end initialises its instance fields first, and a
5461    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5462    /// built rather than `undefined`.
5463    fn emit_class_constructor_tail(&mut self) {
5464        match self.cur().ctor_kind {
5465            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5466            // Nothing to install: a base constructor did it in its prologue and a derived
5467            // one at each `super()` site, which is where `this` first exists.
5468            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5469            CtorKind::Derived => {
5470                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5471                // running `super()` is a ReferenceError, not `undefined`.
5472                self.emit_var(VarAction::Get, "this");
5473                self.emit(Opcode::Return, &[]);
5474            }
5475        }
5476    }
5477
5478    /// `yield expr` / `yield* expr`.
5479    ///
5480    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5481    /// it to the caller and parks the frame. On resume the stack holds the value the
5482    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5483    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5484    /// `if_false <continue>` asks whether this was an ordinary `next`:
5485    ///
5486    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5487    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5488    ///   and uses the value sitting under the magic number.
5489    ///
5490    /// A `throw` never reaches here: the interpreter unwinds instead (see
5491    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5492    fn yield_expression(
5493        &mut self,
5494        argument: Option<&Expr>,
5495        delegate: bool,
5496    ) -> Result<(), SyntaxError> {
5497        if delegate {
5498            return self.yield_star(argument);
5499        }
5500        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5501        // does the same for the `return(v)` that can resume it — which is why an async
5502        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5503        // generator's is just `yield`.
5504        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5505        match argument {
5506            Some(value) => self.expr(value)?,
5507            None => self.emit(Opcode::Undefined, &[]),
5508        }
5509        if is_async {
5510            self.emit(Opcode::Await, &[]);
5511            self.state().has_await = true;
5512        }
5513        self.emit(Opcode::Yield, &[]);
5514        let resume = self.new_label();
5515        self.emit_jump(Opcode::IfFalse, resume, &[]);
5516        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5517        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5518        // finished the generator and never ran the `finally`.
5519        if is_async {
5520            self.emit(Opcode::Await, &[]);
5521        }
5522        self.emit_unwind_for_return(true);
5523        self.emit(Opcode::ReturnAsync, &[]);
5524        self.place_label(resume);
5525        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5526        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5527        // it through the ordinary expression-statement discard.
5528        Ok(())
5529    }
5530
5531    /// `yield* iterable`.
5532    ///
5533    /// The shape is the reference's, and it is a fall-through chain rather than a
5534    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5535    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5536    /// the inner iterator and finishes, `throw` forwards the exception into it and
5537    /// continues only if it has a `throw` method.
5538    ///
5539    /// The stack is `iter next catch value` throughout, `catch` being the offset
5540    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5541    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5542        match argument {
5543            Some(value) => self.expr(value)?,
5544            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5545            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5546        }
5547        // `for await of` is the same protocol as `for of` with two differences that matter
5548        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5549        // every `next()` result is a promise the delegate has to await.
5550        let is_async = self.cur().kind.is_async();
5551        self.emit(
5552            if is_async {
5553                Opcode::ForAwaitOfStart
5554            } else {
5555                Opcode::ForOfStart
5556            },
5557            &[],
5558        );
5559        self.emit(Opcode::Drop, &[]);
5560        self.emit(Opcode::Undefined, &[]);
5561        self.emit(Opcode::Undefined, &[]);
5562        let next = self.new_label();
5563        let resume = self.new_label();
5564        let finished = self.new_label();
5565        let rethrow = self.new_label();
5566        let throw_no_method = self.new_label();
5567        let done = self.new_label();
5568        self.place_label(next);
5569        self.emit(Opcode::IteratorNext, &[]);
5570        if is_async {
5571            self.emit(Opcode::Await, &[]);
5572            self.state().has_await = true;
5573        }
5574        self.emit(Opcode::IteratorCheckObject, &[]);
5575        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5576        self.emit_jump(Opcode::IfTrue, done, &[]);
5577        // The suspension. `resume` is both the label the return path jumps back to in order
5578        // to yield one more value and where the caller's answer arrives, as the value
5579        // followed by the magic number.
5580        //
5581        // The two forms differ in what they hand the suspension: `yield_star` takes the
5582        // result object itself, `async_yield_star` takes `.value`, because an async
5583        // generator awaits and re-wraps whatever it yields.
5584        self.place_label(resume);
5585        if is_async {
5586            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5587            self.emit(Opcode::AsyncYieldStar, &[]);
5588        } else {
5589            self.emit(Opcode::YieldStar, &[]);
5590        }
5591        self.emit(Opcode::Dup, &[]);
5592        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5593        self.emit(Opcode::Drop, &[]);
5594        self.emit_jump(Opcode::Goto, next, &[]);
5595
5596        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5597        self.place_label(rethrow);
5598        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5599        self.emit(Opcode::StrictEq, &[]);
5600        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5601        // A `return` closes the inner iterator; if it had none, the delegate simply
5602        // finishes with the requested value. In an async generator both the call and its
5603        // result are awaited, because the inner `return` may itself be async.
5604        if is_async {
5605            self.emit(Opcode::Await, &[]);
5606        }
5607        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5608        self.emit_jump(Opcode::IfTrue, finished, &[]);
5609        if is_async {
5610            self.emit(Opcode::Await, &[]);
5611        }
5612        self.emit(Opcode::IteratorCheckObject, &[]);
5613        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5614        self.emit_jump(Opcode::IfFalse, resume, &[]);
5615        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5616        self.place_label(finished);
5617        self.emit(Opcode::Nip, &[]);
5618        self.emit(Opcode::Nip, &[]);
5619        self.emit(Opcode::Nip, &[]);
5620        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5621        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5622        // awaits the value in an async generator and then runs the same `finally`/iterator
5623        // unwinding a written `return` would. Skipping the unwinding made
5624        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5625        if is_async {
5626            self.emit(Opcode::Await, &[]);
5627        }
5628        self.emit_unwind_for_return(true);
5629        self.emit(Opcode::ReturnAsync, &[]);
5630
5631        // `throw(e)`: forward it into the inner iterator.
5632        self.place_label(throw_no_method);
5633        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5634        let no_throw = self.new_label();
5635        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5636        if is_async {
5637            self.emit(Opcode::Await, &[]);
5638        }
5639        self.emit(Opcode::IteratorCheckObject, &[]);
5640        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5641        self.emit_jump(Opcode::IfFalse, resume, &[]);
5642        self.emit_jump(Opcode::Goto, done, &[]);
5643        // No `throw` method: close the iterator, then report the spec's TypeError. The
5644        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5645        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5646        // method has nothing to await.
5647        self.place_label(no_throw);
5648        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5649        let no_close = self.new_label();
5650        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5651        if is_async {
5652            self.emit(Opcode::Await, &[]);
5653        }
5654        self.place_label(no_close);
5655        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5656
5657        // The inner iterator finished: the delegate's value is the `yield*` expression's
5658        // value, so it is left on the stack for whatever consumes it.
5659        self.place_label(done);
5660        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5661        self.emit(Opcode::Nip, &[]);
5662        self.emit(Opcode::Nip, &[]);
5663        self.emit(Opcode::Nip, &[]);
5664        Ok(())
5665    }
5666
5667    /// `await expr`: exactly one instruction.
5668    ///
5669    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5670    /// on the stack and completion is signalled by the `return_async` at the end of the
5671    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5672    /// reference never emits, and a `for await` loop — which reaches `await` through the
5673    /// same opcode — would then spill a value the loop's unpacking does not expect.
5674    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5675        self.expr(argument)?;
5676        self.emit(Opcode::Await, &[]);
5677        self.state().has_await = true;
5678        Ok(())
5679    }
5680
5681    /// The `super` base: the receiver followed by the home object's prototype.
5682    ///
5683    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5684    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5685    /// prototype but calls it with the receiver.
5686    fn super_base(&mut self) {
5687        self.this_expression();
5688        self.home_object();
5689        self.emit(Opcode::GetSuper, &[]);
5690    }
5691
5692    /// `[[HomeObject]]` as `super` sees it.
5693    ///
5694    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5695    /// put it there — so for them the special object *is* the answer. An arrow and a
5696    /// static block have none: they read the enclosing function's, which has to be
5697    /// materialised into a local, exactly as `this` is for an arrow.
5698    ///
5699    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5700    /// name any program can write.
5701    fn home_object(&mut self) {
5702        if !self.cur().is_arrow {
5703            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5704            return;
5705        }
5706        if let Some(target) = self.enclosing_function() {
5707            self.state_at(target).needs_home_object_local = true;
5708            self.declare_at(target, HOME_OBJECT);
5709        }
5710        self.emit_var(VarAction::Get, HOME_OBJECT);
5711    }
5712
5713    /// `super(args)`: construct the parent class and adopt the result as `this`.
5714    ///
5715    /// The parent is the prototype of the constructor that is running, which is exactly
5716    /// what `extends` set up. `new.target` is passed through unchanged so that
5717    /// `new.target` inside the parent is the class actually being constructed.
5718    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5719        self.active_func_expression();
5720        self.emit(Opcode::GetSuper, &[]);
5721        self.new_target_expression();
5722        if Self::has_spread(arguments) {
5723            self.argument_array(arguments)?;
5724            self.emit(Opcode::Apply, &[Op::Int(1)]);
5725        } else {
5726            for argument in arguments {
5727                self.expr(argument)?;
5728            }
5729            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5730        }
5731        // The value stays on the stack: `super()` is an expression, and a derived
5732        // constructor's `this` may only be initialised once.
5733        self.emit(Opcode::Dup, &[]);
5734        self.emit_var(VarAction::PutInitChecked, "this");
5735        // Instance fields are installed here, not at the top of the body: a derived
5736        // constructor has no `this` to install them on until `super()` returns. The
5737        // reference emits the same call at every `super()` site.
5738        self.call_field_initialiser();
5739        Ok(())
5740    }
5741
5742    /// `this` as a local, which every class constructor and field initialiser needs.
5743    ///
5744    /// The reference materialises the receiver into a local rather than reading
5745    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5746    /// and a field initialiser has to see the final value.
5747    fn begin_this_local(&mut self) {
5748        self.declare_hidden_local("this", VarKind::Normal);
5749        self.emit(Opcode::PushThis, &[]);
5750        self.emit_var(VarAction::Put, "this");
5751        // The store is already at the top of the body, so `provide_this_local` has
5752        // nothing left to prepend. Without this the initialiser ended up with
5753        // `push_this; put_loc0 this` twice whenever the class also held a field
5754        // initialiser whose body read `this` through an arrow.
5755        self.state().has_this_prologue = true;
5756    }
5757
5758    /// Compile a constructor the class wrote.
5759    ///
5760    /// The flags have to be in place before the body is compiled, but
5761    /// `compile_function_with_name` creates its own state — so the caller's state is
5762    /// marked instead and the new one inherits it. That is the same trick the parameter
5763    /// prologue uses, and it keeps one code path for both.
5764    fn compile_class_constructor(
5765        &mut self,
5766        func: &ast::Function,
5767        has_heritage: bool,
5768    ) -> Result<CompiledFunction, SyntaxError> {
5769        let saved = self.cur().ctor_kind;
5770        self.state().class_ctor_pending = Some(if has_heritage {
5771            CtorKind::Derived
5772        } else {
5773            CtorKind::Base
5774        });
5775        let result = self.compile_function_with_name(func, false);
5776        self.state().ctor_kind = saved;
5777        self.state().class_ctor_pending = None;
5778        result
5779    }
5780
5781    /// The constructor a class gets when it does not declare one.
5782    ///
5783    /// A base class's is empty; a derived class's forwards every argument to the parent
5784    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5785    /// instance field initialiser afterwards when the class has fields, which is why the
5786    /// initialiser is captured rather than inlined.
5787    fn compile_implicit_constructor(
5788        &mut self,
5789        class: &Class,
5790        has_heritage: bool,
5791    ) -> Result<CompiledFunction, SyntaxError> {
5792        self.compile_synthetic_function(
5793            "",
5794            true,
5795            Span::new(class.body_end, class.body_end),
5796            |compiler| {
5797                if has_heritage {
5798                    // A derived constructor's `this` does not exist until `super()` returns,
5799                    // so it starts in the dead zone and `init_ctor` fills it.
5800                    compiler.declare("this", VarDef::lexical("this"));
5801                    compiler.emit(
5802                        Opcode::SetLocUninitialized,
5803                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5804                    );
5805                    compiler.emit(Opcode::InitCtor, &[]);
5806                    compiler.emit(
5807                        Opcode::PutLocCheckInit,
5808                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5809                    );
5810                } else {
5811                    compiler.begin_this_local();
5812                    compiler.emit(Opcode::CheckCtor, &[]);
5813                }
5814                compiler.call_field_initialiser();
5815                // A derived constructor returns `this`, the object `super()` built. Without
5816                // this the implicit constructor fell through to `return_undef`, and `new B()`
5817                // handed back the empty object `construct` had made instead of the one the
5818                // parent constructor initialised.
5819                if has_heritage {
5820                    compiler.emit_var(VarAction::Get, "this");
5821                    compiler.emit(Opcode::Return, &[]);
5822                }
5823                Ok(())
5824            },
5825        )
5826    }
5827
5828    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5829    ///
5830    /// A class with no instance fields leaves the binding `undefined`, and calling it
5831    /// would throw; the reference emits the same guard rather than branching at compile
5832    /// time because a class can be extended by a subclass whose fields still have to run.
5833    fn call_field_initialiser(&mut self) {
5834        let skip = self.new_label();
5835        self.emit_var(VarAction::Get, "<class_fields_init>");
5836        self.emit(Opcode::Dup, &[]);
5837        self.emit_jump(Opcode::IfFalse, skip, &[]);
5838        self.emit_var(VarAction::Get, "this");
5839        self.emit(Opcode::Swap, &[]);
5840        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5841        self.place_label(skip);
5842        self.emit(Opcode::Drop, &[]);
5843    }
5844
5845    /// The function that defines one class's fields on `this`, and runs its static blocks.
5846    ///
5847    /// `define_field` rather than `put_field`: a field is an own property created
5848    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5849    /// `x = 1` field must not call the setter.
5850    ///
5851    /// One function serves the whole class: it is called once per instance (or once, for
5852    /// the static half) and walks the members in source order. Static blocks are compiled
5853    /// into the same function because they *are* part of the same sequence — `static a =
5854    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5855    /// different values, so the two kinds cannot be split apart.
5856    fn compile_field_initialiser(
5857        &mut self,
5858        items: &[StaticInitItem<'_>],
5859        span: Span,
5860        instance: bool,
5861        add_brand: bool,
5862    ) -> Result<CompiledFunction, SyntaxError> {
5863        self.compile_synthetic_function("", true, span, |compiler| {
5864            // A field initialiser and a static block are not functions, so neither has an
5865            // `arguments` of its own; see `FnState::no_arguments_binding`.
5866            let current = compiler.stack.len() - 1;
5867            compiler.stack[current].no_arguments_binding = true;
5868            if instance {
5869                // An instance initialiser always carries a `<home_object>` local, because the
5870                // brand block below reads it — even when that block turns out to be dead. The
5871                // reference has the same artefact, and the store is visible in its dump.
5872                let current = compiler.stack.len() - 1;
5873                compiler.stack[current].needs_home_object_local = true;
5874            }
5875            compiler.begin_this_local();
5876            if instance {
5877                // `this` gets the brand the prototype created, before any field is defined —
5878                // which is what makes `#m()` usable from inside a field initialiser.
5879                //
5880                // The reference always emits `push_false; if_false L; this; home; add_brand;
5881                // L:` and patches the `push_false` to `push_true` from the class parse when
5882                // the class has private methods; either way the branch folds, but the *mark*
5883                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5884                // `this` local from being fused into a `set_loc`.
5885                let skip = compiler.new_label();
5886                if add_brand {
5887                    compiler.emit(Opcode::PushTrue, &[]);
5888                } else {
5889                    compiler.emit(Opcode::PushFalse, &[]);
5890                }
5891                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5892                compiler.emit_var(VarAction::Get, "this");
5893                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5894                compiler.emit(Opcode::AddBrand, &[]);
5895                compiler.place_label(skip);
5896            }
5897            for item in items {
5898                match item {
5899                    StaticInitItem::Field(key, value) => {
5900                        // A private field is *defined*, not assigned: `define_private_field`
5901                        // reads `obj symbol value`, and its point is that it fails on a
5902                        // receiver that is not this class's — which `put_field` would not.
5903                        //
5904                        // The three shapes are the reference's: `define_field <atom>` for a
5905                        // static name, `define_array_el` for a key that is only known at run
5906                        // time (`obj key value`), `define_private_field` for `#x`, and a
5907                        // computed key is read from its binding rather than recomputed.
5908                        compiler.emit_var(VarAction::Get, "this");
5909                        match key {
5910                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5911                                compiler.emit_var(VarAction::Get, binding);
5912                            }
5913                            FieldKey::Literal(_) => {}
5914                        }
5915                        match value {
5916                            Some(value) => compiler.expr(value)?,
5917                            None => compiler.emit(Opcode::Undefined, &[]),
5918                        }
5919                        match key {
5920                            FieldKey::Literal(literal) => {
5921                                let text = compiler.property_key_text(literal, span)?;
5922                                compiler
5923                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5924                            }
5925                            FieldKey::Computed(_) => {
5926                                compiler.emit(Opcode::DefineArrayEl, &[]);
5927                                // `define_array_el` leaves `obj key`; the key is consumed by
5928                                // the copy the pattern machinery wants, so both go.
5929                                compiler.emit(Opcode::Drop, &[]);
5930                            }
5931                            FieldKey::Private(_) => {
5932                                compiler.emit(Opcode::DefinePrivateField, &[]);
5933                            }
5934                        }
5935                        compiler.emit(Opcode::Drop, &[]);
5936                    }
5937                    StaticInitItem::Block { body, body_start } => {
5938                        let block = compiler.compile_static_block(body, *body_start)?;
5939                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5940                        // `this fclosure`, so `call_method` finds the receiver below the
5941                        // callee: the block runs with `this` bound to the class.
5942                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5943                        compiler.emit_var(VarAction::Get, "this");
5944                        compiler.emit(Opcode::Swap, &[]);
5945                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5946                        // Nothing the block evaluates is wanted; its effects are the point.
5947                        compiler.emit(Opcode::Drop, &[]);
5948                    }
5949                }
5950            }
5951            Ok(())
5952        })
5953    }
5954
5955    /// Compile a `static { … }` body into the function the class calls for it.
5956    ///
5957    /// Shaped like an arrow, because that is the one function form with no `this`,
5958    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5959    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5960    /// rejects the reference — but `this` and `super` both depend on it.
5961    ///
5962    /// The body is hoisted like a function body's, because the reference parses it as one:
5963    /// `var` inside a block is a local of the block's function, not of whatever encloses
5964    /// the class.
5965    fn compile_static_block(
5966        &mut self,
5967        body: &[Stmt],
5968        body_start: Position,
5969    ) -> Result<CompiledFunction, SyntaxError> {
5970        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5971        // Class bodies are strict, so a static block is too.
5972        state.strict = true;
5973        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5974        // so `this` and `super` come from the initialiser that calls it.
5975        state.is_arrow = true;
5976        state.created_in_block = self.cur().current_block;
5977        state.with_names = self.cur().with_names.clone();
5978        state.line = body_start.line;
5979        state.column = body_start.column;
5980        let depth = self.stack.len();
5981        self.stack.push(state);
5982        let body_key = body_start.offset as u64;
5983        self.push_block(body_key, NO_PARENT);
5984        self.state().body_block = body_key;
5985        let result = (|| {
5986            self.hoist(body, body_key)?;
5987            self.emit_scope_enter(body_key);
5988            for statement in body {
5989                self.stmt(statement)?;
5990            }
5991            if self.end_is_reachable() {
5992                self.emit(Opcode::ReturnUndef, &[]);
5993            }
5994            Ok(())
5995        })();
5996        if result.is_err() {
5997            self.stack.truncate(depth);
5998            return result.map(|()| unreachable!());
5999        }
6000        Ok(self.finish_current())
6001    }
6002
6003    /// Compile a class, leaving the constructor on the stack when `keep`.
6004    ///
6005    /// The shape follows the reference: the class body is its own scope holding the
6006    /// class's *inner* name as a `const` — which is what lets a method refer to the
6007    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6008    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6009    /// on the top of the stack: the prototype for instance members, the constructor
6010    /// itself for `static` ones, which is why a static member costs an extra `swap`.
6011    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6012        let parent_block = self.cur().current_block;
6013        let key = class.span.start.offset as u64;
6014        self.push_block(key, parent_block);
6015        let name = class.name.as_ref().map(|ident| ident.name.clone());
6016        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6017        // resolves `E` without a global lookup. An *unnamed* class expression has no such
6018        // binding, and `define_class` is handed the empty name.
6019        if let Some(name) = &name {
6020            self.declare(name, VarDef::constant(name.clone()));
6021        }
6022        self.emit_scope_enter(key);
6023
6024        // The heritage clause is evaluated outside the class's own scope: it cannot see
6025        // the class binding it is about to initialise.
6026        let saved_block = self.cur().current_block;
6027        self.state().current_block = parent_block;
6028        match &class.super_class {
6029            Some(parent) => self.expr(parent)?,
6030            None => self.emit(Opcode::Undefined, &[]),
6031        }
6032        self.state().current_block = saved_block;
6033        let has_heritage = class.super_class.is_some();
6034
6035        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6036        // lands after the heritage's code — which is where the reference puts it, because it
6037        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6038        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6039        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6040        // came out in the opposite order from the reference's.
6041        //
6042        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6043        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6044        // a const accepts — so the old comment's worry ("a const would refuse the second
6045        // store") did not apply: there is no second store.
6046        // Every `#name` the class declares gets a `const` binding in the class scope, and so
6047        // does every computed field key. That is how the reference does it
6048        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6049        // what makes a private name resolve like any other class-scope variable — including
6050        // through a nested function's closure — while remaining invisible outside.
6051        //
6052        // All of them are declared *before* `<class_fields_init>`, in member order, because
6053        // that is when the reference's parser creates them.
6054        let plan = ClassPlan::build(class);
6055        // The body's private names are visible from here to the end of the class, and shadow
6056        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6057        // — it is compiled first because `define_class` consumes it, but its body can name
6058        // `#x` like any other member's.
6059        self.private_scopes.push(plan.uses.clone());
6060        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6061        for binding in &plan.bindings {
6062            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6063        }
6064        let fci = self.declare(
6065            "<class_fields_init>",
6066            VarDef::constant("<class_fields_init>"),
6067        );
6068        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6069        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6070        // members' bindings follow in reverse.
6071        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6072        for slot in class_slots.iter().rev() {
6073            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6074        }
6075
6076        // The constructor is compiled before `define_class` because that instruction
6077        // consumes it; a class without one gets the implicit version.
6078        let constructor = class.elements.iter().find_map(|element| match element {
6079            ClassElement::Method {
6080                kind: MethodKind::Constructor,
6081                func,
6082                ..
6083            } => Some(&**func),
6084            _ => None,
6085        });
6086        // A constructor is compiled differently from a method: it owns `this`. The flags
6087        // go on the *enclosing* state because a constructor is a nested function and
6088        // `compile_function_with_name` starts a fresh one.
6089        let ctor = match constructor {
6090            Some(func) => self.compile_class_constructor(func, has_heritage)?,
6091            None => self.compile_implicit_constructor(class, has_heritage)?,
6092        };
6093        // A closure, not the bare constant: the constructor captures
6094        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6095        // has to hold the cell rather than a copy of its value.
6096        //
6097        // The pool slot is left unassigned for now, because the reference gives the
6098        // constructor the *last* index of the members' range: `js_parse_class` emits a
6099        // `push_const` whose operand is patched at the end of the class parse, after every
6100        // method has taken a slot. Emitting the members first and the constant second is how
6101        // the numbering comes out the same; the instruction itself stays where it is.
6102        let ctor_insn = self.cur().insns.len();
6103        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6104        let flags = if has_heritage { 1 } else { 0 };
6105        self.emit(
6106            Opcode::DefineClass,
6107            &[
6108                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6109                Op::Int(flags),
6110            ],
6111        );
6112
6113        // Instance fields and static fields are two different functions: the first runs
6114        // per instance from the constructor, the second runs once, here.
6115        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6116        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6117        for (index, element) in class.elements.iter().enumerate() {
6118            match element {
6119                ClassElement::Method {
6120                    key: member_key,
6121                    is_static,
6122                    kind,
6123                    func,
6124                    span,
6125                } => {
6126                    if *kind == MethodKind::Constructor {
6127                        continue;
6128                    }
6129                    // `static(x)` is a *method* named `static`, not a static method; the
6130                    // parser already decided which by putting it in `kind`.
6131                    if *is_static {
6132                        self.emit(Opcode::Swap, &[]);
6133                    }
6134                    // A computed key is evaluated *here*, before the method's closure
6135                    // exists, and stays under it: `define_method_computed` pops
6136                    // `function, key, object`, so the stack has to read
6137                    // `[class, prototype, key, function]`. Evaluating the key after the
6138                    // `fclosure` and swapping the two put the prototype *below* the
6139                    // closure, which defined the method on the function and lost the
6140                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6141                    // also the spec's — a class body evaluates every element's name before
6142                    // that element's function.
6143                    if let PropName::Computed(key) = member_key {
6144                        self.expr(key)?;
6145                    }
6146                    let function = self.compile_function_with_name(func, true)?;
6147                    let index = self.push_constant(Constant::Function(Box::new(function)));
6148                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6149                    match member_key {
6150                        // A private method is not a property of the prototype: it is a
6151                        // closure in the class scope, which is why nothing outside can reach
6152                        // it and why a use site has to brand-check. `set_name` gives the
6153                        // function its `name` (`#m`), which an accessor does not get — the
6154                        // reference leaves that commented out.
6155                        PropName::Private(ident) => {
6156                            let name = format!("#{}", ident.name);
6157                            // `set_home_object` first: the brand check reads the function's
6158                            // home object, and for a method that is the prototype.
6159                            self.emit(Opcode::SetHomeObject, &[]);
6160                            let binding = if *kind == MethodKind::Set {
6161                                format!("{name}<set>")
6162                            } else {
6163                                name.clone()
6164                            };
6165                            if *kind == MethodKind::Method {
6166                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6167                            }
6168                            self.emit_var(VarAction::PutInit, &binding);
6169                        }
6170                        PropName::Computed(_) => {
6171                            self.emit(
6172                                Opcode::DefineMethodComputed,
6173                                &[Op::Int(class_method_flags(*kind))],
6174                            );
6175                        }
6176                        PropName::Literal(literal) => {
6177                            let text = self.property_key_text(literal, *span)?;
6178                            self.emit(
6179                                Opcode::DefineMethod,
6180                                &[
6181                                    Op::Atom(Atom::from_wtf8(&text)),
6182                                    Op::Int(class_method_flags(*kind)),
6183                                ],
6184                            );
6185                        }
6186                    }
6187                    if *is_static {
6188                        self.emit(Opcode::Swap, &[]);
6189                    }
6190                }
6191                ClassElement::Field {
6192                    key: field_key,
6193                    is_static,
6194                    value,
6195                    ..
6196                } => {
6197                    // A private field's *symbol* is created here, at the member, and stored
6198                    // in its binding: the field's property is keyed by it, so it has to exist
6199                    // before any initialiser runs, and a fresh one per class body is what
6200                    // makes two classes that both write `#x` independent.
6201                    //
6202                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6203                    // whose `toString` has a side effect must not run again per instance.
6204                    let key = match field_key {
6205                        PropName::Private(ident) => {
6206                            let binding = format!("#{}", ident.name);
6207                            if *is_static {
6208                                self.emit(Opcode::Swap, &[]);
6209                            }
6210                            self.emit(
6211                                Opcode::PrivateSymbol,
6212                                &[Op::Atom(Atom::from_text(&binding))],
6213                            );
6214                            self.emit_var(VarAction::PutInit, &binding);
6215                            if *is_static {
6216                                self.emit(Opcode::Swap, &[]);
6217                            }
6218                            FieldKey::Private(binding)
6219                        }
6220                        PropName::Computed(expression) => {
6221                            let binding = plan
6222                                .computed
6223                                .get(&index)
6224                                .cloned()
6225                                .expect("every computed key got a binding");
6226                            if *is_static {
6227                                self.emit(Opcode::Swap, &[]);
6228                            }
6229                            self.expr(expression)?;
6230                            self.emit(Opcode::ToPropkey, &[]);
6231                            self.emit_var(VarAction::PutInit, &binding);
6232                            if *is_static {
6233                                self.emit(Opcode::Swap, &[]);
6234                            }
6235                            FieldKey::Computed(binding)
6236                        }
6237                        PropName::Literal(literal) => FieldKey::Literal(literal),
6238                    };
6239                    if *is_static {
6240                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
6241                    } else {
6242                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6243                    }
6244                }
6245                ClassElement::StaticBlock {
6246                    body, body_start, ..
6247                } => static_items.push(StaticInitItem::Block {
6248                    body,
6249                    body_start: *body_start,
6250                }),
6251            }
6252        }
6253
6254        // Now that every member has its slot, the constructor can have the next one and the
6255        // `fclosure` above can name it.
6256        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6257        match self.state().insns.get_mut(ctor_insn) {
6258            Some(Insn::Fixed { operands, .. }) => {
6259                operands[0] = Op::Const(ctor_index);
6260            }
6261            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6262            // loudly beats emitting a `fclosure` of slot 4294967295.
6263            _ => {
6264                return Err(SyntaxError::new(
6265                    "the class constructor's fclosure went missing",
6266                    class.span,
6267                ));
6268            }
6269        }
6270
6271        // The instance brand: a symbol created once on the prototype, which every instance
6272        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6273        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6274        // copy is created. The prototype is on top of the stack at this point.
6275        if plan.instance_brand {
6276            self.emit(Opcode::Dup, &[]);
6277            self.emit(Opcode::Null, &[]);
6278            self.emit(Opcode::Swap, &[]);
6279            self.emit(Opcode::AddBrand, &[]);
6280        }
6281
6282        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6283        // class has no instance fields. The constructor calls it only when it is defined.
6284        //
6285        // A class with private *methods* but no fields still needs one, because adding the
6286        // brand to each new instance is the initialiser's job.
6287        if instance_fields.is_empty() && !plan.instance_brand {
6288            self.emit(Opcode::Undefined, &[]);
6289        } else {
6290            let initialiser = self.compile_field_initialiser(
6291                &instance_fields,
6292                class.span,
6293                true,
6294                plan.instance_brand,
6295            )?;
6296            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6297            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6298            // `set_home_object` reads `obj func`, so the prototype stays where it is.
6299            self.emit(Opcode::SetHomeObject, &[]);
6300        }
6301        self.emit_var(VarAction::PutInit, "<class_fields_init>");
6302        // The prototype has done its job: every instance member is defined on it. What
6303        // is left under it is the constructor.
6304        self.emit(Opcode::Drop, &[]);
6305
6306        // The static brand, for `static #m() {}`: same opcode, but the home object is the
6307        // constructor itself, so the symbol lands on the class and the class carries it.
6308        if plan.static_brand {
6309            self.emit(Opcode::Dup, &[]);
6310            self.emit(Opcode::Dup, &[]);
6311            self.emit(Opcode::AddBrand, &[]);
6312        }
6313
6314        // The class binding is initialised *before* static fields run, so a static field
6315        // can refer to the class by name (`static y = S.x`).
6316        // `set_loc` leaves the constructor on the stack, which is what the static field
6317        // call and the outer store both consume.
6318        //
6319        // Only when there *is* such a binding: an anonymous class expression declares no
6320        // class-scope name, and asking for one by the empty string resolved to nothing —
6321        // which made `var x = class {}` assign `undefined` and put a bogus global store in
6322        // the instruction stream.
6323        if let Some(name) = &name {
6324            self.emit_var(VarAction::SetInit, name);
6325        }
6326        if !static_items.is_empty() {
6327            // The static half has no brand prologue of its own: the constructor got its
6328            // brand above, before this runs.
6329            let initialiser =
6330                self.compile_field_initialiser(&static_items, class.span, false, false)?;
6331            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6332            self.emit(Opcode::Dup, &[]);
6333            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6334            self.emit(Opcode::SetHomeObject, &[]);
6335            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6336            self.emit(Opcode::Drop, &[]);
6337        }
6338        // The body is over, and with it this class's private names.
6339        let _ = self.private_scopes.pop();
6340        self.emit_scope_leave(key);
6341        self.state().current_block = parent_block;
6342        if keep {
6343            // A class *expression* is its own value; the class-scope binding was only
6344            // ever an alias for it.
6345            return Ok(());
6346        }
6347        // A declaration stores into the binding the enclosing statement declared.
6348        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6349        Ok(())
6350    }
6351
6352    fn push_this(&mut self) {
6353        self.emit(Opcode::PushThis, &[]);
6354    }
6355
6356    /// `this`, which an arrow does not have of its own.
6357    ///
6358    /// The reference gives the enclosing function a local named `this`, initialised from
6359    /// `push_this` at the top of its body, and the arrow then reads it as a captured
6360    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6361    /// the arrow is called with none.
6362    fn this_expression(&mut self) {
6363        // In a class constructor `this` is a local: a derived constructor only gets one
6364        // when `super()` returns, and reading the raw receiver would give the *outer*
6365        // one instead.
6366        if self.cur().ctor_kind != CtorKind::None {
6367            self.emit_var(VarAction::Get, "this");
6368            return;
6369        }
6370        if !self.cur().is_arrow {
6371            self.push_this();
6372            return;
6373        }
6374        // An arrow at the **top level** of a script or module has no enclosing function,
6375        // but it still inherits `this` — the script's or module's own. Falling through to
6376        // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6377        // `var f = () => typeof this` at top level reported
6378        // `ReferenceError: 'this' is not defined` instead of `"object"`
6379        // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6380        // is the test262 case that reaches it, through a native `forEach`).
6381        //
6382        // The script state is the bottom of the stack, so it is the fallback target. Its
6383        // own `provide_this_local` then prepends the `push_this` the arrow reads.
6384        let target = self.enclosing_function().unwrap_or(0);
6385        self.state_at(target).needs_this_local = true;
6386        self.declare_at(target, "this");
6387        self.emit_var(VarAction::Get, "this");
6388    }
6389
6390    /// `new.target`, which an arrow likewise does not own.
6391    fn new_target_expression(&mut self) {
6392        if !self.cur().is_arrow {
6393            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6394            return;
6395        }
6396        if let Some(target) = self.enclosing_function() {
6397            self.state_at(target).needs_new_target_local = true;
6398            self.declare_at(target, NEW_TARGET);
6399        }
6400        self.emit_var(VarAction::Get, NEW_TARGET);
6401    }
6402
6403    /// `this.active_func`: the function `super()` resolves against.
6404    ///
6405    /// In a constructor or a method that is the function being run, so the special object
6406    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6407    /// a closure variable — see [`FnState::needs_active_func_local`].
6408    fn active_func_expression(&mut self) {
6409        if !self.cur().is_arrow {
6410            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6411            return;
6412        }
6413        if let Some(target) = self.enclosing_function() {
6414            self.state_at(target).needs_active_func_local = true;
6415            self.declare_at(target, ACTIVE_FUNC);
6416        }
6417        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6418    }
6419
6420    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6421    fn provide_active_func_local(&mut self) {
6422        let current = self.stack.len() - 1;
6423        if !self.stack[current].needs_active_func_local {
6424            return;
6425        }
6426        if !self.stack[current]
6427            .vars
6428            .iter()
6429            .any(|var| var.name == ACTIVE_FUNC)
6430        {
6431            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6432        }
6433        self.prepend_initialiser(
6434            ACTIVE_FUNC,
6435            Insn::Fixed {
6436                op: Opcode::SpecialObject,
6437                operands: vec![Op::Int(2)],
6438            },
6439        );
6440    }
6441
6442    /// Give the function a local `new.target`, for an arrow inside it to capture.
6443    fn provide_new_target_local(&mut self) {
6444        let current = self.stack.len() - 1;
6445        if !self.stack[current].needs_new_target_local {
6446            return;
6447        }
6448        if !self.stack[current]
6449            .vars
6450            .iter()
6451            .any(|var| var.name == NEW_TARGET)
6452        {
6453            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6454        }
6455        self.prepend_initialiser(
6456            NEW_TARGET,
6457            Insn::Fixed {
6458                op: Opcode::SpecialObject,
6459                operands: vec![Op::Int(3)],
6460            },
6461        );
6462    }
6463
6464    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6465    /// function.
6466    fn ensure_enclosing_arguments(&mut self) {
6467        // An arrow created in a parameter list needs the *parameter* scope's
6468        // `arguments`, not the body's: the two are separate bindings and the arrow was
6469        // born before the body existed.
6470        let from_params = self.cur().created_in_params;
6471        if let Some(target) = self.enclosing_function() {
6472            self.state_at(target).needs_arguments_local = true;
6473            if from_params {
6474                self.state_at(target).needs_param_arguments = true;
6475                // Declare it now, not at the enclosing function's `finish_current`: the
6476                // arrow resolves its own `arguments` before that runs, and a binding that
6477                // does not exist yet resolves as a global.
6478                declare_param_var_at(&mut self.stack[target], "arguments");
6479            }
6480            self.declare_at(target, "arguments");
6481        }
6482    }
6483
6484    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6485    /// rather than starting a scope of its own.
6486    /// The innermost enclosing frame that can own a lexical binding an arrow reads —
6487    /// a real function, or a **script** top level.
6488    ///
6489    /// A script is in the list because an `eval` body is compiled as one and an arrow
6490    /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
6491    /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
6492    /// a *global* lookup of `new.target`, which no frame provides — so it raised
6493    /// `ReferenceError` instead of answering the caller's value
6494    /// (`arrow-body-direct-eval-err-contains-newtarget`).
6495    fn enclosing_function(&self) -> Option<usize> {
6496        (0..self.stack.len())
6497            .rev()
6498            .find(|index| !self.stack[*index].is_arrow)
6499    }
6500
6501    fn state_at(&mut self, index: usize) -> &mut FnState {
6502        &mut self.stack[index]
6503    }
6504
6505    /// Declare a `var` binding directly in a specific frame.
6506    fn declare_at(&mut self, index: usize, name: &str) {
6507        let state = &mut self.stack[index];
6508        if state.vars.iter().any(|var| var.name == name) {
6509            return;
6510        }
6511        state.var_block.push(FUNCTION_SCOPE);
6512        state.vars.push(VarDef::var(name));
6513    }
6514
6515    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6516    /// the reference calls a `special_object` gets initialised on entry.
6517    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6518        let current = self.stack.len() - 1;
6519        let init = [
6520            producer,
6521            Insn::Var {
6522                action: VarAction::Put,
6523                name: name.to_string(),
6524                block: 0,
6525                // A prologue initialiser runs before the body proper, but it is body
6526                // code: `this` and `arguments` are provided for it, not by it.
6527                in_params: false,
6528            },
6529        ];
6530        let inserted = init.len();
6531        for (index, instruction) in init.into_iter().enumerate() {
6532            self.stack[current].insns.insert(index, instruction);
6533        }
6534        for placed in self.stack[current].labels.iter_mut().flatten() {
6535            *placed += inserted;
6536        }
6537        self.stack[current].label_since_insn = true;
6538    }
6539
6540    fn push_constant(&mut self, constant: Constant) -> u32 {
6541        let state = self.state();
6542        let index = state.cpool.len() as u32;
6543        state.cpool.push(constant);
6544        index
6545    }
6546
6547    /// Compile `a && b`, `a || b`, `a ?? b`.
6548    ///
6549    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6550    /// `a` once and jumps past everything when it is truthy, instead of falling
6551    /// into `b`'s test. The parser builds such a run left-associated —
6552    /// `((a || b) || c)` — so the operands are collected off the left spine.
6553    ///
6554    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6555    /// `||`'s label, because the inner chain really does end before `&&` begins.
6556    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6557        let mut operands = Vec::new();
6558        collect_same_operator(op, left, &mut operands);
6559        operands.push(right);
6560
6561        let end = self.new_label();
6562        // Every operand but the last decides whether the chain stops here.
6563        let last = operands.pop().expect("the right operand is always present");
6564        for operand in operands {
6565            self.expr(operand)?;
6566            self.emit(Opcode::Dup, &[]);
6567            match op {
6568                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6569                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6570                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6571                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6572                // null-ish, so the jump is taken on `false`.
6573                LogicalOp::Coalesce => {
6574                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6575                    self.emit_jump(Opcode::IfFalse, end, &[]);
6576                }
6577            }
6578            self.emit(Opcode::Drop, &[]);
6579        }
6580        self.expr(last)?;
6581        self.place_label(end);
6582        Ok(())
6583    }
6584
6585    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6586        match op {
6587            UnaryOp::Typeof => {
6588                // `typeof x` must not throw on an undeclared name.
6589                if let ExprKind::Ident(name) = &argument.kind {
6590                    self.emit_var(VarAction::GetUndef, &name.name);
6591                } else {
6592                    self.expr(argument)?;
6593                }
6594                self.emit(Opcode::Typeof, &[]);
6595            }
6596            UnaryOp::Delete => {
6597                // `delete obj.prop` really deletes, and answers whether it could.
6598                // Deleting a *binding* is always `false`: a local, an argument and a
6599                // declared global are all non-configurable, which the reference encodes
6600                // as a constant `push_false` rather than a runtime check. Only a
6601                // property access has anything to do at run time.
6602                // `delete super.x` is not a delete at all: the spec refuses it, and the
6603                // reference encodes the refusal as a `throw_error`. The receiver and the
6604                // key are still evaluated first, which is what keeps the evaluation order
6605                // of the operand intact.
6606                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6607                // nothing to delete, and a failed delete is not the same as a skipped
6608                // one. The reference emits the guards so they land on a `drop; push_true`
6609                // tail, which is what this reproduces.
6610                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6611                    && let ExprKind::Member {
6612                        object, property, ..
6613                    } = &inner.unparen().kind
6614                {
6615                    let end = self.new_label();
6616                    let done = self.new_label();
6617                    self.chain_link(object, end)?;
6618                    match property {
6619                        MemberProp::Ident(name) => self.emit(
6620                            Opcode::PushAtomValue,
6621                            &[Op::Atom(Atom::from_text(&name.name))],
6622                        ),
6623                        MemberProp::Computed(index) => self.expr(index)?,
6624                        MemberProp::Private(_) => {
6625                            return Err(SyntaxError::new(
6626                                "deleting a private field is not allowed",
6627                                argument.span,
6628                            ));
6629                        }
6630                    }
6631                    self.emit(Opcode::Delete, &[]);
6632                    self.emit_jump(Opcode::Goto, done, &[]);
6633                    self.place_label(end);
6634                    self.emit(Opcode::Drop, &[]);
6635                    self.emit(Opcode::PushTrue, &[]);
6636                    self.place_label(done);
6637                    return Ok(());
6638                }
6639                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6640                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6641                {
6642                    self.super_base();
6643                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6644                    return Ok(());
6645                }
6646                // Parentheses are transparent to `delete`: `(x)` is still a Reference to
6647                // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
6648                // does, and `delete (a().b)` still evaluates `a()`. Matching on the
6649                // unparenthesised operand is what keeps both — matching on `argument.kind`
6650                // sent every parenthesised form to the "not a Reference" arm, which cost
6651                // `delete(__variable) === false` in test262's `S12.2_A2`.
6652                match &argument.unparen().kind {
6653                    ExprKind::Member {
6654                        object, property, ..
6655                    } => {
6656                        self.expr(object)?;
6657                        match property {
6658                            MemberProp::Ident(name) => {
6659                                self.emit(
6660                                    Opcode::PushAtomValue,
6661                                    &[Op::Atom(Atom::from_text(&name.name))],
6662                                );
6663                            }
6664                            MemberProp::Computed(index) => self.expr(index)?,
6665                            MemberProp::Private(_) => {
6666                                return Err(SyntaxError::new(
6667                                    "deleting a private field is not allowed",
6668                                    argument.span,
6669                                ));
6670                            }
6671                        }
6672                        self.emit(Opcode::Delete, &[]);
6673                    }
6674                    ExprKind::Ident(name) => {
6675                        // `delete name`: a declared global, a local and an argument all
6676                        // answer `false`, but an *implicit* global (`x = 1` with no
6677                        // declaration) is a configurable property of the global object
6678                        // and really goes away. Which of those a name is only the
6679                        // resolver knows, so the decision waits for it.
6680                        let pos = self.cur().cur_pos;
6681                        self.state().insns.push(Insn::DeleteVar {
6682                            name: name.name.clone(),
6683                        });
6684                        self.state().insn_pos.push(pos);
6685                    }
6686                    // §13.5.1.2 step 2: an operand that is **not** a Reference Record
6687                    // answers `true` — there is nothing to delete, and "nothing needed
6688                    // deleting" is success. `delete !0`, `delete (1 + 2)` and
6689                    // `delete typeof 0` are all `true`, and the operand is still evaluated
6690                    // (which is why it is `Drop`ed rather than skipped:
6691                    // `delete f()` must call `f`).
6692                    //
6693                    // Answering `false` here is the C reference's old behaviour and was
6694                    // wrong in an observable way: test262's
6695                    // `dynamic-import/assignment-expression/logical-and-expr` builds a
6696                    // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
6697                    // half turned the whole `&&` into `false`, so the import asked for a
6698                    // module named "false".
6699                    _ => {
6700                        self.expr(argument)?;
6701                        self.emit(Opcode::Drop, &[]);
6702                        self.emit(Opcode::PushTrue, &[]);
6703                    }
6704                }
6705            }
6706            UnaryOp::Void => {
6707                self.expr(argument)?;
6708                self.emit(Opcode::Drop, &[]);
6709                self.emit(Opcode::Undefined, &[]);
6710            }
6711            UnaryOp::Minus => {
6712                self.expr(argument)?;
6713                self.emit(Opcode::Neg, &[]);
6714            }
6715            UnaryOp::Plus => {
6716                self.expr(argument)?;
6717                self.emit(Opcode::Plus, &[]);
6718            }
6719            UnaryOp::Not => {
6720                self.expr(argument)?;
6721                self.emit(Opcode::Lnot, &[]);
6722            }
6723            UnaryOp::BitNot => {
6724                self.expr(argument)?;
6725                self.emit(Opcode::Not, &[]);
6726            }
6727        }
6728        Ok(())
6729    }
6730
6731    /// Compile an assignment.
6732    ///
6733    /// Three operator families, three shapes:
6734    ///
6735    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6736    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6737    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6738    ///   the pair it wants and leaves a copy on top.
6739    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6740    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6741    ///   index) underneath the value precisely so the store can follow.
6742    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6743    ///   right-hand side. The test *keeps* the current value and skips the store
6744    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6745    ///   `a` is already truthy.
6746    fn assign(
6747        &mut self,
6748        op: AssignOp,
6749        target: &Pattern,
6750        value: &Expr,
6751        discard: bool,
6752    ) -> Result<(), SyntaxError> {
6753        // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
6754        // about, so it is set only when this assignment *is* that expression.
6755        let keep = !discard;
6756        match &target.kind {
6757            PatternKind::Ident(name) => {
6758                // A *simple* store is blamed on the identifier, not on the `=`: a
6759                // strict-mode `not_def = 1` raises when the name is written, which the
6760                // reference reports at the name's column. A compound store is blamed on
6761                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6762                // which the reference reports at the `+=`), so only the simple case
6763                // moves the position.
6764                let saved = self.cur().cur_pos;
6765                let name_pos = Some(name.span.start);
6766                if matches!(op, AssignOp::Assign) {
6767                    self.state().cur_pos = name_pos;
6768                }
6769                // A *compound* store reads the binding before it combines, and that read
6770                // is blamed on the identifier: `not_def += 2` fails while reading
6771                // `not_def`, so the position is the name's, not the `+=`'s. The
6772                // combination that follows is blamed on the operator, which is why
6773                // `cur_pos` is put back to the operator position before it is emitted.
6774                self.state().cur_pos = name_pos;
6775                match op {
6776                    AssignOp::Assign => {
6777                        self.expr(value)?;
6778                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6779                        // A discarded store to a *slot* consumes its value, so no copy
6780                        // is needed. A global store goes through `put_var`, which the
6781                        // reference always pairs with a `dup` — matching it keeps the
6782                        // bytecode identical. Getting this wrong is not only an extra
6783                        // instruction: a stray copy gives the peephole a chance to fold
6784                        // the store into an unrelated later read.
6785                        let slot = self.is_slot(&name.name);
6786                        if keep || !slot {
6787                            self.emit(Opcode::Dup, &[]);
6788                        }
6789                        self.state().no_value = !keep && slot;
6790                        self.emit_var(VarAction::Put, &name.name);
6791                    }
6792                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6793                        let end = self.new_label();
6794                        self.emit_var(VarAction::Get, &name.name);
6795                        self.state().cur_pos = saved;
6796                        self.emit(Opcode::Dup, &[]);
6797                        self.emit_logical_test(op);
6798                        self.emit_jump(logical_jump(op), end, &[]);
6799                        self.emit(Opcode::Drop, &[]);
6800                        self.expr(value)?;
6801                        self.emit(Opcode::Dup, &[]);
6802                        self.emit_var(VarAction::Put, &name.name);
6803                        self.place_label(end);
6804                    }
6805                    _ => {
6806                        self.emit_var(VarAction::Get, &name.name);
6807                        self.expr(value)?;
6808                        self.state().cur_pos = saved;
6809                        self.emit(compound_opcode(op), &[]);
6810                        self.emit(Opcode::Dup, &[]);
6811                        self.emit_var(VarAction::Put, &name.name);
6812                    }
6813                }
6814                self.state().cur_pos = saved;
6815                Ok(())
6816            }
6817            PatternKind::Member(member) => {
6818                // `super.x = v` is not a store through a value: it starts at the home
6819                // object's prototype but writes to `this`, so it goes through
6820                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6821                // and value are handed over together.
6822                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6823                    return self.assign_super(member, op, value);
6824                }
6825                // A store is blamed on the selector punctuator (`.` or `[`), the same
6826                // token a load is blamed on — the reference records `put_field obj.a`
6827                // at the `.`, so a setter that throws reports that column and not the
6828                // `=` of the assignment it sits in. The inner expressions restore their
6829                // own positions, so the selector's sticks for the store instructions.
6830                let saved = self.cur().cur_pos;
6831                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6832                self.expr(&member.object)?;
6833                match &member.property {
6834                    MemberProp::Ident(property) => {
6835                        let atom = Atom::from_text(&property.name);
6836                        match op {
6837                            AssignOp::Assign => {
6838                                self.expr(value)?;
6839                                // `put_field` consumes the object and the value, so
6840                                // without `insert2` nothing is left over for the
6841                                // statement to drop.
6842                                self.state().no_value = !keep;
6843                                if keep {
6844                                    self.emit(Opcode::Insert2, &[]);
6845                                }
6846                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6847                            }
6848                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6849                                // `get_field2` leaves the object under the value, so
6850                                // the keep path has an object to dispose of. The store
6851                                // path must jump *over* that cleanup: falling into it
6852                                // would `nip` a stack that only holds the value.
6853                                let (keep_label, end) = (self.new_label(), self.new_label());
6854                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6855                                self.emit(Opcode::Dup, &[]);
6856                                self.emit_logical_test(op);
6857                                self.emit_jump(logical_jump(op), keep_label, &[]);
6858                                self.emit(Opcode::Drop, &[]);
6859                                self.expr(value)?;
6860                                self.emit(Opcode::Insert2, &[]);
6861                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6862                                self.emit_jump(Opcode::Goto, end, &[]);
6863                                self.place_label(keep_label);
6864                                self.emit(Opcode::Nip, &[]);
6865                                self.place_label(end);
6866                            }
6867                            _ => {
6868                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6869                                self.expr(value)?;
6870                                self.emit(compound_opcode(op), &[]);
6871                                self.state().no_value = !keep;
6872                                if keep {
6873                                    self.emit(Opcode::Insert2, &[]);
6874                                }
6875                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6876                            }
6877                        }
6878                    }
6879                    MemberProp::Computed(index) => {
6880                        self.expr(index)?;
6881                        match op {
6882                            AssignOp::Assign => {
6883                                self.expr(value)?;
6884                                self.state().no_value = !keep;
6885                                if keep {
6886                                    self.emit(Opcode::Insert3, &[]);
6887                                }
6888                                self.emit(Opcode::PutArrayEl, &[]);
6889                            }
6890                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6891                                let (keep_label, end) = (self.new_label(), self.new_label());
6892                                self.emit(Opcode::GetArrayEl3, &[]);
6893                                self.emit(Opcode::Dup, &[]);
6894                                self.emit_logical_test(op);
6895                                self.emit_jump(logical_jump(op), keep_label, &[]);
6896                                self.emit(Opcode::Drop, &[]);
6897                                self.expr(value)?;
6898                                self.emit(Opcode::Insert3, &[]);
6899                                self.emit(Opcode::PutArrayEl, &[]);
6900                                self.emit_jump(Opcode::Goto, end, &[]);
6901                                self.place_label(keep_label);
6902                                // Both the object and the index are left over.
6903                                self.emit(Opcode::Nip, &[]);
6904                                self.emit(Opcode::Nip, &[]);
6905                                self.place_label(end);
6906                            }
6907                            _ => {
6908                                self.emit(Opcode::GetArrayEl3, &[]);
6909                                self.expr(value)?;
6910                                self.emit(compound_opcode(op), &[]);
6911                                self.state().no_value = !keep;
6912                                if keep {
6913                                    self.emit(Opcode::Insert3, &[]);
6914                                }
6915                                self.emit(Opcode::PutArrayEl, &[]);
6916                            }
6917                        }
6918                    }
6919                    MemberProp::Private(name) => {
6920                        // `obj value` is on the stack, and every private store wants exactly
6921                        // that. A top-level private name cannot be assigned (the parser rejects
6922                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6923                        //
6924                        // The reference emits `insert2` whether or not the value is wanted,
6925                        // so this does too: the copy left behind is the assignment expression's
6926                        // value, and a discarded one is simply never read.
6927                        let binding = format!("#{}", name.name);
6928                        let (kind, setter) = self.private_use(&binding, member.span)?;
6929                        match op {
6930                            AssignOp::Assign => {
6931                                self.expr(value)?;
6932                                if keep {
6933                                    self.emit(Opcode::Insert2, &[]);
6934                                }
6935                                self.private_store(&binding, kind, setter.as_deref())?;
6936                                self.state().no_value = !keep;
6937                            }
6938                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6939                                let (keep_label, end) = (self.new_label(), self.new_label());
6940                                self.emit(Opcode::Dup, &[]);
6941                                self.private_load(&binding, kind, member.span)?;
6942                                self.emit(Opcode::Dup, &[]);
6943                                self.emit_logical_test(op);
6944                                self.emit_jump(logical_jump(op), keep_label, &[]);
6945                                self.emit(Opcode::Drop, &[]);
6946                                self.expr(value)?;
6947                                self.emit(Opcode::Insert2, &[]);
6948                                self.private_store(&binding, kind, setter.as_deref())?;
6949                                self.emit_jump(Opcode::Goto, end, &[]);
6950                                self.place_label(keep_label);
6951                                self.emit(Opcode::Nip, &[]);
6952                                self.place_label(end);
6953                            }
6954                            _ => {
6955                                self.emit(Opcode::Dup, &[]);
6956                                self.private_load(&binding, kind, member.span)?;
6957                                self.expr(value)?;
6958                                self.emit(compound_opcode(op), &[]);
6959                                self.emit(Opcode::Insert2, &[]);
6960                                self.private_store(&binding, kind, setter.as_deref())?;
6961                            }
6962                        }
6963                    }
6964                }
6965                self.state().cur_pos = saved;
6966                Ok(())
6967            }
6968            // A destructuring assignment: the right-hand side is the expression's own
6969            // value, so it is evaluated once and kept under the pattern's stores.
6970            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6971                self.expr(value)?;
6972                if keep {
6973                    self.emit(Opcode::Dup, &[]);
6974                }
6975                self.destructure(target, None)?;
6976                self.state().no_value = !keep;
6977                Ok(())
6978            }
6979            _ => Err(SyntaxError::new(
6980                "this assignment target is not supported by the compiler yet",
6981                target.span,
6982            )),
6983        }
6984    }
6985
6986    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6987    ///
6988    /// The stack has to carry four values — receiver, prototype, key, value — because
6989    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6990    /// the prototype run with `this`, and the key has to survive until the store, which is
6991    /// why a compound form converts it to a property key once and `dup3`s rather than
6992    /// evaluating it twice.
6993    fn assign_super(
6994        &mut self,
6995        member: &MemberPattern,
6996        op: AssignOp,
6997        value: &Expr,
6998    ) -> Result<(), SyntaxError> {
6999        let saved = self.cur().cur_pos;
7000        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7001        self.super_base();
7002        match &member.property {
7003            MemberProp::Ident(property) => self.emit(
7004                Opcode::PushAtomValue,
7005                &[Op::Atom(Atom::from_text(&property.name))],
7006            ),
7007            MemberProp::Computed(index) => self.expr(index)?,
7008            MemberProp::Private(_) => {
7009                return Err(SyntaxError::new(
7010                    "private fields are not supported by the compiler yet",
7011                    member.span,
7012                ));
7013            }
7014        }
7015        match op {
7016            AssignOp::Assign => {
7017                // The key is only converted once, by `put_super_value` itself, so a
7018                // computed key's `toString` runs exactly once.
7019                self.expr(value)?;
7020                self.emit(Opcode::Insert4, &[]);
7021                self.emit(Opcode::PutSuperValue, &[]);
7022            }
7023            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7024                let (keep_label, end) = (self.new_label(), self.new_label());
7025                self.emit(Opcode::ToPropkey, &[]);
7026                self.emit(Opcode::Dup3, &[]);
7027                self.emit(Opcode::GetSuperValue, &[]);
7028                self.emit(Opcode::Dup, &[]);
7029                self.emit_logical_test(op);
7030                self.emit_jump(logical_jump(op), keep_label, &[]);
7031                self.emit(Opcode::Drop, &[]);
7032                self.expr(value)?;
7033                self.emit(Opcode::Insert4, &[]);
7034                self.emit(Opcode::PutSuperValue, &[]);
7035                self.emit_jump(Opcode::Goto, end, &[]);
7036                self.place_label(keep_label);
7037                // The prototype and the key are still under the value that was read.
7038                self.emit(Opcode::Nip, &[]);
7039                self.emit(Opcode::Nip, &[]);
7040                self.emit(Opcode::Nip, &[]);
7041                self.place_label(end);
7042            }
7043            _ => {
7044                self.emit(Opcode::ToPropkey, &[]);
7045                self.emit(Opcode::Dup3, &[]);
7046                self.emit(Opcode::GetSuperValue, &[]);
7047                self.expr(value)?;
7048                self.emit(compound_opcode(op), &[]);
7049                self.emit(Opcode::Insert4, &[]);
7050                self.emit(Opcode::PutSuperValue, &[]);
7051            }
7052        }
7053        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7054        // is still on the stack when the store finishes, and the expression statement is
7055        // what disposes of it — the same arrangement as `put_field`, reached from the other
7056        // side: there the store consumes the value (`no_value`), here it leaves it
7057        // (`keep` already false, so nothing tells the statement otherwise).
7058        self.state().cur_pos = saved;
7059        Ok(())
7060    }
7061
7062    /// The test a logical assignment applies to the current value.
7063    ///
7064    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7065    /// assign, while `0 ||= b` must not.
7066    fn emit_logical_test(&mut self, op: AssignOp) {
7067        if op == AssignOp::Coalesce {
7068            self.emit(Opcode::IsUndefinedOrNull, &[]);
7069        }
7070    }
7071
7072    /// The private name `#name` this use site resolves against.
7073    ///
7074    /// The parser has already rejected a name no enclosing class declares, so a miss here
7075    /// means the compiler lost track of a class scope — which is worth a real error rather
7076    /// than an `unwrap`.
7077    fn private_use(
7078        &self,
7079        binding: &str,
7080        span: Span,
7081    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7082        ClassPlan::find(self, binding)
7083            .map(|use_| (use_.kind, use_.setter.clone()))
7084            .ok_or_else(|| {
7085                SyntaxError::new(
7086                    format!("the private name '{binding}' is out of scope here"),
7087                    span,
7088                )
7089            })
7090    }
7091
7092    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7093    ///
7094    /// The three readable kinds take three different instructions, because a private name
7095    /// holds three different things — a symbol, a method function, a getter function — and
7096    /// only the first one is a property read at all.
7097    fn private_load(
7098        &mut self,
7099        binding: &str,
7100        kind: PrivateKind,
7101        span: Span,
7102    ) -> Result<(), SyntaxError> {
7103        match kind {
7104            PrivateKind::Field => {
7105                self.emit_var(VarAction::Get, binding);
7106                self.emit(Opcode::GetPrivateField, &[]);
7107            }
7108            PrivateKind::Method => {
7109                self.emit_var(VarAction::Get, binding);
7110                self.emit(Opcode::CheckBrand, &[]);
7111                // `check_brand` reads `obj func` and leaves both; the method itself is what
7112                // `this.#m` evaluates to.
7113                self.emit(Opcode::Nip, &[]);
7114            }
7115            PrivateKind::Getter => {
7116                self.emit_var(VarAction::Get, binding);
7117                self.emit(Opcode::CheckBrand, &[]);
7118                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7119            }
7120            // `#a` is declared but never filled when only a setter exists, so reading it is
7121            // the same refusal as assigning to a `const`. The reference reports it with the
7122            // generic read-only wording and leaves the better message as a `XXX`.
7123            PrivateKind::Setter => self.emit(
7124                Opcode::ThrowError,
7125                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7126            ),
7127        }
7128        let _ = span;
7129        Ok(())
7130    }
7131
7132    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7133    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7134        match kind {
7135            // A method *is* the callee, so only the check goes in between.
7136            PrivateKind::Method => {
7137                self.emit_var(VarAction::Get, binding);
7138                self.emit(Opcode::CheckBrand, &[]);
7139            }
7140            _ => self.private_load(binding, kind, Span::default())?,
7141        }
7142        Ok(())
7143    }
7144
7145    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7146    /// wanted back.
7147    ///
7148    /// A getter/setter pair is a *method call*, not a property store: the reference reads
7149    /// the setter out of its own binding and calls it with the receiver, which is why the
7150    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7151    /// keeps the assignment's value for an expression context.
7152    fn private_store(
7153        &mut self,
7154        binding: &str,
7155        kind: PrivateKind,
7156        setter: Option<&str>,
7157    ) -> Result<(), SyntaxError> {
7158        match kind {
7159            PrivateKind::Field => {
7160                self.emit_var(VarAction::Get, binding);
7161                self.emit(Opcode::PutPrivateField, &[]);
7162            }
7163            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7164                Some(setter) => {
7165                    self.emit_var(VarAction::Get, setter);
7166                    // `obj func value` -> `value obj func` for the check, and back again for
7167                    // the call, which wants `obj func arg`.
7168                    self.emit(Opcode::Swap, &[]);
7169                    self.emit(Opcode::Rot3r, &[]);
7170                    self.emit(Opcode::CheckBrand, &[]);
7171                    self.emit(Opcode::Rot3l, &[]);
7172                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7173                    // The setter's return value is discarded; the assignment's own value is
7174                    // whatever the caller left underneath.
7175                    self.emit(Opcode::Drop, &[]);
7176                }
7177                None => self.emit(
7178                    Opcode::ThrowError,
7179                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7180                ),
7181            },
7182        }
7183        Ok(())
7184    }
7185
7186    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7187        let instruction = match (op, prefix) {
7188            (UpdateOp::Increment, true) => Opcode::Inc,
7189            (UpdateOp::Increment, false) => Opcode::PostInc,
7190            (UpdateOp::Decrement, true) => Opcode::Dec,
7191            (UpdateOp::Decrement, false) => Opcode::PostDec,
7192        };
7193        if let ExprKind::Member {
7194            object,
7195            property,
7196            optional: _,
7197        } = &argument.kind
7198        {
7199            // `o.x++` needs the receiver twice, so the last link is read with the
7200            // `get_*2`/`get_*3` form that keeps it, and the update is written back
7201            // with `put_field`/`put_array_el`. The reordering in between is what puts
7202            // the old value below the receiver for a postfix update and the new one
7203            // above it for a prefix one:
7204            //
7205            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7206            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
7207            //
7208            // This mirrors the reference instruction for instruction.
7209            self.expr(object)?;
7210            match property {
7211                MemberProp::Ident(name) => {
7212                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7213                    self.emit(instruction, &[]);
7214                    self.emit(
7215                        if prefix {
7216                            Opcode::Insert2
7217                        } else {
7218                            Opcode::Perm3
7219                        },
7220                        &[],
7221                    );
7222                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7223                }
7224                MemberProp::Computed(index) => {
7225                    self.expr(index)?;
7226                    self.emit(Opcode::GetArrayEl3, &[]);
7227                    self.emit(instruction, &[]);
7228                    self.emit(
7229                        if prefix {
7230                            Opcode::Insert3
7231                        } else {
7232                            Opcode::Perm4
7233                        },
7234                        &[],
7235                    );
7236                    self.emit(Opcode::PutArrayEl, &[]);
7237                }
7238                MemberProp::Private(name) => {
7239                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7240                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7241                    // `perm3` -> `old obj new` -> store.
7242                    let binding = format!("#{}", name.name);
7243                    let (kind, setter) = self.private_use(&binding, argument.span)?;
7244                    self.emit(Opcode::Dup, &[]);
7245                    self.private_load(&binding, kind, argument.span)?;
7246                    self.emit(instruction, &[]);
7247                    self.emit(
7248                        if prefix {
7249                            Opcode::Insert2
7250                        } else {
7251                            Opcode::Perm3
7252                        },
7253                        &[],
7254                    );
7255                    self.private_store(&binding, kind, setter.as_deref())?;
7256                }
7257            }
7258            return Ok(());
7259        }
7260        let ExprKind::Ident(name) = &argument.kind else {
7261            return Err(SyntaxError::new(
7262                "increment of a non-variable is not supported by the compiler yet",
7263                argument.span,
7264            ));
7265        };
7266        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7267        // reference's `inc_loc` folds those three into one, but it does so only in some
7268        // positions (a `for` update and not a bare statement, and never for a lexical
7269        // binding), so emitting it unconditionally would move *away* from its output.
7270        // The instruction is equivalent either way; matching the reference matters more
7271        // than saving two instructions.
7272        let _ = !std::mem::take(&mut self.state().discard_value);
7273        self.emit_var(VarAction::Get, &name.name);
7274        self.emit(instruction, &[]);
7275        if prefix {
7276            self.emit(Opcode::Dup, &[]);
7277        }
7278        self.emit_var(VarAction::Put, &name.name);
7279        Ok(())
7280    }
7281
7282    /// Compile an array literal.
7283    ///
7284    /// The reference splits this into three phases, and the split is load-bearing
7285    /// rather than an optimisation detail:
7286    ///
7287    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7288    ///    the array in one instruction.
7289    /// 2. **Everything up to the first spread** is appended with explicit indices
7290    ///    (`define_field <index>`), because a hole has no element to pass to
7291    ///    `array_from`. A hole here is what makes `length` need fixing up: an
7292    ///    explicit index does not extend the array the way a pushed element does.
7293    /// 3. **From the first spread on** the index lives on the stack, so `append` and
7294    ///    `define_array_el` can consume it and `inc` advances it.
7295    ///
7296    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7297    /// forces phase 2, and `[...a]` forces phase 3.
7298    fn array_literal(
7299        &mut self,
7300        elements: &[Option<ArrayElement>],
7301        span: Span,
7302    ) -> Result<(), SyntaxError> {
7303        let _ = span;
7304        let mut index: u32 = 0;
7305        let mut cursor = 0usize;
7306
7307        // Phase 1: a leading run of plain elements, at most 32 of them.
7308        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7309            if index >= 32 {
7310                break;
7311            }
7312            self.expr(element)?;
7313            index += 1;
7314            cursor += 1;
7315        }
7316        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7317
7318        // Phase 2: explicit indices, up to the first spread.
7319        let mut need_length = false;
7320        while let Some(element) = elements.get(cursor) {
7321            if matches!(element, Some(ArrayElement::Spread(_))) {
7322                break;
7323            }
7324            need_length = true;
7325            if let Some(ArrayElement::Expr(expression)) = element {
7326                self.expr(expression)?;
7327                self.emit_define_index(index);
7328                need_length = false;
7329            }
7330            index += 1;
7331            cursor += 1;
7332        }
7333
7334        if cursor >= elements.len() {
7335            if need_length {
7336                // `define_field` cannot set `length`, which is not configurable.
7337                self.emit(Opcode::Dup, &[]);
7338                self.push_number(index as f64);
7339                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7340            }
7341            return Ok(());
7342        }
7343
7344        // Phase 3: the index moves onto the stack for the spreading tail.
7345        //
7346        // `need_length` deliberately carries over from phase 2: a hole before the
7347        // first spread still has to be reflected in `length`, and only the final
7348        // check can do it because the array is not finished until the tail is
7349        // appended.
7350        self.push_number(index as f64);
7351        while let Some(element) = elements.get(cursor) {
7352            match element {
7353                Some(ArrayElement::Spread(expression)) => {
7354                    // `append` copies an iterable and leaves the next index behind,
7355                    // so no `inc` is needed here.
7356                    self.expr(spread_argument(expression))?;
7357                    self.emit(Opcode::Append, &[]);
7358                }
7359                None | Some(ArrayElement::Expr(_)) => {
7360                    need_length = true;
7361                    if let Some(ArrayElement::Expr(expression)) = element {
7362                        self.expr(expression)?;
7363                        self.emit(Opcode::DefineArrayEl, &[]);
7364                        need_length = false;
7365                    }
7366                    self.emit(Opcode::Inc, &[]);
7367                }
7368            }
7369            cursor += 1;
7370        }
7371        if need_length {
7372            self.emit(Opcode::Dup1, &[]);
7373            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7374        } else {
7375            self.emit(Opcode::Drop, &[]);
7376        }
7377        Ok(())
7378    }
7379
7380    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7381    fn emit_define_index(&mut self, index: u32) {
7382        self.emit(
7383            Opcode::DefineField,
7384            &[Op::Atom(Atom::from_text(&index.to_string()))],
7385        );
7386    }
7387
7388    // -- functions ---------------------------------------------------------
7389
7390    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7391        self.compile_function_with_name(func, false)
7392    }
7393
7394    /// Compile a function, recording whether it is a *named function expression*.
7395    ///
7396    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7397    /// must not leak outside. The reference does that by declaring `g` as a local of
7398    /// the function itself and initialising it with `special_object 2` (the current
7399    /// function), which is why this has to be known at compile time.
7400    fn compile_function_with_name(
7401        &mut self,
7402        func: &ast::Function,
7403        is_expression: bool,
7404    ) -> Result<CompiledFunction, SyntaxError> {
7405        let kind = match (func.is_generator, func.is_async) {
7406            (false, false) => FunctionKind::Normal,
7407            (true, false) => FunctionKind::Generator,
7408            (false, true) => FunctionKind::Async,
7409            (true, true) => FunctionKind::AsyncGenerator,
7410        };
7411        let mut state = FnState::new(
7412            func.name
7413                .as_ref()
7414                .map(|n| n.name.clone())
7415                .unwrap_or_default(),
7416            kind,
7417        );
7418        // The function's own mode, recorded by the parser. Inheriting the enclosing
7419        // function's instead let a nested `"use strict"` directive be ignored, so the
7420        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7421        state.strict = func.strict;
7422        // A function defined inside a `with` block keeps seeing that object: the guard
7423        // chain names the enclosing `<with>` locals, which resolve outward into closure
7424        // variables exactly like any other captured binding.
7425        state.with_names = self.cur().with_names.clone();
7426        state.is_arrow = func.is_arrow;
7427        state.created_in_block = self.cur().current_block;
7428        // A default anywhere in the parameter list is what gives the function two
7429        // variable environments. The reference decides this the same way: it scans the
7430        // parenthesis for a top-level `=`, so a destructured name without a default
7431        // stays a plain function-scope binding.
7432        state.in_params = false;
7433        // The reference scans the parenthesis for *any* `=`, including one nested inside
7434        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7435        // parameter itself carries no initialiser.
7436        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7437        // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7438        // flag above this looks at the *shape* of each parameter, not just for `=`.
7439        state.simple_parameter_list = func
7440            .params
7441            .iter()
7442            .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7443        // A function born inside a parameter list inherits the prohibition: it must not
7444        // see the body bindings of the function it was created in.
7445        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7446        // A class constructor knows what it is only because the class told it.
7447        if let Some(kind) = self.cur().class_ctor_pending {
7448            state.ctor_kind = kind;
7449        }
7450        // A named *expression* binds its own name; a declaration's name is already
7451        // bound in the enclosing scope.
7452        state.self_name = if is_expression && !func.is_arrow {
7453            func.name.as_ref().map(|n| n.name.clone())
7454        } else {
7455            None
7456        };
7457        // Keep the written range so `Function.prototype.toString` can answer with the
7458        // original text rather than `[native code]`.
7459        //
7460        // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7461        // accessor and generator prefixes, and for a method it must not include the name
7462        // or a leading `static`. `params_span` is exactly that boundary.
7463        // A *method* keeps the old `[native code]` answer: its reported text is defined
7464        // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7465        // the comments in between kept verbatim), and reconstructing that from a byte
7466        // span got it wrong in more cases than it got right. A plain function and an
7467        // arrow are the shapes libraries actually introspect, and those are exact.
7468        // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
7469        // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
7470        // so the same slice works for every form. (`Params_span` is the boundary that
7471        // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
7472        // `source_span` is set only where the reported text is not the function's own
7473        // range — a class's constructor reports the whole class definition.
7474        let reported = func.source_span.unwrap_or(func.span);
7475        state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
7476        state.line = func.span.start.line;
7477        state.column = func.span.start.column;
7478        // A function body has no hidden `<ret>` local; the value comes back on
7479        // the stack. Only a script keeps one.
7480        // Parameters are positional, so even a pattern occupies one argument slot. A
7481        // simple name is that slot itself; anything else (a pattern, a default, a rest
7482        // parameter) takes an anonymous slot and is unpicked into locals at the top of
7483        // the body, which is the only way one argument can bind several names.
7484        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7485        // `.length` stops at the first parameter that can be substituted: a default
7486        // fills a missing argument in, and a rest parameter absorbs the rest.
7487        let mut defined_args = func.params.len() as u32;
7488        for (index, param) in func.params.iter().enumerate() {
7489            match simple_parameter(param) {
7490                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7491                None => {
7492                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7493                    prologue.push((index, param.clone()));
7494                }
7495            }
7496        }
7497        // A default anywhere before the end also ends the count, which the loop above
7498        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7499        for (position, param) in func.params.iter().enumerate() {
7500            if matches!(
7501                param.kind,
7502                PatternKind::Assign { .. } | PatternKind::Rest(_)
7503            ) {
7504                defined_args = position as u32;
7505                break;
7506            }
7507        }
7508        state.defined_args = defined_args;
7509        state.param_prologue = prologue;
7510        let depth = self.stack.len();
7511        self.stack.push(state);
7512        let result = self.compile_function_body(func);
7513        if result.is_err() {
7514            // A failed compile must not leave its `FnState` behind. Every caller
7515            // reads `self.state()` as "the function being compiled", so a leftover
7516            // frame silently retargets all later bookkeeping at a dead function.
7517            self.stack.truncate(depth);
7518        }
7519        result
7520    }
7521
7522    /// The body of a function, with its frame already pushed.
7523    fn compile_function_body(
7524        &mut self,
7525        func: &ast::Function,
7526    ) -> Result<CompiledFunction, SyntaxError> {
7527        let body_key = func.params_span.end.offset as u64;
7528        // Where the body begins, in source order. The runtime needs this to tell a
7529        // closure created by a default expression from one the body creates — the two see
7530        // different variable environments — and a bytecode offset would not survive the
7531        // instruction shuffling that building the frame does. Positions are in source
7532        // order, so a comparison answers it.
7533        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7534        self.push_block(body_key, NO_PARENT);
7535        self.state().body_block = body_key;
7536        // An arrow with an expression body has no statements; the expression is
7537        // its `return`. Building the statement here keeps one code path below, and
7538        // matters for correctness beyond convenience: returning early with the new
7539        // `FnState` still on the stack would leave the compiler looking at the
7540        // wrong function, which surfaces as an unrelated underflow later.
7541        let concise = match &func.body {
7542            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7543                StmtKind::Return(Some(Box::new((**value).clone()))),
7544                value.span,
7545            )),
7546            js_parse::ast::FunctionBody::Block(_) => None,
7547        };
7548        let body: &[Stmt] = match &concise {
7549            Some(stmt) => std::slice::from_ref(stmt),
7550            None => func
7551                .body
7552                .statements()
7553                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7554        };
7555        let prologue = std::mem::take(&mut self.state().param_prologue);
7556        let has_param_scope = self.cur().has_parameter_expressions;
7557        // The parameter scope's own bindings, declared in source order.
7558        //
7559        // With parameter expressions the list gets a variable environment of its own, and
7560        // every name it binds is a `let` there. That is what puts the *list* in the
7561        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7562        // and `function f(x = y, y){}` does the same, where a single shared environment
7563        // would answer `undefined` to both.
7564        if has_param_scope {
7565            let mut declared: Vec<String> = Vec::new();
7566            for param in &func.params {
7567                let mut names = Vec::new();
7568                param.bound_names(&mut names);
7569                for name in names {
7570                    if declared.contains(&name.name) {
7571                        continue;
7572                    }
7573                    declared.push(name.name.clone());
7574                    self.declare_param_binding(&name.name);
7575                }
7576            }
7577        }
7578        // A pattern parameter binds its names as function-scope locals, so they have to
7579        // exist — and be unpicked from the argument — before the body runs. With a
7580        // parameter scope these are the *second* environment: the pattern fills the
7581        // parameter's copy, and the body's binding is filled from it afterwards.
7582        for (_, pattern) in &prologue {
7583            let mut names = Vec::new();
7584            pattern.bound_names(&mut names);
7585            for name in names {
7586                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7587            }
7588        }
7589        self.hoist(body, body_key)?;
7590        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7591        // a base constructor takes the receiver, a derived one starts in the dead zone
7592        // because only `super()` may produce it.
7593        match self.cur().ctor_kind {
7594            CtorKind::None => {}
7595            CtorKind::Base => {
7596                self.begin_this_local();
7597                self.emit(Opcode::CheckCtor, &[]);
7598                // Instance fields are installed at the top of a base constructor's body,
7599                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7600                // `1`. This used to be emitted at the *tail*, which made every field read
7601                // `undefined` inside the constructor that declared it.
7602                self.call_field_initialiser();
7603            }
7604            CtorKind::Derived => {
7605                self.declare("this", VarDef::lexical("this"));
7606                let slot = self.cur().vars.len() as u32 - 1;
7607                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7608                self.emit(Opcode::CheckCtor, &[]);
7609            }
7610        }
7611        // Entering the parameter list: everything it binds starts in the dead zone.
7612        // The order is the reference's — it walks the scope chain, which is prepended, so
7613        // the bindings come out newest first.
7614        for name in self.param_binding_names().into_iter().rev() {
7615            if let Some(slot) = self.param_binding_slot(&name) {
7616                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7617            }
7618        }
7619        // The whole parameter list is one scope, and nothing in the body exists yet, so
7620        // every name it mentions resolves against the parameter bindings and outward.
7621        self.state().in_params = has_param_scope;
7622        for (index, param) in func.params.iter().enumerate() {
7623            if let Some(pattern) = prologue_pattern(&prologue, index) {
7624                // A destructuring parameter *initialises* its bindings: with a parameter
7625                // scope they are the list's own `let`s, which is why the stores skip the
7626                // dead-zone check, and why the reference reads their properties with
7627                // `get_field2` — a `let` needs no reference.
7628                let kind = if has_param_scope {
7629                    VarDeclKind::Let
7630                } else {
7631                    VarDeclKind::Var
7632                };
7633                match &pattern.kind {
7634                    // `...rest` collects what is left rather than reading one slot.
7635                    PatternKind::Rest(inner) => {
7636                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7637                        self.destructure(inner, Some(kind))?;
7638                    }
7639                    _ => {
7640                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7641                        self.destructure(pattern, Some(kind))?;
7642                    }
7643                }
7644                continue;
7645            }
7646            // A plain name binds straight from its argument slot. With a parameter scope
7647            // the slot is also copied into the parameter binding, which is what a later
7648            // default (or a closure made among the defaults) reads.
7649            let Some(name) = simple_parameter(param) else {
7650                continue;
7651            };
7652            let target = self.param_binding_slot(&name.name);
7653            if matches!(param.kind, PatternKind::Rest(_)) {
7654                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7655                if let Some(slot) = target {
7656                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7657                }
7658                // `put_arg` rather than `set_arg`: the array is the last thing on the
7659                // stack and nothing keeps it. Named by hand because a name in the
7660                // parameter list resolves to the parameter binding, and this store has to
7661                // reach the *argument* — that is what the body reads.
7662                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7663                continue;
7664            }
7665            if let PatternKind::Assign { default, .. } = &param.kind {
7666                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7667                let has_value = self.new_label();
7668                self.emit(Opcode::Dup, &[]);
7669                self.emit(Opcode::IsUndefined, &[]);
7670                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7671                self.emit(Opcode::Drop, &[]);
7672                self.expr(default)?;
7673                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7674                // The argument slot keeps the substituted value, because the *body* reads
7675                // the slot rather than the parameter binding — so this store is named
7676                // explicitly, like the rest parameter's.
7677                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7678                self.place_label(has_value);
7679                if let Some(slot) = target {
7680                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7681                }
7682                continue;
7683            }
7684            if let Some(slot) = target {
7685                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7686                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7687            }
7688        }
7689        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7690        // body reads its argument slot, and the list kept the two in step. A name a
7691        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7692        // from the parameter's copy — and *that* is why an assignment inside a default
7693        // does not reach the body.
7694        if has_param_scope {
7695            for (_, pattern) in &prologue {
7696                let mut names = Vec::new();
7697                pattern.bound_names(&mut names);
7698                for name in names {
7699                    let Some(slot) = self.param_binding_slot(&name.name) else {
7700                        continue;
7701                    };
7702                    let Some(body) = self.body_var_slot(&name.name) else {
7703                        continue;
7704                    };
7705                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7706                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7707                }
7708            }
7709        }
7710        // The parameter list is over; from here on a direct `eval` belongs to the body.
7711        self.state().in_params = false;
7712        // Entering the body's own scope comes *after* the parameter list: the body's
7713        // `let`s are not in existence while the defaults run, and the reference emits
7714        // their `set_loc_uninitialized` only once the parameters are bound.
7715        self.emit_scope_enter(body_key);
7716        // A generator starts suspended: `initial_yield` parks the body so that creating one
7717        // runs no body code until the first `next()`.
7718        //
7719        // It comes *after* the parameter unpacking, not before, because a parameter
7720        // initialiser is not body code — `function* g(a = sideEffect())` must run
7721        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7722        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7723        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7724        // saw none at all.
7725        //
7726        // An async function does **not** get one. Its body runs synchronously up to the
7727        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7728        // before its caller's next statement — so an `initial_yield` here would park the
7729        // body before it started, which is not fixable at run time: the suspension looks
7730        // exactly like a real `await`.
7731        if self.cur().kind.is_generator() {
7732            self.emit(Opcode::InitialYield, &[]);
7733        }
7734        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7735        // disposal region.
7736        self.stmts(body)?;
7737        // The implicit return only exists if control can actually get here: an
7738        // infinite loop never falls off the end.
7739        if self.end_is_reachable() {
7740            if self.cur().is_suspending() {
7741                // Falling off the end finishes the generator with `undefined`, and the
7742                // value is what tells the resume machinery "completed" rather than
7743                // "suspended".
7744                self.emit(Opcode::Undefined, &[]);
7745                self.emit(Opcode::ReturnAsync, &[]);
7746            } else {
7747                self.emit_class_constructor_tail();
7748            }
7749        }
7750        // Resolution runs while this function is still on the stack: capturing a
7751        // variable from an enclosing function means reaching into that
7752        // function's state, which requires the whole chain to be present.
7753        Ok(self.finish_current())
7754    }
7755
7756    /// Put every binding of a function that contains a direct `eval` into a cell.
7757    ///
7758    /// A direct eval can name any binding in scope, and any closure it creates has to
7759    /// keep sharing that binding after the function returns — `for (let i …)
7760    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7761    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7762    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7763    /// answer: the alternative is knowing at compile time which names a string will
7764    /// mention.
7765    fn capture_everything_for_eval(&mut self) {
7766        let current = self.stack.len() - 1;
7767        if !self.stack[current].has_direct_eval {
7768            return;
7769        }
7770        for arg in &mut self.stack[current].args {
7771            arg.is_captured = true;
7772        }
7773        for var in &mut self.stack[current].vars {
7774            var.is_captured = true;
7775        }
7776    }
7777
7778    /// Whether the current position in the instruction stream can be reached.
7779    ///
7780    /// A walk over the control-flow graph, using labels as instruction indices.
7781    /// The reference does the same thing to decide whether an implicit
7782    /// `return_undef` is needed.
7783    fn end_is_reachable(&self) -> bool {
7784        let state = self.cur();
7785        reachable_instructions(state, state.insns.len())[state.insns.len()]
7786    }
7787
7788    /// Resolve and assemble the function on top of the compiler stack, then pop
7789    /// it.
7790    fn finish_current(&mut self) -> CompiledFunction {
7791        self.provide_param_arguments();
7792        self.provide_arguments();
7793        self.provide_this_local();
7794        self.provide_new_target_local();
7795        self.provide_home_object_local();
7796        self.provide_active_func_local();
7797        self.provide_self_name();
7798        self.materialize_eval_sites();
7799        self.capture_everything_for_eval();
7800        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7801        // Captured bindings need a reference cell; the count goes in the header so
7802        // the runtime knows how many cells to allocate on entry.
7803        let current = self.stack.len() - 1;
7804        let captured = self.stack[current]
7805            .args
7806            .iter()
7807            .filter(|a| a.is_captured)
7808            .count()
7809            + self.stack[current]
7810                .vars
7811                .iter()
7812                .filter(|v| v.is_captured)
7813                .count();
7814        self.stack[current].var_ref_count = captured as u32;
7815        // The scope chain is only final now that every binding is known.
7816        rebuild_scope_chain(&mut self.stack[current]);
7817        let (code, stack_size, positions) =
7818            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7819        let _ = &mut resolved;
7820        let mut state = self.stack.pop().expect("a function is being compiled");
7821        CompiledFunction {
7822            name: state.name,
7823            kind: state.kind,
7824            strict: state.strict,
7825            is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
7826            is_arrow: state.is_arrow,
7827            has_parameter_expressions: state.has_parameter_expressions,
7828            simple_parameter_list: state.simple_parameter_list,
7829            body_start: state.body_start,
7830            args: state.args,
7831            defined_args: state.defined_args,
7832            vars: state.vars,
7833            closure_vars: state.closure_vars,
7834            cpool: state.cpool,
7835            atoms: state.atoms,
7836            code,
7837            stack_size,
7838            var_ref_count: state.var_ref_count,
7839            positions,
7840            source: self.function_source(state.span, state.line, state.column),
7841            line: state.line,
7842            column: state.column,
7843            filename: None,
7844            eval_sites: state.eval_sites,
7845            module: state.module.take().map(Box::new),
7846        }
7847    }
7848}
7849
7850/// Assign each binding a scope level and rebuild the scope chains.
7851///
7852/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7853/// function scope where `var` and hoisted functions live. Every binding outside
7854/// level 0 gets a `scope_next` link to the next binding visible from the same
7855/// point, so walking a block's chain enumerates exactly the bindings live there.
7856///
7857/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7858/// point at `b`, which is declared later in the source but earlier in the chain.
7859fn rebuild_scope_chain(state: &mut FnState) {
7860    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7861    // real block that happens to start at offset zero keeps its own level instead of
7862    // being merged into the function scope.
7863    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7864    for block in &state.blocks {
7865        if !levels.contains(&block.key) {
7866            levels.push(block.key);
7867        }
7868    }
7869    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7870    let parent_level = |level: usize| -> usize {
7871        if level == 0 {
7872            return 0;
7873        }
7874        let key = levels[level];
7875        let parent = state
7876            .blocks
7877            .iter()
7878            .find(|b| b.key == key)
7879            .map(|b| b.parent)
7880            .unwrap_or(FUNCTION_SCOPE);
7881        level_of(parent)
7882    };
7883
7884    // Own bindings per level, in declaration order.
7885    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7886    let keys: Vec<u64> = (0..state.vars.len())
7887        .map(|index| {
7888            state
7889                .var_block
7890                .get(index)
7891                .copied()
7892                .unwrap_or(FUNCTION_SCOPE)
7893        })
7894        .collect();
7895    for (index, key) in keys.into_iter().enumerate() {
7896        // The parameter scope is not a block: it is a level of its own with no parent,
7897        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7898        // it, which the reference does not do — the two environments are siblings.
7899        if key == PARAM_SCOPE {
7900            continue;
7901        }
7902        let level = level_of(key);
7903        state.vars[index].scope_level = level as u32;
7904        // A `catch` parameter is part of the runtime scope chain even though it is
7905        // not lexical: the handler's own bindings chain on to it, which is why the
7906        // reference prints `let y [next:1]` with `e` at 1.
7907        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7908        {
7909            own[level].push(index);
7910        }
7911    }
7912
7913    // A scope's chain is its own bindings in reverse declaration order followed
7914    // by the enclosing scope's chain.
7915    let mut head = vec![-1i32; levels.len()];
7916    for level in 0..levels.len() {
7917        let inherited = if level == 0 {
7918            -1
7919        } else {
7920            head[parent_level(level)]
7921        };
7922        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7923        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7924        for (position, &index) in chain.iter().enumerate() {
7925            let next = chain
7926                .get(position + 1)
7927                .map_or(inherited, |next| *next as i32);
7928            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7929        }
7930    }
7931    state.block_heads = head;
7932
7933    // The parameter list is a scope of its own, and it has no parent: the reference pops
7934    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7935    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7936    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7937    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7938    let param_level = levels.len() as u32;
7939    let mut previous: Option<usize> = None;
7940    for index in 0..state.vars.len() {
7941        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7942        {
7943            continue;
7944        }
7945        state.vars[index].scope_level = param_level;
7946        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7947        previous = Some(index);
7948    }
7949}
7950
7951/// This is where names become slots and where the temporal dead zone shows up in
7952/// the instruction stream: a read of a `let`/`const` binding compiles to
7953/// `get_loc_check`, which throws if the binding is still uninitialised.
7954///
7955/// The peephole pass from the reference implementation is applied at the end,
7956/// for the same reason it is applied to resolved bytecode there: the patterns are
7957/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7958/// resolution. Deleted instructions stay in the list as `None` so that label
7959/// indices remain valid; [`Assembler`] maps them to byte offsets.
7960/// A resolved instruction and the source position it came from.
7961type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7962
7963/// A resolved instruction paired with its position, which is what `assemble` consumes.
7964type PositionedInsn = (Opcode, Vec<Op>);
7965
7966fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7967    let current = stack.len() - 1;
7968    // Dead-code elimination, on the symbolic form where labels are still
7969    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7970    // unreachable, and a `return` leaves everything after it unreachable; the
7971    // reference drops both. Doing it here means the emitter never has to think
7972    // about reachability.
7973    strip_empty_gosubs(stack, current);
7974    eliminate_dead_code(stack, current);
7975    let insns = std::mem::take(&mut stack[current].insns);
7976    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7977    // `insns`, and every arm below pushes exactly one instruction, so the positions
7978    // stay aligned with `out`.
7979    let positions = std::mem::take(&mut stack[current].insn_pos);
7980    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7981    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7982    for (index, insn) in insns.iter().enumerate() {
7983        let pos = positions.get(index).copied().flatten();
7984        out_pos.push(pos);
7985        match insn {
7986            Insn::Fixed { op, operands } => {
7987                let operands = operands
7988                    .iter()
7989                    .map(|operand| match operand {
7990                        Op::Atom(atom) => {
7991                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7992                        }
7993                        other => other.clone(),
7994                    })
7995                    .collect();
7996                out.push(Some((*op, operands)));
7997            }
7998            Insn::Var {
7999                action,
8000                name,
8001                block,
8002                in_params,
8003            } => {
8004                // Both reads and writes in the parameter list address the parameter
8005                // scope. That is what puts the list in the temporal dead zone — a read of
8006                // a later parameter is `get_loc_check` on an uninitialised slot — and it
8007                // is also what keeps an assignment made inside a default away from the
8008                // body, which sees a separate environment.
8009                let slot = resolve_slot(stack, current, name, *block, *in_params);
8010                // A store to the name of a named function expression is special: the
8011                // reference drops it in sloppy mode and throws in strict mode, because
8012                // the binding is immutable but only *checked* when the body is strict.
8013                // The same rule applies when the name is reached through a closure:
8014                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8015                // the store in the arrow too, not just in the function that owns the
8016                // binding. Reaching the owner means walking the chain of closure
8017                // entries, which is what `self_name_binding` does.
8018                let self_name = matches!(action, VarAction::Put | VarAction::Set)
8019                    .then(|| {
8020                        // A local of this function is the common case and needs no
8021                        // chain walk; only an access that resolves elsewhere can be
8022                        // pointing at an enclosing function's name binding.
8023                        if let Slot::Loc(index) = slot {
8024                            stack[current]
8025                                .vars
8026                                .get(index as usize)
8027                                .filter(|var| var.kind == VarKind::FunctionName)
8028                                .map(|var| var.is_const)
8029                        } else {
8030                            self_name_binding(stack, current, name, *block)
8031                        }
8032                    })
8033                    .flatten();
8034                if let Some(is_const) = self_name {
8035                    out.push(Some(if is_const {
8036                        (
8037                            Opcode::ThrowError,
8038                            vec![
8039                                Op::AtomId(intern_atom(&mut stack[current], name)),
8040                                Op::Int(0),
8041                            ],
8042                        )
8043                    } else {
8044                        (Opcode::Drop, Vec::new())
8045                    }));
8046                    continue;
8047                }
8048                out.push(Some(variable_instruction(stack, current, *action, slot)));
8049            }
8050            Insn::CloseCaptured { name, block } => {
8051                // The block matters: a loop variable is scoped to the `for` head's own
8052                // block, so resolving it against block 0 would miss it entirely and
8053                // silently emit nothing.
8054                let slot = resolve_slot(stack, current, name, *block, false);
8055                // Only a local with a reference cell has anything to close. A global
8056                // or a never-captured local resolves to no instruction at all, which
8057                // keeps the bytecode identical to the reference's.
8058                if let Slot::Loc(index) = slot
8059                    && stack[current]
8060                        .vars
8061                        .get(index as usize)
8062                        .is_some_and(|v| v.is_captured)
8063                {
8064                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8065                } else {
8066                    out.push(None);
8067                }
8068            }
8069            Insn::DeleteVar { name } => {
8070                // A binding — a local, an argument, or a declared global — cannot be
8071                // deleted, and the reference encodes that as a constant `push_false`.
8072                // Only an implicit global needs the runtime lookup.
8073                if matches!(
8074                    resolve_slot(stack, current, name, 0, false),
8075                    Slot::Global(_)
8076                ) {
8077                    let atom = intern_atom(&mut stack[current], name);
8078                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8079                } else {
8080                    out.push(Some((Opcode::PushFalse, Vec::new())));
8081                }
8082            }
8083            Insn::Dead => out.push(None),
8084        }
8085    }
8086    // Which label (if any) sits on each instruction, so the jump patterns can
8087    // tell whether they would cross a jump target.
8088    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8089    for (id, placed) in stack[current].labels.iter().enumerate() {
8090        if let Some(index) = *placed
8091            && index < label_at.len()
8092            && label_at[index].is_none()
8093        {
8094            label_at[index] = Some(id as u32);
8095        }
8096    }
8097    if std::env::var_os("QJS_DEBUG").is_some() {
8098        eprintln!("--- peephole entry ---");
8099        for (i, e) in out.iter().enumerate() {
8100            eprintln!("{i}: {e:?}");
8101        }
8102        eprintln!("label_at: {label_at:?}");
8103    }
8104    peephole(&mut out, &label_at, &stack[current].labels);
8105    (out, out_pos)
8106}
8107
8108/// Find where `name` lives, capturing it in an enclosing function when needed.
8109///
8110/// The search runs outward through the enclosing functions' states, which are
8111/// still on the compiler stack while a nested function is resolved. Finding the
8112/// name in an enclosing function is what creates a closure reference, and every
8113/// function in between has to forward it — a function can only reach its own
8114/// parent's frame.
8115///
8116/// A name declared nowhere is a global. The reference does *not* look it up by
8117/// name from the inner function: the top-level function gets one `[global]`
8118/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8119/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8120/// rather than `[global]`.
8121/// The lexical blocks enclosing `block`, innermost first.
8122fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8123    let mut chain = Vec::new();
8124    let mut current = Some(block);
8125    while let Some(key) = current {
8126        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8127        // explicitly (rather than on "no block with this key") is what keeps a block
8128        // that happens to sit at offset zero from being mistaken for the terminator.
8129        if key == NO_PARENT || chain.contains(&key) {
8130            break;
8131        }
8132        chain.push(key);
8133        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8134    }
8135    chain
8136}
8137
8138/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8139///
8140/// The binding may be several functions away: an arrow nested in `function myfunc`
8141/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8142/// means following `Ref` entries down and then reading the owning function's var table.
8143fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8144    let state = stack.get(current)?;
8145    // A parameter shadows everything and is never a function-expression name.
8146    if state.args.iter().any(|arg| arg.name == name) {
8147        return None;
8148    }
8149    // A local of this very function: the answer is in its var table.
8150    if let Some(index) = local_slot_index(state, name, block) {
8151        let var = state.vars.get(index)?;
8152        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8153    }
8154    // Otherwise the name lives further out, and the closure entry says how to get
8155    // there. `Local` names the owner's slot directly; `Ref` names the next level's
8156    // closure entry, so the walk continues downwards.
8157    let mut level = current;
8158    let mut index = state
8159        .closure_vars
8160        .iter()
8161        .position(|closure| closure.name == name)?;
8162    loop {
8163        let state = stack.get(level)?;
8164        let closure = state.closure_vars.get(index)?;
8165        match closure.closure_type {
8166            ClosureType::Local => {
8167                let owner = stack.get(level.checked_sub(1)?)?;
8168                let var = owner.vars.get(closure.var_idx as usize)?;
8169                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8170            }
8171            ClosureType::Arg => return None,
8172            ClosureType::Ref => {
8173                level -= 1;
8174                index = closure.var_idx as usize;
8175            }
8176            // A global is never a function-expression name.
8177            ClosureType::Global
8178            | ClosureType::GlobalDecl
8179            | ClosureType::GlobalRef
8180            | ClosureType::ModuleDecl
8181            | ClosureType::ModuleImport => return None,
8182        }
8183    }
8184}
8185
8186/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8187fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8188    block_chain(state, block).into_iter().find_map(|scope| {
8189        state.vars.iter().enumerate().find_map(|(index, var)| {
8190            (var.name == name && state.var_block.get(index).copied() == Some(scope))
8191                .then_some(index)
8192        })
8193    })
8194}
8195
8196/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8197fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8198    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8199        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8200    }) {
8201        return index as u32;
8202    }
8203    state.var_block.push(PARAM_SCOPE);
8204    state.vars.push(VarDef::var(name));
8205    state.vars.len() as u32 - 1
8206}
8207
8208/// The name a parameter binds straight from its argument slot, if it has one.
8209///
8210/// A plain name does — with or without a default, and with or without `...`. Everything
8211/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8212/// reference names the argument in the first case and leaves it `<null>` in the second,
8213/// so both the dump and the closures that capture the argument depend on this.
8214fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8215    match &param.kind {
8216        PatternKind::Ident(name) => Some(name),
8217        PatternKind::Assign { target, .. } => match &target.kind {
8218            PatternKind::Ident(name) => Some(name),
8219            _ => None,
8220        },
8221        PatternKind::Rest(inner) => match &inner.kind {
8222            PatternKind::Ident(name) => Some(name),
8223            _ => None,
8224        },
8225        _ => None,
8226    }
8227}
8228
8229/// The pattern a parameter list has to unpick, if `index` is one of them.
8230fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8231    prologue
8232        .iter()
8233        .find(|(at, _)| *at == index)
8234        .map(|(_, pattern)| pattern)
8235}
8236
8237fn pattern_has_default(pattern: &Pattern) -> bool {
8238    match &pattern.kind {
8239        PatternKind::Assign { .. } => true,
8240        PatternKind::Rest(inner) => pattern_has_default(inner),
8241        PatternKind::Array { elements, rest } => {
8242            elements.iter().flatten().any(element_has_default)
8243                || rest.as_deref().is_some_and(rest_has_default)
8244        }
8245        PatternKind::Object { properties, rest } => {
8246            properties.iter().flatten().any(element_has_default)
8247                || rest.as_deref().is_some_and(rest_has_default)
8248        }
8249        _ => false,
8250    }
8251}
8252
8253fn element_has_default(element: &PatternElement) -> bool {
8254    match element {
8255        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8256        PatternElement::Property { value, .. } => pattern_has_default(value),
8257    }
8258}
8259
8260fn rest_has_default(rest: &RestElement) -> bool {
8261    match rest {
8262        RestElement::Pattern(pattern) => pattern_has_default(pattern),
8263        RestElement::Member(_) => false,
8264    }
8265}
8266
8267/// Whether a function-scope binding is visible to the parameter list.
8268///
8269/// The parameter list runs before the body, so the body's `var`s and function
8270/// declarations do not exist yet — a name that only the body declares has to resolve
8271/// outward instead. What *does* exist by then is the compiler's own prologue: the
8272/// self-name of a named function expression (bound by `special_object 2` before anything
8273/// else), `this` and `new.target`. Those stay visible, which is what makes
8274/// `function f(a = this)` and `var f = function f(a = f)` work.
8275///
8276/// `arguments` is handled separately, as a binding of the parameter scope itself: with
8277/// parameter expressions the reference creates two of them, and the one the parameter
8278/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
8279fn visible_in_params(var: &VarDef) -> bool {
8280    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
8281}
8282
8283fn resolve_slot(
8284    stack: &mut [FnState],
8285    current: usize,
8286    name: &str,
8287    block: u64,
8288    in_params: bool,
8289) -> Slot {
8290    // The parameter list's own bindings. They are consulted first because they shadow
8291    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8292    // `a` in the parameter scope, so a closure made there reads the parameter even after
8293    // the body assigns to its own `a`.
8294    if in_params
8295        && let Some(index) = stack[current]
8296            .vars
8297            .iter()
8298            .enumerate()
8299            .position(|(index, var)| {
8300                var.name == name
8301                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8302            })
8303    {
8304        return Slot::Loc(index as u32);
8305    }
8306    // A name can be bound more than once: two `catch` parameters in nested
8307    // handlers are two slots. The binding that wins is the one whose scope encloses
8308    // the access, and among those the innermost — so the blocks are walked outward
8309    // and the first binding found on the way is the one that counts. A binding in
8310    // no block (`var`) is reachable from anywhere, which is why the function scope
8311    // is the end of the walk.
8312    //
8313    // The block walk comes *before* the argument slots, because a block may shadow a
8314    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8315    // slot is only the answer once nothing nearer claims the name.
8316    let chain = block_chain(&stack[current], block);
8317    for scope in &chain {
8318        let found = stack[current]
8319            .vars
8320            .iter()
8321            .enumerate()
8322            .find(|(index, var)| {
8323                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8324            })
8325            .map(|(index, _)| index);
8326        if let Some(index) = found {
8327            return Slot::Loc(index as u32);
8328        }
8329    }
8330    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8331    // its own slot, and `var` of the same name in the body is the same binding.
8332    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8333        return Slot::Arg(index as u32);
8334    }
8335    // Function-scope bindings — `var` and function declarations — are recorded with
8336    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8337    // them. They are reachable from anywhere in the function, which is exactly what
8338    // the sentinel means.
8339    //
8340    // This pass is *only* for those. A lexical binding has to be found through the
8341    // chain or not at all, and looking a name up without its block is precisely how
8342    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8343    // block leaked out of it.
8344    let function_scoped = stack[current]
8345        .vars
8346        .iter()
8347        .enumerate()
8348        .find(|(index, var)| {
8349            var.name == name
8350                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8351                && (!in_params || visible_in_params(var))
8352        })
8353        .map(|(index, _)| index);
8354    if let Some(index) = function_scoped {
8355        return Slot::Loc(index as u32);
8356    }
8357    if let Some(index) = stack[current]
8358        .closure_vars
8359        .iter()
8360        .position(|c| c.name == name)
8361    {
8362        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8363    }
8364
8365    for owner in (0..current).rev() {
8366        // The nested function was created inside one of this frame's blocks, and the
8367        // outermost visible binding is the innermost block on that chain — not whatever
8368        // comes first in the variable table. `function f(){ class S{} }` has two `S`
8369        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8370        // the class body is the one a method may see.
8371        let entry = stack
8372            .get(owner + 1)
8373            .map(|s| s.created_in_block)
8374            .unwrap_or(0);
8375        let lexical = block_chain(&stack[owner], entry)
8376            .into_iter()
8377            .find_map(|scope| {
8378                stack[owner]
8379                    .vars
8380                    .iter()
8381                    .enumerate()
8382                    .find(|(index, var)| {
8383                        var.name == name
8384                            && stack[owner].var_block.get(*index).copied() == Some(scope)
8385                    })
8386                    .map(|(index, _)| index)
8387            });
8388        // A function born in a parameter list sees that list's bindings, not the body's:
8389        // the parameter scope is the environment it was created in.
8390        let in_param_scope = stack
8391            .get(owner + 1)
8392            .is_some_and(|child| child.created_in_params)
8393            .then(|| {
8394                stack[owner]
8395                    .vars
8396                    .iter()
8397                    .enumerate()
8398                    .position(|(index, var)| {
8399                        var.name == name
8400                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8401                    })
8402            })
8403            .flatten();
8404        let found = if let Some(index) = in_param_scope {
8405            let var = &stack[owner].vars[index];
8406            Some(Found::Local(
8407                ClosureType::Local,
8408                index as u32,
8409                var.is_const,
8410                var.needs_check(),
8411            ))
8412        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8413            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8414        } else if let Some(index) = lexical {
8415            let var = &stack[owner].vars[index];
8416            Some(Found::Local(
8417                ClosureType::Local,
8418                index as u32,
8419                var.is_const,
8420                var.needs_check(),
8421            ))
8422        } else if let Some(index) = stack[owner]
8423            .vars
8424            .iter()
8425            .enumerate()
8426            .find_map(|(index, var)| {
8427                // A function created inside a parameter list must not see the body of the
8428                // function it was born in; see [`FnState::created_in_params`].
8429                let hidden = stack
8430                    .get(owner + 1)
8431                    .is_some_and(|child| child.created_in_params);
8432                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8433            })
8434        {
8435            let var = &stack[owner].vars[index];
8436            Some(Found::Local(
8437                ClosureType::Local,
8438                index as u32,
8439                var.is_const,
8440                var.needs_check(),
8441            ))
8442        } else if stack[owner].self_name.as_deref() == Some(name) {
8443            // A named function expression's own name. The reference declares it here,
8444            // on the first lookup that fails, rather than up front — and that is what
8445            // makes it reachable from a *nested* function: the nested lookup is what
8446            // walks out and creates the binding. A direct reference in the body is
8447            // caught the same way, which is why `provide_self_name` only has to add
8448            // the prologue.
8449            let strict = stack[owner].strict;
8450            stack[owner].var_block.push(FUNCTION_SCOPE);
8451            stack[owner].vars.push(VarDef {
8452                kind: VarKind::FunctionName,
8453                // In strict mode the name is immutable, so a store raises; sloppy
8454                // mode drops the store instead (see `variable_instruction`).
8455                is_const: strict,
8456                ..VarDef::var(name)
8457            });
8458            let index = stack[owner].vars.len() as u32 - 1;
8459            Some(Found::Local(ClosureType::Local, index, strict, false))
8460        } else if let Some(index) = stack[owner]
8461            .closure_vars
8462            .iter()
8463            .position(|c| c.name == name)
8464        {
8465            let closure = &stack[owner].closure_vars[index];
8466            Some(match closure.closure_type {
8467                // `GlobalRef` belongs here too: it is a *global* reached through this
8468                // frame's reference table, so treating it as a `Ref` to a local cell makes
8469                // the reader look for a cell no frame ever fills. That is how a second
8470                // function using `eval` in its parameter list read `undefined` after a
8471                // sibling had already made `eval` a closure entry.
8472                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8473                    Found::Global(index as u32)
8474                }
8475                // A module variable is a cell in the *module's* environment, which is
8476                // the module body's parent as far as a nested function is concerned — so
8477                // it is captured as a plain reference, not looked up as a global.
8478                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8479                    ClosureType::Ref,
8480                    index as u32,
8481                    closure.is_const,
8482                    closure.is_lexical,
8483                ),
8484                _ => Found::Local(
8485                    ClosureType::Ref,
8486                    index as u32,
8487                    closure.is_const,
8488                    closure.is_lexical,
8489                ),
8490            })
8491        } else {
8492            None
8493        };
8494        let Some(found) = found else { continue };
8495
8496        let (is_const, is_lexical) = match found {
8497            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8498            Found::Global(_) => (false, false),
8499        };
8500        // Mark the owner's binding as captured so it moves into a reference cell.
8501        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8502            let slot = match found {
8503                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8504                _ => &mut stack[owner].vars[index as usize],
8505            };
8506            slot.is_captured = true;
8507        }
8508        // Forward the reference through every function in between.
8509        let mut previous = match found {
8510            Found::Local(kind, index, _, _) => (kind, index),
8511            Found::Global(index) => (ClosureType::Global, index),
8512        };
8513        for level in owner + 1..=current {
8514            let kind = match (previous.0, level) {
8515                // A global stays a global at *every* level. Without `GlobalRef` in
8516                // this arm the second nested function over the same global got a
8517                // `Ref` to a cell no frame ever held, so the innermost closure read
8518                // `undefined` — which is how a two-deep getter lost its outer
8519                // variable.
8520                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8521                    ClosureType::GlobalRef
8522                }
8523                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8524                _ => ClosureType::Ref,
8525            };
8526            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8527            previous = (kind, index);
8528        }
8529        let index = previous.1;
8530        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8531    }
8532
8533    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8534    // creating a property. The top-level function holds the entry.
8535    let mut previous = (
8536        ClosureType::Global,
8537        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8538    );
8539    for level in 1..=current {
8540        let index = ensure_closure(
8541            stack,
8542            level,
8543            name,
8544            false,
8545            false,
8546            ClosureType::GlobalRef,
8547            previous.1,
8548        );
8549        previous = (ClosureType::GlobalRef, index);
8550    }
8551    Slot::Global(previous.1)
8552}
8553
8554/// What an outward search turned up.
8555#[derive(Debug, Clone, Copy)]
8556enum Found {
8557    /// A binding in an enclosing function, reachable through a closure of this
8558    /// type, with its const/lexical flags.
8559    Local(ClosureType, u32, bool, bool),
8560    /// A global, reached through the enclosing function's closure entry.
8561    Global(u32),
8562}
8563
8564/// Add a closure entry to `level` if it is not there yet.
8565fn ensure_closure(
8566    stack: &mut [FnState],
8567    level: usize,
8568    name: &str,
8569    is_const: bool,
8570    is_lexical: bool,
8571    closure_type: ClosureType,
8572    var_idx: u32,
8573) -> u32 {
8574    if let Some(index) = stack[level]
8575        .closure_vars
8576        .iter()
8577        .position(|c| c.name == name)
8578    {
8579        return index as u32;
8580    }
8581    stack[level].closure_vars.push(ClosureVar {
8582        name: name.to_string(),
8583        is_const,
8584        is_lexical,
8585        closure_type,
8586        var_idx: var_idx as u16,
8587    });
8588    stack[level].closure_vars.len() as u32 - 1
8589}
8590
8591fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8592    match closure.closure_type {
8593        // A `global_ref` only says *how* the binding is found (through the
8594        // parent's closure table); the access itself is an ordinary global one.
8595        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8596        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8597        // A module variable is a real cell in the module's environment, so it is reached
8598        // exactly like a captured local — the host, not the global object, is what fills
8599        // the slot.
8600        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8601        _ => Slot::VarRef(index),
8602    }
8603}
8604
8605/// Pick the opcode for one variable access.
8606///
8607/// The `_check` variants are what enforce the temporal dead zone. They are used
8608/// for every access to a `let`/`const` binding except its own initialisation —
8609/// which is exactly the operation that takes the binding out of the dead zone.
8610fn variable_instruction(
8611    stack: &[FnState],
8612    current: usize,
8613    action: VarAction,
8614    slot: Slot,
8615) -> (Opcode, Vec<Op>) {
8616    let lexical = match slot {
8617        Slot::Loc(index) => stack[current]
8618            .vars
8619            .get(index as usize)
8620            .is_some_and(|v| v.needs_check()),
8621        Slot::VarRef(index) => stack[current]
8622            .closure_vars
8623            .get(index as usize)
8624            .is_some_and(|c| c.is_lexical),
8625        _ => false,
8626    };
8627    let operand = vec![Op::Slot(slot)];
8628    match (action, slot) {
8629        (VarAction::Get, Slot::Loc(index)) => (
8630            if lexical {
8631                Opcode::GetLocCheck
8632            } else {
8633                Opcode::GetLoc
8634            },
8635            vec![Op::Slot(Slot::Loc(index))],
8636        ),
8637        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8638        (VarAction::Get, Slot::VarRef(index)) => (
8639            if lexical {
8640                Opcode::GetVarRefCheck
8641            } else {
8642                Opcode::GetVarRef
8643            },
8644            vec![Op::Slot(Slot::VarRef(index))],
8645        ),
8646        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8647        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8648        // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
8649        // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
8650        // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
8651        // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
8652        // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
8653        // `ReferenceError`.
8654        (VarAction::GetUndef, Slot::Loc(index)) => (
8655            if lexical {
8656                Opcode::GetLocCheck
8657            } else {
8658                Opcode::GetLoc
8659            },
8660            vec![Op::Slot(Slot::Loc(index))],
8661        ),
8662        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8663        (VarAction::GetUndef, Slot::VarRef(index)) => (
8664            if lexical {
8665                Opcode::GetVarRefCheck
8666            } else {
8667                Opcode::GetVarRef
8668            },
8669            vec![Op::Slot(Slot::VarRef(index))],
8670        ),
8671        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8672            (Opcode::GetVarUndef, operand)
8673        }
8674
8675        (VarAction::Put, Slot::Loc(_)) => (
8676            if lexical {
8677                Opcode::PutLocCheck
8678            } else {
8679                Opcode::PutLoc
8680            },
8681            operand,
8682        ),
8683        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8684        (VarAction::Put, Slot::VarRef(_)) => (
8685            if lexical {
8686                Opcode::PutVarRefCheck
8687            } else {
8688                Opcode::PutVarRef
8689            },
8690            operand,
8691        ),
8692        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8693        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8694        // Initialisation is what ends the dead zone, so it never checks.
8695        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8696        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8697        // `this` in a derived constructor is always a local, so these cannot happen;
8698        // routing them to the ordinary forms keeps the match total without inventing
8699        // opcodes the reference does not have.
8700        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8701        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8702        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8703            (Opcode::PutVarInit, operand)
8704        }
8705        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8706        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8707        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8708            (Opcode::PutVarInit, operand)
8709        }
8710        (VarAction::Set, Slot::Loc(_)) => (
8711            if lexical {
8712                Opcode::SetLocCheck
8713            } else {
8714                Opcode::SetLoc
8715            },
8716            operand,
8717        ),
8718        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8719        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8720        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8721        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8722        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8723        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8724        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8725        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8726        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8727        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8728        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8729        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8730    }
8731}
8732
8733/// The instruction-rewriting pass.
8734///
8735/// These are the reference implementation's patterns, restricted to the ones the
8736/// constructs this compiler supports can produce. Each entry is a comment on the
8737/// bytecode it removes, because the whole point is that the result is one
8738/// instruction shorter than the literal translation of the AST.
8739fn peephole(
8740    insns: &mut [Option<(Opcode, Vec<Op>)>],
8741    label_at: &[Option<u32>],
8742    placed: &[Option<usize>],
8743) {
8744    fold_dup_patterns(insns, label_at);
8745
8746    // `drop` before `return_undef` is dead: the return discards the whole frame
8747    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8748    // consumes its own `drop`; removing the drop first would leave the `dup` and
8749    // produce a `set_` where the reference has a `put_`.
8750    for index in 0..insns.len() {
8751        if opcode_at(insns, index) != Some(Opcode::Drop) {
8752            continue;
8753        }
8754        // Skip over a run of drops, but stop at a jump target: removing code on
8755        // one side of a label would silently retarget the jump.
8756        let mut next = index + 1;
8757        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8758            next += 1;
8759        }
8760        if is_label_at(label_at, next) {
8761            continue;
8762        }
8763        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8764            for entry in &mut insns[index..next] {
8765                *entry = None;
8766            }
8767        }
8768    }
8769
8770    // The rewrites below all decide against one fixed snapshot, which is what the
8771    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8772    // the pass, so a rule never observes what an earlier rule removed. Gathering
8773    // every deletion first and applying them together reproduces that.
8774    let snapshot: Vec<Option<Opcode>> = insns
8775        .iter()
8776        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8777        .collect();
8778    // The next instruction that is still there. Holes left by dead-code
8779    // elimination are not instructions, so a rule looks past them.
8780    let next_op = |index: usize| -> Option<usize> {
8781        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8782    };
8783
8784    let mut doomed = vec![false; insns.len()];
8785    for index in 0..insns.len() {
8786        // A constant pushed only to be dropped does nothing at all. This is what a
8787        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8788        // the reference removes the pair rather than making the reader step over it.
8789        let constant = matches!(
8790            snapshot[index],
8791            Some(
8792                Opcode::Undefined
8793                    | Opcode::Null
8794                    | Opcode::PushMinus1
8795                    | Opcode::Push0
8796                    | Opcode::Push1
8797                    | Opcode::Push2
8798                    | Opcode::Push3
8799                    | Opcode::Push4
8800                    | Opcode::Push5
8801                    | Opcode::Push6
8802                    | Opcode::Push7
8803                    | Opcode::PushTrue
8804                    | Opcode::PushFalse
8805                    | Opcode::PushI32
8806            )
8807        );
8808        if constant
8809            && let Some(next) = next_op(index)
8810            && snapshot[next] == Some(Opcode::Drop)
8811        {
8812            doomed[index] = true;
8813            doomed[next] = true;
8814        }
8815    }
8816    for (index, entry) in insns.iter_mut().enumerate() {
8817        if doomed[index] {
8818            *entry = None;
8819        }
8820    }
8821
8822    // A conditional whose destination is the very next instruction just pops its
8823    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8824    // compiles to.
8825    //
8826    // Order matters, and it is the reference's order: this runs *before* the
8827    // folding below, on the instruction the conditional originally had. Folding
8828    // moves a conditional's destination, and the reference never re-examines it
8829    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8830    // a conditional even though folding leaves it pointing at the next
8831    // instruction.
8832    for (index, entry) in insns.iter_mut().enumerate() {
8833        let Some((op, operands)) = entry.clone() else {
8834            continue;
8835        };
8836        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8837            continue;
8838        }
8839        let Some(id) = label_id(&operands) else {
8840            continue;
8841        };
8842        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8843            *entry = Some((Opcode::Drop, Vec::new()));
8844        }
8845    }
8846
8847    // A constant condition is decided here rather than at run time.
8848    fold_constant_conditions(insns);
8849    // The conditional folding below is about pairs of *real* branches, so it runs
8850    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8851    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8852    // the branch first and only then notices the jump goes nowhere.
8853    fold_conditional_jumps(insns, label_at, placed);
8854
8855    // A jump whose destination is the very next instruction does nothing, which is
8856    // what constant folding leaves behind for `while (1) { … }`.
8857    remove_jump_to_next(insns, placed);
8858
8859    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8860    // a use of the same variable boils down to.
8861    for index in 0..insns.len() {
8862        let Some((put_op, _)) = insns[index].clone() else {
8863            continue;
8864        };
8865        if !is_foldable_put(put_op) {
8866            continue;
8867        }
8868        if is_label_at(label_at, index + 1) {
8869            continue;
8870        }
8871        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8872            continue;
8873        };
8874        if get_op != get_form_of(put_op) {
8875            continue;
8876        }
8877        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8878        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8879            continue;
8880        }
8881        insns[index] = Some((set_form_of(put_op), get_operands));
8882        insns[index + 1] = None;
8883    }
8884}
8885
8886/// Drop `gosub`s that call an empty subroutine.
8887///
8888/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8889/// drops the call. This is how `try`/`catch` without a `finally` loses its
8890/// finalizer plumbing: the finalizer block is empty, its first instruction is
8891/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8892/// [`eliminate_dead_code`] then removes.
8893fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8894    let state = &stack[current];
8895    let mut targets = Vec::new();
8896    for insn in &state.insns {
8897        if let Insn::Fixed { op, operands } = insn
8898            && *op == Opcode::Gosub
8899            && let Some(id) = label_id(operands)
8900            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8901        {
8902            targets.push(target);
8903        }
8904    }
8905    let empty: Vec<usize> = targets
8906        .into_iter()
8907        .filter(|target| {
8908            stack[current]
8909                .insns
8910                .get(*target)
8911                .map(|insn| {
8912                    matches!(
8913                        insn,
8914                        Insn::Fixed {
8915                            op: Opcode::Ret,
8916                            ..
8917                        }
8918                    )
8919                })
8920                .unwrap_or(false)
8921        })
8922        .collect();
8923    if empty.is_empty() {
8924        return;
8925    }
8926    for insn in stack[current].insns.iter_mut() {
8927        if let Insn::Fixed { op, operands } = insn
8928            && *op == Opcode::Gosub
8929            && let Some(id) = label_id(operands)
8930            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8931            && empty.contains(&target)
8932        {
8933            *insn = Insn::Dead;
8934        }
8935    }
8936}
8937
8938/// Replace unreachable instructions with [`Insn::Dead`].
8939fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8940    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8941    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8942        if !reachable[index] {
8943            *insn = Insn::Dead;
8944        }
8945    }
8946}
8947
8948/// Mark every instruction index reachable from the entry, plus the index one past
8949/// the last instruction.
8950///
8951/// `seen[len]` answers "can control reach the end of this function", and the
8952/// entries before it identify dead code. Both DCE and the implicit-return decision
8953/// read the same result, which keeps them from disagreeing.
8954fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8955    let mut seen = vec![false; count + 1];
8956    let mut worklist = vec![0usize];
8957    while let Some(index) = worklist.pop() {
8958        if index > count || seen[index] {
8959            continue;
8960        }
8961        seen[index] = true;
8962        if index == count {
8963            continue;
8964        }
8965        let (op, operands) = match &state.insns[index] {
8966            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8967            // A variable access never transfers control, and a removed
8968            // instruction is only reachable if it is already marked.
8969            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8970                worklist.push(index + 1);
8971                continue;
8972            }
8973        };
8974        match op {
8975            // A return, a throw and a `ret` all leave this instruction stream: the
8976            // first two give control to the caller or the handler, and `ret`
8977            // returns to a `gosub` elsewhere.
8978            // A tail call leaves the function too: the callee's result becomes this
8979            // function's result, so nothing after it runs.
8980            Opcode::Return
8981            | Opcode::ReturnUndef
8982            | Opcode::ReturnAsync
8983            | Opcode::TailCall
8984            | Opcode::TailCallMethod
8985            | Opcode::Throw
8986            | Opcode::ThrowError
8987            | Opcode::Ret => {}
8988            // A `catch` records where exceptions from the code that follows go.
8989            // That code is not reachable through normal control flow, but it is
8990            // reachable — through the exception edge — so the walk has to follow
8991            // it, or dead-code elimination would delete every handler.
8992            Opcode::Catch => {
8993                if let Some(target) = placed_label(state, operands) {
8994                    worklist.push(target);
8995                }
8996                worklist.push(index + 1);
8997            }
8998            // A `gosub` calls a subroutine and then continues, so both edges count.
8999            Opcode::Gosub => {
9000                if let Some(target) = placed_label(state, operands) {
9001                    worklist.push(target);
9002                }
9003                worklist.push(index + 1);
9004            }
9005            Opcode::Goto => {
9006                if let Some(target) = placed_label(state, operands) {
9007                    worklist.push(target);
9008                }
9009            }
9010            Opcode::IfTrue | Opcode::IfFalse => {
9011                if let Some(target) = placed_label(state, operands) {
9012                    worklist.push(target);
9013                }
9014                worklist.push(index + 1);
9015            }
9016            _ => worklist.push(index + 1),
9017        }
9018    }
9019    seen
9020}
9021
9022/// The instruction index a jump operand points at, resolved through the label
9023/// placement table.
9024fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9025    let id = label_id(operands)?;
9026    state.labels.get(id as usize).copied().flatten()
9027}
9028
9029/// The label an instruction refers to.
9030fn label_id(operands: &[Op]) -> Option<u32> {
9031    operands.iter().find_map(|operand| match operand {
9032        Op::Label(label) => Some(label.0),
9033        _ => None,
9034    })
9035}
9036
9037/// Turn `if_false L; goto M; L:` into `if_true M`.
9038///
9039/// A conditional whose alternate branch is an unconditional jump needs one jump,
9040/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9041/// instruction and a label from every conditional `break`.
9042/// The boolean a constant-push instruction produces, or `None` if it is not one.
9043///
9044/// Only the operators whose truthiness is decided by the opcode are covered; a
9045/// constant that needs the constant pool (a string) is left alone, because reading it
9046/// would mean threading the pool through the peephole for a case the reference also
9047/// skips.
9048fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9049    match op {
9050        // `push_0` returns -1 for zero, `push_1` 1, and so on.
9051        Opcode::PushMinus1 => Some(true),
9052        Opcode::Push0 => Some(false),
9053        Opcode::Push1
9054        | Opcode::Push2
9055        | Opcode::Push3
9056        | Opcode::Push4
9057        | Opcode::Push5
9058        | Opcode::Push6
9059        | Opcode::Push7 => Some(true),
9060        Opcode::PushTrue => Some(true),
9061        Opcode::PushFalse => Some(false),
9062        Opcode::Undefined | Opcode::Null => Some(false),
9063        Opcode::PushI32 => match operands.first() {
9064            Some(Op::Int(value)) => Some(*value != 0),
9065            _ => None,
9066        },
9067        _ => None,
9068    }
9069}
9070
9071/// Fold a branch on a constant condition.
9072///
9073/// `if (0) a() else b()` must not test anything at run time, and the reference
9074/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9075/// which is why the bytecode for a `while (1)` loop has no condition at all.
9076///
9077/// Two instructions become one, so the slot the test occupied is left empty rather
9078/// than shifting everything after it: labels have already been resolved to indices.
9079fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
9080    for index in 0..insns.len() {
9081        let Some((push_op, push_operands)) = insns[index].clone() else {
9082            continue;
9083        };
9084        let Some(truth) = constant_truth(push_op, &push_operands) else {
9085            continue;
9086        };
9087        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9088            continue;
9089        };
9090        let (destination, taken) = match branch_op {
9091            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9092            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9093            _ => continue,
9094        };
9095        let Some(destination) = destination else {
9096            continue;
9097        };
9098        insns[index] = if taken {
9099            // The branch is always taken, so it becomes an unconditional jump.
9100            Some((Opcode::Goto, vec![destination]))
9101        } else {
9102            // The branch never runs: both instructions disappear and control falls
9103            // through to what came after.
9104            None
9105        };
9106        insns[index + 1] = None;
9107    }
9108}
9109
9110/// Remove a jump whose destination is the instruction right after it.
9111///
9112/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9113/// its test into nothing, and the loop-end jump then points at the following
9114/// instruction. The reference drops them, so `stack_size` and the listing agree.
9115fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9116    for index in 0..insns.len() {
9117        let Some((op, operands)) = insns[index].clone() else {
9118            continue;
9119        };
9120        if !is_goto(op) {
9121            continue;
9122        }
9123        let Some(id) = label_id(&operands) else {
9124            continue;
9125        };
9126        // The next instruction that still exists, which is what "the instruction
9127        // after this jump" means once earlier folds have punched holes.
9128        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9129        if placed.get(id as usize).copied().flatten() == next {
9130            insns[index] = None;
9131        }
9132    }
9133}
9134
9135fn fold_conditional_jumps(
9136    insns: &mut [Option<(Opcode, Vec<Op>)>],
9137    label_at: &[Option<u32>],
9138    placed: &[Option<usize>],
9139) {
9140    for index in 0..insns.len() {
9141        let Some((op, operands)) = insns[index].clone() else {
9142            continue;
9143        };
9144        let inverted = match op {
9145            Opcode::IfFalse => Opcode::IfTrue,
9146            Opcode::IfTrue => Opcode::IfFalse,
9147            _ => continue,
9148        };
9149        // Next must be an unconditional jump that is not itself a target, and the
9150        // instruction after it must be exactly where the conditional goes.
9151        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9152            continue;
9153        };
9154        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9155            continue;
9156        }
9157        // The conditional must land on the instruction *after* the jump. Several
9158        // labels can share a position, so this asks where *this* label was put
9159        // rather than what label happens to sit there.
9160        let Some(taken) = label_id(&operands) else {
9161            continue;
9162        };
9163        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9164            continue;
9165        }
9166        let Some(destination) = next_operands.first().cloned() else {
9167            continue;
9168        };
9169        insns[index] = Some((inverted, vec![destination]));
9170        insns[index + 1] = None;
9171    }
9172}
9173
9174/// Whether a jump target is placed at this instruction index.
9175fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9176    label_at.get(index).copied().flatten().is_some()
9177}
9178
9179fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9180    // `dup put_x(n)` -> `set_x(n)`
9181    // `dup put_x(n) drop` -> `put_x(n)`
9182    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9183    for index in 0..insns.len() {
9184        if opcode_at(insns, index) != Some(Opcode::Dup) {
9185            continue;
9186        }
9187        if is_label_at(label_at, index + 1) {
9188            continue;
9189        }
9190        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9191            continue;
9192        };
9193        if !is_foldable_put(put_op) {
9194            continue;
9195        }
9196        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9197            continue;
9198        };
9199        let mut new_op = set_form_of(put_op);
9200        let mut end = index + 2;
9201        if is_label_at(label_at, end) {
9202            // The `put` has to stay as it is; only the `dup` can be folded.
9203            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9204            insns[index + 1] = None;
9205            continue;
9206        }
9207        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9208        // Deleting it moves the label's target onto whatever follows, and the code that
9209        // jumps there arrives with a different stack than the fall-through path: that is
9210        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9211        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9212        // an empty stack. The store had already consumed the value it was supposed to
9213        // leave behind.
9214        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9215            new_op = put_op;
9216            end += 1;
9217            if opcode_at(insns, end) == Some(get_form_of(put_op))
9218                && !is_label_at(label_at, end)
9219                && insns[end]
9220                    .as_ref()
9221                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9222            {
9223                new_op = set_form_of(put_op);
9224                end += 1;
9225            }
9226        }
9227        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9228        for entry in &mut insns[index + 1..end] {
9229            *entry = None;
9230        }
9231    }
9232}
9233
9234fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9235    insns
9236        .get(index)
9237        .and_then(|entry| entry.as_ref())
9238        .map(|(op, _)| *op)
9239}
9240
9241/// The four `put_` families that have a `set_` twin. Deliberately not including
9242/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9243/// these, and folding the others would produce instructions that do not exist.
9244fn is_foldable_put(op: Opcode) -> bool {
9245    matches!(
9246        op,
9247        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9248    )
9249}
9250
9251fn set_form_of(op: Opcode) -> Opcode {
9252    match op {
9253        Opcode::PutLoc => Opcode::SetLoc,
9254        Opcode::PutLocCheck => Opcode::SetLocCheck,
9255        Opcode::PutArg => Opcode::SetArg,
9256        Opcode::PutVarRef => Opcode::SetVarRef,
9257        other => other,
9258    }
9259}
9260
9261fn get_form_of(op: Opcode) -> Opcode {
9262    match op {
9263        Opcode::PutLoc => Opcode::GetLoc,
9264        Opcode::PutLocCheck => Opcode::GetLocCheck,
9265        Opcode::PutArg => Opcode::GetArg,
9266        Opcode::PutVarRef => Opcode::GetVarRef,
9267        other => other,
9268    }
9269}
9270
9271/// Atom interning, per function.
9272///
9273/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
9274/// identifiers, so the array-index rule applies here rather than at the handful of
9275/// call sites that build property keys.
9276fn intern_atom(state: &mut FnState, name: &str) -> u32 {
9277    intern_atom_value(state, Atom::from_text(name))
9278}
9279
9280/// [`intern_atom`] for an operand that is already an [`Atom`].
9281///
9282/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
9283/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
9284/// would have looked up.
9285fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
9286    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
9287        return index as u32;
9288    }
9289    state.atoms.push(atom);
9290    state.atoms.len() as u32 - 1
9291}
9292
9293fn binary_opcode(op: BinaryOp) -> Opcode {
9294    match op {
9295        BinaryOp::Add => Opcode::Add,
9296        BinaryOp::Sub => Opcode::Sub,
9297        BinaryOp::Mul => Opcode::Mul,
9298        BinaryOp::Div => Opcode::Div,
9299        BinaryOp::Mod => Opcode::Mod,
9300        BinaryOp::Pow => Opcode::Pow,
9301        BinaryOp::BitOr => Opcode::Or,
9302        BinaryOp::BitXor => Opcode::Xor,
9303        BinaryOp::BitAnd => Opcode::And,
9304        BinaryOp::Shl => Opcode::Shl,
9305        BinaryOp::Shr => Opcode::Sar,
9306        BinaryOp::UShr => Opcode::Shr,
9307        BinaryOp::Lt => Opcode::Lt,
9308        BinaryOp::LtEq => Opcode::Lte,
9309        BinaryOp::Gt => Opcode::Gt,
9310        BinaryOp::GtEq => Opcode::Gte,
9311        BinaryOp::Eq => Opcode::Eq,
9312        BinaryOp::NotEq => Opcode::Neq,
9313        BinaryOp::StrictEq => Opcode::StrictEq,
9314        BinaryOp::StrictNotEq => Opcode::StrictNeq,
9315        BinaryOp::In => Opcode::In,
9316        BinaryOp::Instanceof => Opcode::Instanceof,
9317    }
9318}
9319
9320fn compound_opcode(op: AssignOp) -> Opcode {
9321    match op {
9322        AssignOp::Add => Opcode::Add,
9323        AssignOp::Sub => Opcode::Sub,
9324        AssignOp::Mul => Opcode::Mul,
9325        AssignOp::Div => Opcode::Div,
9326        AssignOp::Mod => Opcode::Mod,
9327        AssignOp::Pow => Opcode::Pow,
9328        AssignOp::Shl => Opcode::Shl,
9329        AssignOp::Shr => Opcode::Sar,
9330        AssignOp::UShr => Opcode::Shr,
9331        AssignOp::BitOr => Opcode::Or,
9332        AssignOp::BitXor => Opcode::Xor,
9333        AssignOp::BitAnd => Opcode::And,
9334        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9335    }
9336}
9337
9338/// Encode the resolved instruction stream, choosing short forms where possible.
9339///
9340/// The peephole pass leaves holes in the instruction list so that label indices
9341/// stay valid. A label names an *instruction index*, and an index that was
9342/// deleted has to resolve to the next surviving instruction, which is what
9343/// [`resolve_label`] does before the byte offsets are known.
9344fn assemble(
9345    insns: &mut [Option<(Opcode, Vec<Op>)>],
9346    insn_pos: &[Option<Position>],
9347    state: &mut FnState,
9348) -> (Vec<u8>, u32, Vec<LineCol>) {
9349    // Compaction: surviving instructions in order, plus the index mapping.
9350    //
9351    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9352    // point below where instructions are removed — otherwise a stack trace would point
9353    // at the wrong source line as soon as dead-code elimination kicked in.
9354    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9355    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9356    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9357    for (original, entry) in insns.iter_mut().enumerate() {
9358        if let Some((op, operands)) = entry.take() {
9359            original_to_kept[original] = Some(kept.len());
9360            kept.push((op, operands));
9361            spans.push(insn_pos.get(original).copied().flatten());
9362        }
9363    }
9364
9365    if std::env::var_os("QJS_DEBUG").is_some() {
9366        eprintln!("--- assemble entry --- {kept:?}");
9367    }
9368    // How many labels are real, as opposed to the per-instruction ones allocated
9369    // just below. Only a real label marks a spot in the source program.
9370    let real_labels = state.labels.len();
9371
9372    // Give every surviving instruction a label of its own. Jump cleanup below
9373    // redirects jumps to arbitrary instructions, and a jump target has to be a
9374    // label; pre-allocating one per index means a redirect never has to invent
9375    // anything.
9376    let existing = state.labels.len();
9377    let base = kept.len();
9378    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9379    for offset in 0..=kept.len() {
9380        state.labels.push(Some(0));
9381        index_label.push(Label((existing + offset) as u32));
9382    }
9383    // Point each pre-allocated label at its instruction, reusing the count from
9384    // `original_to_kept` so the mapping survives compaction.
9385    let place_index_labels = |state: &mut FnState,
9386                              original_to_kept: &[Option<usize>],
9387                              kept_len: usize,
9388                              index_label: &[Label]| {
9389        for (original, mapped) in original_to_kept.iter().enumerate() {
9390            if let Some(kept_index) = mapped {
9391                let label = index_label[*kept_index].0 as usize;
9392                state.labels[label] = Some(original);
9393            }
9394        }
9395        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9396    };
9397    place_index_labels(state, &original_to_kept, base, &index_label);
9398
9399    // Resolve every label to a kept index once; the placement table maps labels
9400    // to original indices, so a second hop lands in kept space.
9401    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9402    for (id, placed) in state.labels.iter().enumerate() {
9403        let Some(original) = placed else { continue };
9404        label_kept[id] = if *original == usize::MAX {
9405            Some(base)
9406        } else {
9407            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9408        };
9409    }
9410
9411    // Code after an unconditional transfer is unreachable, and the reference drops it
9412    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9413    // scans forward until it finds a label something still jumps to, so a run of
9414    // dead instructions between a `throw` and the next live target disappears.
9415    //
9416    // The scan repeats because dropping a jump lowers the reference count of the
9417    // label it pointed at, which can strand what follows. Only a real label keeps an
9418    // instruction alive here; the per-instruction labels allocated above belong to
9419    // this pass, not to the program.
9420    loop {
9421        let mut references = vec![false; kept.len() + 1];
9422        for (_, operands) in &kept {
9423            if let Some(target) = target_kept_index(operands, &label_kept)
9424                && target < references.len()
9425            {
9426                references[target] = true;
9427            }
9428        }
9429        let mut doomed = vec![false; kept.len()];
9430        let mut any = false;
9431        for (index, (op, _)) in kept.iter().enumerate() {
9432            if !is_transfer(*op) {
9433                continue;
9434            }
9435            for next in index + 1..kept.len() {
9436                if references[next] {
9437                    break;
9438                }
9439                doomed[next] = true;
9440                any = true;
9441            }
9442        }
9443        if !any {
9444            break;
9445        }
9446        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9447    }
9448
9449    // A label that lands on an unconditional jump stands for wherever that jump
9450    // goes, so retarget it once and every jump to the label follows for free.
9451    // This is what makes `continue` in a `for` head reach the loop top instead of
9452    // stopping at the update's trailing jump.
9453    let folded: Vec<Option<usize>> = label_kept
9454        .iter()
9455        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9456        .collect();
9457    label_kept = folded;
9458
9459    // Jump cleanup, in compacted index space. Two rewrites the reference also
9460    // applies while it resolves labels:
9461    //   * a jump whose destination is the very next instruction does nothing;
9462    //   * a jump to a jump is redirected to its final destination.
9463    // The second can expose the first, so this repeats until it settles.
9464    loop {
9465        let mut delete = vec![false; kept.len()];
9466        let mut changed = false;
9467        for index in 0..kept.len() {
9468            let (op, operands) = &kept[index];
9469            if !is_goto(*op) {
9470                continue;
9471            }
9472            let Some(immediate) = target_kept_index(operands, &label_kept) else {
9473                continue;
9474            };
9475            let target = follow_jump_chain(&kept, &label_kept, immediate);
9476            if target == index + 1 {
9477                delete[index] = true;
9478                changed = true;
9479            } else if matches!(
9480                kept.get(target).map(|(op, _)| *op),
9481                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9482            ) {
9483                // Jumping straight to a return or throw is the same as doing it
9484                // here, so the jump becomes that instruction.
9485                kept[index] = (kept[target].0, Vec::new());
9486                changed = true;
9487            } else if target != immediate {
9488                // Redirect to the end of the chain.
9489                let label = index_label[target];
9490                kept[index].1 = vec![Op::Label(label)];
9491                changed = true;
9492            }
9493        }
9494        if !changed {
9495            break;
9496        }
9497        if !delete.iter().any(|deleted| *deleted) {
9498            break;
9499        }
9500        // Drop the deleted instructions and renumber everything.
9501        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9502        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9503        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9504        for (old, entry) in kept.into_iter().enumerate() {
9505            if delete[old] {
9506                continue;
9507            }
9508            moved[old] = Some(next.len());
9509            next.push(entry);
9510            next_spans.push(spans[old]);
9511        }
9512        for (id, slot) in label_kept.iter_mut().enumerate() {
9513            let Some(old) = *slot else { continue };
9514            *slot = match moved.get(old).copied().flatten() {
9515                Some(new) => Some(new),
9516                // The target was deleted: the jump now lands on whatever follows.
9517                None => (old..moved.len())
9518                    .find_map(|i| moved[i])
9519                    .or(Some(next.len())),
9520            };
9521            let _ = id;
9522        }
9523        kept = next;
9524        spans = next_spans;
9525    }
9526
9527    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9528    // jump to the next instruction and is deleted, leaving the label at the end with
9529    // nothing pointing at it. If that also strands the last instruction, it goes
9530    // too — which is how a `try` whose body always returns ends on its `ret` rather
9531    // than an implicit `return_undef`.
9532    // Which instructions something still jumps to. Reading the surviving jumps is
9533    // what the reference's reference counts amount to: once a jump has been folded
9534    // away the label it named is unreferenced, even though the program still has a
9535    // label there.
9536    let mut references = vec![false; kept.len() + 1];
9537    let _ = real_labels;
9538    for (_, operands) in &kept {
9539        if let Some(target) = target_kept_index(operands, &label_kept)
9540            && target < references.len()
9541        {
9542            references[target] = true;
9543        }
9544    }
9545    let mut end = kept.len();
9546    while end > 0 {
9547        let last = end - 1;
9548        let reachable = references[last] || end < kept.len();
9549        if reachable {
9550            break;
9551        }
9552        let after_transfer = last
9553            .checked_sub(1)
9554            .map(|previous| {
9555                matches!(
9556                    kept[previous].0,
9557                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9558                )
9559            })
9560            .unwrap_or(false);
9561        if !after_transfer {
9562            break;
9563        }
9564        end = last;
9565    }
9566    kept.truncate(end);
9567    spans.truncate(end);
9568
9569    // Choose an opcode for each instruction and its size, so label offsets can be
9570    // computed.
9571    let chosen = choose_opcodes(&kept, &label_kept);
9572    let offsets = instruction_offsets(&chosen);
9573    let offset = *offsets.last().unwrap_or(&0);
9574
9575    let mut code = Vec::with_capacity(offset);
9576    for (position, (_, operands)) in kept.iter().enumerate() {
9577        let op = chosen[position];
9578        code.push(op as u8);
9579        let operands = retarget_labels(operands, &label_kept, kept.len());
9580        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9581    }
9582    let stack_size = compute_stack_size(&code);
9583    // Keep only the offsets where the position actually changes: a run of
9584    // instructions on one line is one table entry, and the runtime binary searches
9585    // the table for the frame's pc.
9586    //
9587    // The table always starts at pc 0 with the *function's own* position, because the
9588    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9589    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9590    // (`function`, `async`, a method's property name). An instruction before the first
9591    // recorded operator therefore reports the function's own start, which is what makes a
9592    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9593    let mut positions: Vec<LineCol> = vec![LineCol {
9594        pc: 0,
9595        line: state.line,
9596        column: state.column,
9597    }];
9598    let mut last: Option<Position> = None;
9599    for (index, span) in spans.iter().enumerate() {
9600        let Some(pos) = *span else { continue };
9601        if last == Some(pos) {
9602            continue;
9603        }
9604        last = Some(pos);
9605        if pos.line == state.line && pos.column == state.column {
9606            // Already the seed entry above.
9607            continue;
9608        }
9609        positions.push(LineCol {
9610            pc: offsets[index] as u32,
9611            line: pos.line,
9612            column: pos.column,
9613        });
9614    }
9615    (code, stack_size, positions)
9616}
9617
9618/// Whether an instruction always transfers control away, so anything after it in the
9619/// same stream is unreachable.
9620fn is_transfer(op: Opcode) -> bool {
9621    matches!(
9622        op,
9623        Opcode::Goto
9624            | Opcode::Goto8
9625            | Opcode::Goto16
9626            | Opcode::Return
9627            | Opcode::ReturnUndef
9628            | Opcode::Throw
9629            | Opcode::ThrowError
9630            | Opcode::Ret
9631    )
9632}
9633
9634/// Remove the marked instructions and renumber the label table so it keeps pointing
9635/// at the same instructions. A label whose instruction went away moves to whatever
9636/// follows it, since a jump is never left with nowhere to land.
9637fn drop_instructions(
9638    kept: Vec<(Opcode, Vec<Op>)>,
9639    spans: Vec<Option<Position>>,
9640    label_kept: &mut [Option<usize>],
9641    doomed: &[bool],
9642) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9643    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9644    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9645    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9646    for (old, entry) in kept.into_iter().enumerate() {
9647        if doomed.get(old).copied().unwrap_or(false) {
9648            continue;
9649        }
9650        moved[old] = Some(result.len());
9651        result.push(entry);
9652        result_spans.push(spans[old]);
9653    }
9654    for slot in label_kept.iter_mut() {
9655        let Some(old) = *slot else { continue };
9656        *slot = match moved.get(old).copied().flatten() {
9657            Some(new) => Some(new),
9658            None => (old..moved.len())
9659                .find_map(|i| moved[i])
9660                .or(Some(result.len())),
9661        };
9662    }
9663    (result, result_spans)
9664}
9665
9666fn is_goto(op: Opcode) -> bool {
9667    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9668}
9669
9670/// The kept index a jump operand points at.
9671fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9672    let id = label_id(operands)?;
9673    label_kept.get(id as usize).copied().flatten()
9674}
9675
9676/// Follow a chain of unconditional jumps to its first real destination.
9677fn follow_jump_chain(
9678    kept: &[(Opcode, Vec<Op>)],
9679    label_kept: &[Option<usize>],
9680    start: usize,
9681) -> usize {
9682    let mut current = start;
9683    // `for(;;)` jumps to itself, so the walk has to be bounded.
9684    for _ in 0..kept.len() {
9685        let Some((op, operands)) = kept.get(current) else {
9686            return current;
9687        };
9688        if !is_goto(*op) {
9689            return current;
9690        }
9691        let Some(next) = target_kept_index(operands, label_kept) else {
9692            return current;
9693        };
9694        if next == current {
9695            return current;
9696        }
9697        current = next;
9698    }
9699    current
9700}
9701
9702/// Rewrite label operands from label ids to kept instruction indices.
9703fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9704    operands
9705        .iter()
9706        .map(|operand| match operand {
9707            Op::Label(label) => {
9708                let target = label_kept
9709                    .get(label.0 as usize)
9710                    .copied()
9711                    .flatten()
9712                    .unwrap_or(kept_len);
9713                Op::Label(Label(target as u32))
9714            }
9715            other => other.clone(),
9716        })
9717        .collect()
9718}
9719
9720/// Encode the resolved instruction stream, choosing short forms where possible.
9721///
9722/// Compute the maximum value-stack depth by exploring the control-flow graph.
9723///
9724/// This is a breadth-first walk from the first instruction, tracking the stack
9725/// depth on entry to each instruction. Every instruction has at most two
9726/// successors (fall through, and a jump target), so a worklist over byte offsets
9727/// is enough. The reference does the same thing in `compute_stack_size`, which is
9728/// why the resulting numbers match exactly.
9729///
9730/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9731/// encode that count in their operand, which is added to the static `n_pop`.
9732fn compute_stack_size(code: &[u8]) -> u32 {
9733    let mut depth_at = vec![u16::MAX; code.len()];
9734    // Each entry carries the enclosing `catch` levels, innermost last, because
9735    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9736    // offset and forgets that level.
9737    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9738    let mut max_depth = 0u32;
9739
9740    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9741        if pc >= code.len() {
9742            continue;
9743        }
9744        if depth_at[pc] != u16::MAX {
9745            continue;
9746        }
9747        force_depth(&mut depth_at, pc, depth);
9748
9749        let Some(op) = Opcode::from_u8(code[pc]) else {
9750            break;
9751        };
9752        let info = op.info();
9753        let next = pc + info.size as usize;
9754        if next > code.len() {
9755            break;
9756        }
9757        let mut n_pop = info.n_pop as u32;
9758        let mut n_push = info.n_push as u32;
9759        // Variable-length forms carry their count in the operand.
9760        match info.format {
9761            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9762                n_pop += read_u16(code, pc + 1) as u32;
9763            }
9764            crate::opcode::OpFormat::Npopx => {
9765                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9766            }
9767            _ => {}
9768        }
9769        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9770        // are the `set_` variant; the table already records that, so nothing to
9771        // adjust here.
9772        let _ = &mut n_push;
9773
9774        // The depth before this instruction's own push, which is what a `catch`
9775        // records as its level.
9776        let depth_before = depth;
9777        let mut depth = depth.saturating_sub(n_pop) + n_push;
9778        let mut catch_levels = catch_levels;
9779        if op == Opcode::NipCatch {
9780            // Discard everything above the innermost catch offset, keeping the value
9781            // on top: the frame the code after this sees is the same shape it would
9782            // have had if the `try` were not there.
9783            if let Some(base) = catch_levels.pop() {
9784                depth = base + 1;
9785            }
9786        }
9787        max_depth = max_depth.max(depth);
9788
9789        // Successors.
9790        let target = jump_target_of(code, pc, op);
9791        match op {
9792            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9793                if let Some(target) = target {
9794                    worklist.push((target, depth, catch_levels));
9795                }
9796            }
9797            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9798                if let Some(target) = target {
9799                    worklist.push((target, depth, catch_levels.clone()));
9800                }
9801                worklist.push((next, depth, catch_levels));
9802            }
9803            // A `catch` records an exception edge to the handler. The handler is
9804            // entered with the thrown value on top of the stack, in the slot the
9805            // catch offset occupies on the normal path — which is why the handler's
9806            // first instruction can `put_loc` the exception away, and why the depth
9807            // is the same on both paths.
9808            Opcode::Catch => {
9809                if let Some(target) = target {
9810                    // The handler is protected by the *enclosing* catch, not by this
9811                    // one: an error raised inside it is what the handler's own
9812                    // `catch` catches.
9813                    worklist.push((target, depth, catch_levels.clone()));
9814                }
9815                catch_levels.push(depth_before);
9816                worklist.push((next, depth, catch_levels));
9817            }
9818            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9819            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9820            // the iterator and next-method slots occupy the offset's place.
9821            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9822                if let Some(target) = target {
9823                    worklist.push((target, depth, catch_levels.clone()));
9824                }
9825                catch_levels.push(depth_before + 1);
9826                worklist.push((next, depth, catch_levels));
9827            }
9828            // `gosub` calls a subroutine with the return address on top. The opcode
9829            // table records no push for it — `ret` is what pops the slot — so the
9830            // extra one is added here, where the depth of the subroutine's first
9831            // instruction is being computed.
9832            Opcode::Gosub => {
9833                if let Some(target) = target {
9834                    worklist.push((target, depth + 1, catch_levels.clone()));
9835                }
9836                worklist.push((next, depth, catch_levels));
9837            }
9838            // `ret` goes back to a `gosub`; nothing here follows it.
9839            Opcode::Ret
9840            | Opcode::Return
9841            | Opcode::ReturnUndef
9842            | Opcode::Throw
9843            | Opcode::ThrowError => {}
9844            _ => worklist.push((next, depth, catch_levels)),
9845        }
9846    }
9847    max_depth
9848}
9849
9850/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9851/// instruction is reachable more than once.
9852fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9853    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9854    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9855        depth_at[pc] = clamped;
9856    }
9857}
9858
9859fn read_u16(code: &[u8], at: usize) -> u16 {
9860    let mut value = 0u16;
9861    for i in 0..2 {
9862        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9863    }
9864    value
9865}
9866
9867/// The absolute target of a jump instruction, if it has one.
9868fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9869    let info = op.info();
9870    let position = pc + 1;
9871    match info.format {
9872        crate::opcode::OpFormat::Label8 => {
9873            let offset = *code.get(position)? as i8 as i64;
9874            Some((position as i64 + offset) as usize)
9875        }
9876        crate::opcode::OpFormat::Label16 => {
9877            let offset = read_u16(code, position) as i16 as i64;
9878            Some((position as i64 + offset) as usize)
9879        }
9880        crate::opcode::OpFormat::Label => {
9881            let mut offset = 0i32;
9882            for i in 0..4 {
9883                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9884            }
9885            Some((position as i64 + offset as i64) as usize)
9886        }
9887        _ => None,
9888    }
9889}
9890
9891fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9892    use Opcode::*;
9893    match (op, operands.first()) {
9894        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9895            op.short_form(*value as u32).unwrap_or(op)
9896        }
9897        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9898        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9899        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9900        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9901        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9902        // A declared global is reached through its reference cell, so it shares
9903        // the `var_ref` encodings, short forms included.
9904        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9905            op.short_form(*index).unwrap_or(op)
9906        }
9907        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9908            op.short_form(*count as u32).unwrap_or(op)
9909        }
9910        _ => op,
9911    }
9912}
9913
9914/// The byte offset each instruction will start at, plus the total code size.
9915fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9916    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9917    let mut offset = 0usize;
9918    for op in chosen {
9919        offsets.push(offset);
9920        offset += op.size() as usize;
9921    }
9922    offsets.push(offset);
9923    offsets
9924}
9925
9926/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9927/// the offset actually fits.
9928///
9929/// The choice is circular: an instruction's size decides the offsets of everything after
9930/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9931/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9932/// Shrinking only ever *shortens* distances, so the loop converges.
9933///
9934/// Doing it in one pass instead — which is what this used to do — silently truncated any
9935/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9936/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9937/// with four closures in its body simply stopped, with no error and no output past the
9938/// first iteration.
9939fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9940    let mut chosen: Vec<Opcode> = kept
9941        .iter()
9942        .map(|(op, operands)| choose_short_form(*op, operands))
9943        .collect();
9944    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9945    let candidates = |op: Opcode| match op {
9946        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9947        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9948        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9949        _ => None,
9950    };
9951    loop {
9952        let offsets = instruction_offsets(&chosen);
9953        let mut changed = false;
9954        for index in 0..kept.len() {
9955            let (op, operands) = &kept[index];
9956            let Some((short, medium, has_medium)) = candidates(*op) else {
9957                continue;
9958            };
9959            if chosen[index] == short {
9960                continue;
9961            }
9962            let Some(target) = target_kept_index(operands, label_kept) else {
9963                continue;
9964            };
9965            let Some(&target_offset) = offsets.get(target) else {
9966                continue;
9967            };
9968            // A jump is relative to the byte after its opcode, which is the convention
9969            // `jump_target_of` decodes with.
9970            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9971            if (-128..=127).contains(&relative) {
9972                chosen[index] = short;
9973                changed = true;
9974            } else if has_medium
9975                && chosen[index] == Opcode::Goto
9976                && (-32_768..=32_767).contains(&relative)
9977            {
9978                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9979                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9980                // the reference encodes them.
9981                chosen[index] = medium;
9982                changed = true;
9983            }
9984        }
9985        if !changed {
9986            return chosen;
9987        }
9988    }
9989}
9990
9991fn encode_operands(
9992    code: &mut Vec<u8>,
9993    op: Opcode,
9994    operands: &[Op],
9995    position: usize,
9996    offsets: &[usize],
9997) {
9998    use crate::opcode::OpFormat::*;
9999    let info = op.info();
10000    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10001        let index = match slot {
10002            Slot::Arg(i)
10003            | Slot::Loc(i)
10004            | Slot::VarRef(i)
10005            | Slot::Global(i)
10006            | Slot::GlobalDecl(i) => i,
10007        };
10008        code.extend_from_slice(&(index as u16).to_be_bytes());
10009    };
10010    match info.format {
10011        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10012        U8 | Const8 => {
10013            if let Some(value) = operands.first().and_then(operand_uint) {
10014                code.push(value as u8);
10015            }
10016        }
10017        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10018        // like their wide counterparts, only one byte wide.
10019        Loc8 => {
10020            if let Some(Op::Slot(slot)) = operands.first() {
10021                let index = match slot {
10022                    Slot::Arg(i)
10023                    | Slot::Loc(i)
10024                    | Slot::VarRef(i)
10025                    | Slot::Global(i)
10026                    | Slot::GlobalDecl(i) => *i,
10027                };
10028                code.push(index as u8);
10029            }
10030        }
10031        I8 => {
10032            if let Some(value) = operands.first().and_then(operand_int) {
10033                code.push(value as i8 as u8);
10034            }
10035        }
10036        U16 | Npop => {
10037            if let Some(value) = operands.first().and_then(operand_int) {
10038                code.extend_from_slice(&(value as u16).to_be_bytes());
10039            }
10040        }
10041        I16 => {
10042            if let Some(value) = operands.first().and_then(operand_int) {
10043                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10044            }
10045        }
10046        I32 => {
10047            if let Some(value) = operands.first().and_then(operand_int) {
10048                code.extend_from_slice(&value.to_be_bytes());
10049            }
10050        }
10051        U32 | Const => {
10052            if let Some(value) = operands.first().and_then(operand_uint) {
10053                code.extend_from_slice(&value.to_be_bytes());
10054            }
10055        }
10056        Loc | Arg | VarRef => {
10057            if let Some(Op::Slot(slot)) = operands.first() {
10058                write_slot(code, *slot);
10059            }
10060        }
10061        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10062            if let Some(Op::AtomId(index)) = operands.first() {
10063                code.extend_from_slice(&index.to_be_bytes());
10064            }
10065            // The trailing immediate means different things per format, and the
10066            // atom forms that carry a *label* have to resolve it like any other
10067            // jump, so they cannot share the `U8`/`U16` arms above.
10068            match info.format {
10069                AtomU8 | AtomLabelU8 => {
10070                    if let Some(value) = operands.get(1).and_then(operand_uint) {
10071                        code.push(value as u8);
10072                    }
10073                }
10074                AtomU16 | AtomLabelU16 => {
10075                    if let Some(value) = operands.get(1).and_then(operand_uint) {
10076                        code.extend_from_slice(&(value as u16).to_be_bytes());
10077                    }
10078                }
10079                _ => {}
10080            }
10081        }
10082        NpopU16 => {
10083            for operand in operands.iter().take(2) {
10084                if let Some(value) = operand_uint(operand) {
10085                    code.extend_from_slice(&(value as u16).to_be_bytes());
10086                }
10087            }
10088        }
10089        Label | Label8 | Label16 | LabelU16 => {
10090            if let Some(Op::Label(label)) = operands.first() {
10091                // Labels were already remapped to kept-instruction indices.
10092                let Some(&target) = offsets.get(label.0 as usize) else {
10093                    debug_assert!(false, "label {} is past the end", label.0);
10094                    return;
10095                };
10096                let relative = target as i64 - (position as i64 + 1);
10097                match info.format {
10098                    Label8 => code.push(relative as i8 as u8),
10099                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10100                    // `label_u16` stores the target followed by an unrelated u16.
10101                    LabelU16 => {
10102                        code.extend_from_slice(&(relative as i32).to_be_bytes());
10103                        if let Some(value) = operands.get(1).and_then(operand_uint) {
10104                            code.extend_from_slice(&(value as u16).to_be_bytes());
10105                        }
10106                    }
10107                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10108                }
10109            }
10110        }
10111    }
10112}
10113
10114fn operand_int(op: &Op) -> Option<i32> {
10115    match op {
10116        Op::Int(value) => Some(*value),
10117        _ => None,
10118    }
10119}
10120
10121fn operand_uint(op: &Op) -> Option<u32> {
10122    match op {
10123        Op::Const(value) | Op::AtomId(value) => Some(*value),
10124        Op::Int(value) => Some(*value as u32),
10125        _ => None,
10126    }
10127}
10128
10129/// Disassemble a compiled function.
10130pub fn disassemble(function: &CompiledFunction) -> String {
10131    disasm::disassemble_program(function)
10132}
10133
10134/// How many of an object pattern's keys are computed.
10135///
10136/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10137/// key is not a literal, and the log is sized by walking the pattern anyway.
10138fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10139    properties
10140        .iter()
10141        .flatten()
10142        .filter(|element| {
10143            matches!(
10144                element,
10145                PatternElement::Property {
10146                    key: PropName::Computed(_),
10147                    ..
10148                }
10149            )
10150        })
10151        .count()
10152}