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    Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, ExportEntry,
27    Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
28    VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::ast::{self, *};
36
37/// A label id, local to the function being compiled.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub struct Label(u32);
40
41/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
42///
43/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
44/// is why the brackets are part of the name; nothing a program writes can collide with it.
45const HOME_OBJECT: &str = "<home_object>";
46
47/// One step of a class's initialisation, in source order.
48///
49/// A static block is not a member the class keeps — it is a run of statements that executes
50/// at the point the class definition reaches it — so it belongs *inside* the initialiser
51/// function rather than alongside the fields as a separate pass. Merging the two is what
52/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
53/// same way the reference is.
54enum StaticInitItem<'a> {
55    /// `static x = value`, or `x = value` for the instance half.
56    Field(&'a PropName, Option<&'a Expr>),
57    /// `static { … }`
58    Block {
59        body: &'a [Stmt],
60        /// Position of the `{`, which is where the reference puts the function.
61        body_start: Position,
62    },
63}
64
65/// The `var_block` sentinel for a binding that lives at function scope.
66///
67/// It has to be a value a *real* block key can never take. Block keys are source
68/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
69/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
70/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
71/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
72/// sentinel takes the slot below it.
73const FUNCTION_SCOPE: u64 = u64::MAX - 3;
74
75/// The `var_block` sentinel for a binding of the parameter list.
76///
77/// A function whose parameter list contains a default expression gets *two* variable
78/// environments: one for the parameters and one for the body, so a `var` in the body
79/// that shares a name with a parameter is a different binding. The parameter bindings
80/// therefore need a scope key of their own: reachable while the defaults are
81/// evaluated, invisible to the body, and never merged with a body `var` of the same
82/// name.
83///
84/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
85/// the closure and the body shared one slot, when only the parameters were in scope
86/// when it was created.
87const PARAM_SCOPE: u64 = u64::MAX - 4;
88
89/// The name of the hidden local a `using` declaration caches its dispose method in.
90///
91/// It has to be a name no source can produce, because a script may declare anything: the
92/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
93fn using_method_name(name: &str) -> String {
94    format!("<using.method {name}>")
95}
96
97/// The `blocks` parent sentinel for "this block has no enclosing block".
98///
99/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
100/// also the terminator the chain walk from the script body reached the file's
101/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
102/// leaked into the body scope.
103const NO_PARENT: u64 = u64::MAX - 2;
104
105/// The block key for a script body. Distinct from both sentinels and unreachable from
106/// any source offset.
107const SCRIPT_BODY: u64 = u64::MAX - 1;
108
109/// An operand of a symbolic instruction.
110#[derive(Debug, Clone, PartialEq)]
111enum Op {
112    /// An immediate integer.
113    Int(i32),
114    /// A jump target.
115    Label(Label),
116    /// A constant pool index.
117    Const(u32),
118    /// An atom, before interning.
119    Atom(Atom),
120    /// An interned atom, as an index into [`Function::atoms`].
121    AtomId(u32),
122    /// A resolved slot.
123    Slot(Slot),
124}
125
126/// Where a resolved variable lives.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128enum Slot {
129    Arg(u32),
130    Loc(u32),
131    VarRef(u32),
132    /// A global, by closure-var index.
133    Global(u32),
134    /// A global *declared* in this script. The reference keeps these bindings in
135    /// reference cells so that the script and any closure share one variable, so
136    /// a store goes through `put_var_ref` while a read uses `get_var`.
137    GlobalDecl(u32),
138}
139
140/// What a symbolic variable access does, which decides the final opcode.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142enum VarAction {
143    /// Read the value.
144    Get,
145    /// Read the value, yielding `undefined` for an undeclared global.
146    GetUndef,
147    /// Write, leaving nothing on the stack.
148    Put,
149    /// Write and initialise, leaving the value on the stack.
150    PutInit,
151    /// Write, leaving the value on the stack.
152    Set,
153    /// Initialise a binding that may only be initialised once, such as a derived
154    /// constructor's `this`.
155    PutInitChecked,
156    /// Initialise, leaving the value on the stack and without the `const` check.
157    ///
158    /// A class's own scope binding is a `const` that has to be initialised in the middle
159    /// of the definition — after the constructor exists but before the static fields run
160    /// — and the value has to survive for the outer store to use.
161    SetInit,
162    /// Write a binding that lives in a reference cell.
163    PutRef,
164}
165
166#[derive(Debug, Clone)]
167enum Insn {
168    /// A fully determined instruction.
169    Fixed { op: Opcode, operands: Vec<Op> },
170    /// A variable access, resolved in the second pass.
171    ///
172    /// `block` is the lexical block the access appears in, which is what makes
173    /// shadowing work: two bindings can share a name, and the one that wins is
174    /// whichever scope encloses the access.
175    Var {
176        action: VarAction,
177        name: String,
178        block: u64,
179        /// Whether the access was written in the parameter list; see
180        /// [`FnState::in_params`].
181        in_params: bool,
182    },
183    /// Close a binding *if* it turned out to be captured.
184    ///
185    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
186    /// only known once the body has been compiled — a closure created there is the
187    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
188    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
189    /// of emitted blind.
190    CloseCaptured { name: String, block: u64 },
191    /// `delete name`, which can only answer `false` once the binding is known.
192    ///
193    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
194    /// looks the name up on the global object, which is what distinguishes an implicit
195    /// global (configurable, deletable) from a declared one (a binding, always `false`).
196    DeleteVar { name: String },
197    /// An instruction that dead-code elimination removed. It keeps its slot so
198    /// that label indices stay valid, and resolves to no bytecode.
199    Dead,
200}
201
202/// Where `break` and `continue` jump to.
203///
204/// Targets are stacked as the compiler enters loops and labelled statements, so a
205/// bare `break` needs no analysis: it is simply the innermost target. A labelled
206/// one searches outward by name.
207#[derive(Debug, Clone)]
208struct JumpTarget {
209    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
210    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
211    /// same statement and `break a` must reach the same place as `break b`.
212    names: Vec<String>,
213    /// Where `break` lands. `None` for a construct `break` may only leave, not
214    /// target — a `try`, whose entry exists purely to unwind.
215    break_label: Option<Label>,
216    /// Where `continue` lands. `None` for anything that is not a loop.
217    continue_label: Option<Label>,
218    /// Stack slots to discard when control leaves this construct by a jump.
219    ///
220    /// Both `switch` and `try` leave something on the value stack for the duration
221    /// of the construct — the discriminant, or the `catch` offset — and a jump out
222    /// has to take it with it. A loop leaves nothing.
223    drop_count: u32,
224    /// The finalizer to run when control leaves this construct.
225    ///
226    /// Set on a `try` even when it has no `finally`: the label is always emitted and
227    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
228    /// does not have to know whether a finalizer exists.
229    finally_label: Option<Label>,
230    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
231    /// does not reach.
232    is_regular_stmt: bool,
233    /// Whether leaving this construct has to close an iterator.
234    ///
235    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
236    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
237    /// is dropped rather than closed.
238    has_iterator: bool,
239}
240
241/// `copy_data_properties` flags for an object-literal spread.
242///
243/// The byte packs three fields: the low bits are the stack offset of the source,
244/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
245/// as well as string keys. A spread passes a literal `null` exclusion list right
246/// below the source, so that field stays zero and only the source offset and the
247/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
248const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
249
250/// The expression a `...` introduces.
251///
252/// The parser marks the spread in two places — the element/property variant and an
253/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
254/// stepped through before the argument can be compiled.
255fn spread_argument(spread: &Expr) -> &Expr {
256    match &spread.kind {
257        ExprKind::Spread(inner) => inner,
258        _ => spread,
259    }
260}
261
262/// The flag byte `define_method` takes.
263///
264/// The low two bits pick value/getter/setter; bit 2 marks the property
265/// enumerable, which every object-literal method is.
266/// What kind of class constructor a function is being compiled as.
267///
268/// A constructor is not an ordinary method: a base one materialises `this` and refuses
269/// to run without `new`, and a derived one starts with `this` in the dead zone until
270/// `super()` produces it.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272enum CtorKind {
273    /// Not a class constructor.
274    None,
275    /// A constructor of a class without `extends`.
276    Base,
277    /// A constructor of a class with `extends`.
278    Derived,
279}
280
281/// The flag byte `define_method` takes for a class member.
282///
283/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
284/// a class method is *not* — that is the whole difference from an object-literal method,
285/// and the reason `Object.keys(C.prototype)` stays empty.
286fn class_method_flags(kind: MethodKind) -> i32 {
287    match kind {
288        MethodKind::Constructor | MethodKind::Method => 0,
289        MethodKind::Get => 1,
290        MethodKind::Set => 2,
291    }
292}
293
294fn define_method_flags(kind: PropertyKind) -> i32 {
295    let base = match kind {
296        PropertyKind::Value | PropertyKind::Method => 0,
297        PropertyKind::Get => 1,
298        PropertyKind::Set => 2,
299    };
300    base | 4
301}
302
303/// Convert a numeric property key to the text an atom would be made from.
304///
305/// Only the range where Rust and JavaScript agree on the spelling is accepted.
306/// Both print the shortest representation that round-trips, so plain decimal
307/// digits match; they diverge at the extremes, where JavaScript switches to an
308/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
309/// differs from the reference, those keys are rejected.
310fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
311    if !value.is_finite() {
312        return Err(SyntaxError::new(
313            "a non-finite numeric property key is not supported by the compiler yet",
314            span,
315        ));
316    }
317    if value == value.trunc() && value.abs() < 1e21 {
318        return Ok(format!("{}", value as i64));
319    }
320    if value.abs() >= 1e-6 && value.abs() < 1e21 {
321        return Ok(format!("{value}"));
322    }
323    Err(SyntaxError::new(
324        "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
325        span,
326    ))
327}
328
329/// Collect the operands of a same-operator logical run, in source order.
330///
331/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
332/// the caller appends `c`. A node with a different operator is one operand.
333fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
334    if let ExprKind::Logical {
335        op: inner_op,
336        left,
337        right,
338    } = &expr.kind
339        && *inner_op == op
340    {
341        collect_same_operator(op, left, out);
342        out.push(right);
343        return;
344    }
345    out.push(expr);
346}
347
348/// The jump a logical assignment or `??` takes when the value is kept.
349///
350/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
351/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
352/// the value when it is *not* null-ish, so it is the `if_false` side.
353fn logical_jump(op: AssignOp) -> Opcode {
354    match op {
355        AssignOp::Or => Opcode::IfTrue,
356        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
357        _ => Opcode::IfFalse,
358    }
359}
360
361/// Whether a loop enumerates keys or values.
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
363enum ForLoopKind {
364    /// `for (x in o)` — the keys of an object.
365    In,
366    /// `for (x of o)` — the values of an iterable.
367    Of,
368    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
369    AwaitOf,
370}
371
372/// Which part of a `try` statement a block key refers to.
373#[derive(Debug, Clone, Copy)]
374enum TryPart {
375    /// The guarded block.
376    Block = 0,
377    /// The handler body, excluding the catch parameter.
378    Catch = 1,
379    /// The finalizer block.
380    Finally = 2,
381    /// The catch parameter's own scope.
382    Param = 3,
383}
384
385/// A lexical scope, identified while hoisting and numbered at the end.
386///
387/// Scope identity is needed in two passes that must agree: declarations are
388/// hoisted in source order (so slots come out in source order, as in the
389/// reference), but a binding belongs to the block it was written in, which is only
390/// entered later. Blocks are therefore keyed by the source position of their
391/// opening brace, which is stable across both walks.
392#[derive(Debug, Clone, Copy)]
393struct Block {
394    /// Source position of the block.
395    key: u64,
396    /// The block this one is nested in; `0` for the function scope.
397    parent: u64,
398}
399
400/// One function under construction.
401struct FnState {
402    name: String,
403    kind: FunctionKind,
404    strict: bool,
405    args: Vec<VarDef>,
406    vars: Vec<VarDef>,
407    closure_vars: Vec<ClosureVar>,
408    cpool: Vec<Constant>,
409    atoms: Vec<Atom>,
410    /// Every lexical scope, in creation order.
411    blocks: Vec<Block>,
412    /// The block currently being parsed or compiled.
413    current_block: u64,
414    /// The block a *nested* function was created in, so a capture made from here can be
415    /// resolved against the enclosing function's lexical scopes rather than against a
416    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
417    /// function's own `let S` instead of the class body's `const S`.
418    created_in_block: u64,
419    /// The block each local was declared in, parallel to `vars`. `0` means the
420    /// function scope, where `var` bindings live.
421    var_block: Vec<u64>,
422    /// Set when the expression just compiled left no value on the stack.
423    ///
424    /// Only a store can do that: `put_field` consumes the object and the value, so
425    /// an assignment whose result is unused emits nothing extra. The expression
426    /// statement then has nothing to drop.
427    no_value: bool,
428    /// Whether a label was placed since the last instruction was emitted.
429    ///
430    /// The `put`/`get` fold is only valid when the two are adjacent in the final
431    /// stream; a label in between means a jump can land on the read, so the store has
432    /// to keep consuming its value. A flag is enough and avoids having to reason about
433    /// which index a label recorded.
434    label_since_insn: bool,
435    /// Whether the value of the expression being compiled is thrown away.
436    ///
437    /// Only an expression *statement* discards its value, and only the outermost
438    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
439    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
440    /// the one construct whose bytecode depends on it.
441    discard_value: bool,
442    /// The block that holds the function body.
443    body_block: u64,
444    /// Head of each scope's binding chain, indexed by level. Filled in by
445    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
446    block_heads: Vec<i32>,
447    /// Enclosing `break`/`continue` targets, innermost last.
448    jump_targets: Vec<JumpTarget>,
449    insns: Vec<Insn>,
450    labels: Vec<Option<usize>>,
451    /// Captured locals, which need a reference cell.
452    var_ref_count: u32,
453    line: u32,
454    column: u32,
455    /// Whether this is a script body. A script's top-level declarations create
456    /// global properties rather than locals, which is why they show up as
457    /// closure variables with `[global_decl]`.
458    is_script: bool,
459    /// Whether this is a module body.
460    ///
461    /// A module body is a script in every respect that matters here — no `arguments`,
462    /// no `this` of its own — but its top-level declarations are *module*-scoped
463    /// instead of global, which is what this flag changes.
464    is_module: bool,
465    /// Whether the function is an arrow, which never gets its own `arguments`.
466    is_arrow: bool,
467    /// The name a *named function expression* binds inside its own body.
468    /// How many parameters count towards `.length`.
469    defined_args: u32,
470    /// Parameters that are not a plain name, with the argument slot each came from.
471    param_prologue: Vec<(usize, Pattern)>,
472    /// What kind of class constructor this function is, if any.
473    ctor_kind: CtorKind,
474    /// Whether the class has instance fields, so the constructor has to run their
475    /// initialiser before it returns.
476    has_instance_fields: bool,
477    /// What the nested function about to be compiled should be told about its class.
478    class_ctor_pending: Option<(CtorKind, bool)>,
479    /// Whether this function needs the hidden `this` local, because an arrow inside it
480    /// refers to `this`.
481    ///
482    /// An arrow has no `this` of its own, so the reference materialises the enclosing
483    /// function's receiver into a local and lets the arrow capture it as an ordinary
484    /// closure variable. Declaring the local is not enough on its own: the store that
485    /// fills it has to be prepended to the body, which is what this flag arranges.
486    needs_this_local: bool,
487    /// The same, for `arguments`.
488    needs_arguments_local: bool,
489    /// The same, for `new.target`.
490    needs_new_target_local: bool,
491    /// Whether the body already opens by filling a `this` local, which
492    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
493    has_this_prologue: bool,
494    /// The same, for `<home_object>`: the object `super` resolves against.
495    ///
496    /// An arrow and a static block have no home object of their own — only the method or
497    /// initialiser they were written in does — so `super.x` inside one is a read of the
498    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
499    /// by `special_object 4`, the same way `this` is.
500    needs_home_object_local: bool,
501    /// Hidden locals of the `with` blocks currently open, innermost last.
502    with_names: Vec<String>,
503    /// Set while a with-guard is being emitted, so the guard's own accesses are not
504    /// wrapped in another guard.
505    emitting_with_guard: bool,
506    self_name: Option<String>,
507    /// Where the function body starts, in source order; see [`Function::body_start`].
508    body_start: (u32, u32),
509    /// Whether the body contains a *direct* `eval(...)` call.
510    ///
511    /// A direct eval sees every binding of the function that called it, including ones
512    /// no other code mentions. It also hands those bindings to any closure it creates,
513    /// which can outlive the function. Both need the bindings to live in cells, so this
514    /// flag makes the function treat all of them as captured.
515    has_direct_eval: bool,
516    /// Whether the parameter list contains a default expression, which is what gives
517    /// the function a second variable environment (see [`PARAM_SCOPE`]).
518    has_parameter_expressions: bool,
519    /// Whether the instructions being emitted belong to the parameter list.
520    ///
521    /// References made here must not see the body's `var`s: the body has not run yet,
522    /// and the reference's own model keeps the two scopes apart.
523    in_params: bool,
524    /// Whether an arrow created in this function's parameter list needs the parameter
525    /// scope's `arguments` binding.
526    needs_param_arguments: bool,
527    /// Whether this function was *created* inside a parameter list.
528    ///
529    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
530    /// arrow too. The name reference is the arrow's, but the scope it must not see
531    /// belongs to the function the arrow was born in.
532    created_in_params: bool,
533    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
534    ///
535    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
536    /// final while the body is still being compiled: a named function expression declares
537    /// its own name binding *after* the body, and that binding is exactly what
538    /// `eval("myfunc = 1")` has to find.
539    eval_sites: Vec<EvalSite>,
540    /// Direct `eval` call sites seen so far: where, and the block that was current.
541    pending_eval_sites: Vec<(Span, u64, bool)>,
542    /// Whether this body contains `await`.
543    ///
544    /// For a *module* this decides whether its body is an async function: top-level
545    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
546    /// to survive to the compiled function rather than being a local of the compiler.
547    has_await: bool,
548    /// The module tables, when this body is a module.
549    ///
550    /// Only the top-level state ever has one: `export` and `import` are top-level
551    /// statements, so nothing nested can add to these tables.
552    module: Option<ModuleMeta>,
553    /// Whether the self-name prologue (`special_object 2` then the store) has been
554    /// emitted for this function.
555    ///
556    /// A *nested* function's lookup declares the binding early (see
557    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
558    /// prologue is still needed — the binding existing is not the same as it being
559    /// initialised.
560    self_name_initialized: bool,
561    /// Whether the code emitted so far leaves the program's result on the stack.
562    /// The reference tracks this for the hidden `<ret>` local of an eval script.
563    leaves_value: bool,
564    /// Statement nesting depth, used to tell top-level statements apart.
565    stmt_depth: u32,
566    /// Function declarations waiting to be instantiated at scope entry, as
567    /// (target slot, constant pool index). The reference emits these from
568    /// `instantiate_hoisted_definitions` rather than at the statement, because a
569    /// declaration is visible before it is reached.
570    hoisted: Vec<(u64, HoistTarget, u32)>,
571    /// Function declarations whose bodies are compiled only once the enclosing scope
572    /// has finished hoisting, as (owning block, declaration).
573    ///
574    /// Compiling a body at the declaration makes the result depend on source order: in
575    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
576    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
577    /// names first and the bodies second is what removes that dependence.
578    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
579    /// The source position of the node being compiled. Every instruction emitted
580    /// takes it, which is how the position table that feeds stack traces is built.
581    cur_pos: Option<Position>,
582    /// One position per entry in `insns`, index-aligned.
583    insn_pos: Vec<Option<Position>>,
584}
585
586/// Where a hoisted function declaration is stored.
587#[derive(Debug, Clone)]
588enum HoistTarget {
589    Arg(u32),
590    Loc(u32),
591    /// A global, which the resolver looks up by name.
592    Global(String),
593}
594
595impl FnState {
596    /// Whether this function suspends: a generator or an async function.
597    ///
598    /// A suspending function's `return` is a `return_async` and its body starts with an
599    /// `initial_yield`, so almost every statement that touches control flow asks this.
600    fn is_suspending(&self) -> bool {
601        self.kind.is_generator() || self.kind.is_async()
602    }
603
604    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
605        FnState {
606            name: name.into(),
607            kind,
608            strict: false,
609            args: Vec::new(),
610            vars: Vec::new(),
611            closure_vars: Vec::new(),
612            cpool: Vec::new(),
613            atoms: Vec::new(),
614            blocks: Vec::new(),
615            current_block: 0,
616            created_in_block: NO_PARENT,
617            var_block: Vec::new(),
618            no_value: false,
619            label_since_insn: false,
620            discard_value: false,
621            body_block: 0,
622            block_heads: Vec::new(),
623            jump_targets: Vec::new(),
624            insns: Vec::new(),
625            labels: Vec::new(),
626            var_ref_count: 0,
627            line: 1,
628            column: 1,
629            is_script: false,
630            is_module: false,
631            is_arrow: false,
632            defined_args: 0,
633            param_prologue: Vec::new(),
634            ctor_kind: CtorKind::None,
635            has_instance_fields: false,
636            class_ctor_pending: None,
637            needs_this_local: false,
638            needs_arguments_local: false,
639            needs_new_target_local: false,
640            has_this_prologue: false,
641            needs_home_object_local: false,
642            with_names: Vec::new(),
643            emitting_with_guard: false,
644            self_name: None,
645            has_direct_eval: false,
646            body_start: (0, 0),
647            has_parameter_expressions: false,
648            in_params: false,
649            needs_param_arguments: false,
650            created_in_params: false,
651            eval_sites: Vec::new(),
652            pending_eval_sites: Vec::new(),
653            has_await: false,
654            module: None,
655            self_name_initialized: false,
656            leaves_value: false,
657            stmt_depth: 0,
658            hoisted: Vec::new(),
659            deferred_funcs: Vec::new(),
660            cur_pos: None,
661            insn_pos: Vec::new(),
662        }
663    }
664
665    /// The scope a declaration lands in: a script's top-level declarations are
666    /// globals, everything else gets a slot.
667    /// Whether a binding declared *now* becomes a property of the global object.
668    ///
669    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
670    /// The `var` case is decided by the keyword rather than by the cursor position:
671    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
672    /// binding as a `var i` in the body, even though the head has its own block.
673    fn declares_globally(&self, def: &VarDef) -> bool {
674        // A module's top-level declarations are *module*-scoped: they live in the module
675        // record, never on the global object. Two modules can both declare `var x`
676        // without seeing each other, which is the whole point.
677        if self.is_module {
678            return false;
679        }
680        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
681    }
682}
683
684/// The compiler's entry point.
685pub struct Compiler {
686    module: bool,
687    /// Whether the program itself is the body of an `async` function.
688    ///
689    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
690    /// completion value is wrapped so a returned promise is not adopted.
691    async_body: bool,
692    /// Enclosing functions, outermost first. The last entry is the current one.
693    stack: Vec<FnState>,
694}
695
696/// Compile a script.
697pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
698    Compiler::new(false).compile(program)
699}
700
701/// Compile a script whose top level is the body of an `async` function.
702///
703/// The body is an ordinary script in every other way — it still reports a completion value
704/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
705/// it answers a promise instead of a value. The wrapper is what keeps that promise from
706/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
707/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
708/// documents.
709pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
710    Compiler::for_suspensible_script().compile(program)
711}
712
713/// Compile a module.
714pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
715    Compiler::new(true).compile(program)
716}
717
718impl Compiler {
719    /// Create a compiler.
720    pub fn new(module: bool) -> Compiler {
721        Compiler {
722            module,
723            async_body: false,
724            stack: Vec::new(),
725        }
726    }
727
728    /// Create a compiler for a script whose top level is an `async` function body.
729    fn for_suspensible_script() -> Compiler {
730        Compiler {
731            module: false,
732            async_body: true,
733            stack: Vec::new(),
734        }
735    }
736
737    /// Compile a whole program into its top-level function.
738    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
739        let mut state = FnState::new("<eval>", FunctionKind::Normal);
740        // A module body is *not* a script: it has no completion value, so no hidden
741        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
742        // is having no `arguments` of its own and no receiver — see `is_module`.
743        state.is_script = !self.module;
744        state.is_module = self.module;
745        if self.module {
746            state.module = Some(ModuleMeta::default());
747        }
748        state.strict = program.strict || self.module;
749        state.line = program.span.start.line;
750        state.column = program.span.start.column;
751        // Locals are numbered in declaration order; `<ret>` is always slot 0.
752        //
753        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
754        // slot that only appears in one of the two arrays shifts every later
755        // binding's block and silently loses the temporal-dead-zone marking for
756        // the script's own blocks. A function frame has no `<ret>`, which is why
757        // the misalignment only showed up at the top level.
758        if !self.module {
759            state.vars.push(VarDef::var("<ret>"));
760            state.var_block.push(FUNCTION_SCOPE);
761        }
762        self.stack.push(state);
763        // The body is its own scope, keyed by the position of the program.
764        // The script body needs a key no statement can produce. Statement keys are
765        // source offsets, and the program's own start offset is `0` — which is also
766        // the offset of the first statement, so a top-level `{ let x }` or
767        // `for (let i …)` used to share the body's block and lose its scope.
768        let body_key = SCRIPT_BODY;
769        self.push_block(body_key, NO_PARENT);
770        self.state().body_block = body_key;
771        // A module body opens with a re-entry guard. The host evaluates a module exactly
772        // once, so the guard never fires in practice — but the reference emits it, and a
773        // module function called a second time (through `eval` of its own source, say)
774        // must not run its body again.
775        let module_guard = self.module.then(|| self.new_label());
776        if let Some(body) = module_guard {
777            // The guard wraps the *hoisting* too: a second evaluation of the same module
778            // body must not even re-create its function declarations.
779            self.emit(Opcode::PushThis, &[]);
780            self.emit_jump(Opcode::IfFalse, body, &[]);
781        }
782        self.hoist(&program.body, body_key)?;
783        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
784        // come before the guard's `return_undef`: the reference's jump target sits past
785        // both, and a second evaluation therefore re-creates nothing.
786        self.emit_scope_enter(body_key);
787        if let Some(body) = module_guard {
788            self.emit(Opcode::ReturnUndef, &[]);
789            self.place_label(body);
790        }
791        // Through `stmts` rather than the loop, so a `using` region at the top level of an
792        // eval'd body or a module gets its disposal epilogue like any other block.
793        self.stmts(&program.body)?;
794        if self.module {
795            // A module has no completion value; its body simply ends.
796            self.emit(Opcode::Undefined, &[]);
797            self.emit(Opcode::ReturnAsync, &[]);
798            // Top-level `await` makes the body an async function, so the host runs it as
799            // a coroutine and waits. Without this the `await` opcode would suspend in a
800            // body that nothing knows how to resume — which is what "a generator body ran
801            // as an ordinary call" was reporting.
802            if self.cur().has_await {
803                self.state().kind = FunctionKind::Async;
804            }
805        } else if self.async_body {
806            // An async body reports its completion value the same way, but through an
807            // object: the function answers a promise, and resolving that promise *with*
808            // the completion value would adopt a promise completion instead of reporting
809            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
810            // resolve to `{value: <promise>}` rather than to `7`.
811            //
812            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
813            // value in an object so that promises can be safely returned").
814            self.emit(Opcode::Object, &[]);
815            self.emit(Opcode::Dup, &[]);
816            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
817            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
818            self.emit(Opcode::Return, &[]);
819            self.state().kind = FunctionKind::Async;
820        } else {
821            // The program's value is whatever the last expression statement stored in
822            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
823            // case into a single `set_loc0`.
824            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
825            self.emit(Opcode::Return, &[]);
826        }
827        Ok(self.finish_current())
828    }
829
830    // -- emitting ----------------------------------------------------------
831
832    fn state(&mut self) -> &mut FnState {
833        self.stack.last_mut().expect("a function is being compiled")
834    }
835
836    fn cur(&self) -> &FnState {
837        self.stack.last().expect("a function is being compiled")
838    }
839
840    fn emit(&mut self, op: Opcode, operands: &[Op]) {
841        self.state().label_since_insn = false;
842        let pos = self.cur().cur_pos;
843        self.state().insns.push(Insn::Fixed {
844            op,
845            operands: operands.to_vec(),
846        });
847        self.state().insn_pos.push(pos);
848    }
849
850    /// Reset the script's hidden return value to `undefined`.
851    ///
852    /// Called at the start of every statement that does not itself produce the
853    /// program's value, which is how the reference keeps `if`/loop results from
854    /// leaking into an eval result.
855    fn reset_value(&mut self) {
856        if !self.cur().is_script {
857            return;
858        }
859        self.emit(Opcode::Undefined, &[]);
860        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
861        self.state().leaves_value = false;
862    }
863
864    /// Whether `name` is a local or argument slot rather than a global.
865    fn is_slot(&self, name: &str) -> bool {
866        self.cur().vars.iter().any(|v| v.name == name)
867            || self.cur().args.iter().any(|a| a.name == name)
868    }
869
870    /// `with (object) body`
871    ///
872    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
873    /// what makes the object reachable from a closure created inside the block, and it
874    /// is also what lets an `eval` find it: the runtime collects the active `With`
875    /// locals of every frame and resolves names against them before the realm.
876    ///
877    /// Inside the block every name reference is spelled as "look in the with objects
878    /// first", innermost outwards, and falls through to the ordinary access. The test is
879    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
880    /// Record asks.
881    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
882        let name = self.next_with_name();
883        // The object expression is evaluated *outside* the scope it introduces, so no
884        // wrapper may be emitted for the names it mentions.
885        let saved = std::mem::take(&mut self.state().with_names);
886        self.expr(object)?;
887        self.state().with_names = saved;
888        self.emit(Opcode::ToObject, &[]);
889        self.declare_hidden_local(&name, VarKind::With);
890        // Pushed before the store so the store itself is not guarded by an *outer*
891        // `with` — the object being stored is the new one, not something to look up.
892        self.state().with_names.push(name.clone());
893        self.emit_var(VarAction::Put, &name);
894        let result = self.stmt(body);
895        self.state().with_names.pop();
896        result
897    }
898
899    /// A hidden-local name for one `with` block, distinct from every enclosing one.
900    fn next_with_name(&self) -> String {
901        let depth = self.cur().with_names.len();
902        if depth == 0 {
903            "<with>".to_string()
904        } else {
905            format!("<with{depth}>")
906        }
907    }
908
909    /// Declare a hidden local that must stay a *local* even in a script.
910    ///
911    /// A script's `var` is a property of the global object, but the `with` object is not
912    /// part of the source program's name space at all — it only exists for the compiler
913    /// and the runtime — so it goes straight into the frame's slot list.
914    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
915        let state = self.state();
916        if state.vars.iter().any(|v| v.name == name) {
917            return;
918        }
919        state.var_block.push(FUNCTION_SCOPE);
920        state.vars.push(VarDef {
921            kind,
922            ..VarDef::var(name)
923        });
924    }
925
926    /// Emit a name access, guarded by every active `with` object.
927    ///
928    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
929    /// the read itself; the outer guards and the plain access are what the `if_false`
930    /// jumps to, so the innermost object wins.
931    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
932        let names = self.cur().with_names.clone();
933        let done = self.new_label();
934        let mut starts = Vec::new();
935        // Innermost object first: the last `with` opened is the one that shadows the
936        // others, so its guard has to be the first chance to satisfy the name.
937        for with_name in names.iter().rev() {
938            let next = self.new_label();
939            // `in` takes the key then the object.
940            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
941            self.emit_var(VarAction::Get, with_name);
942            self.emit(Opcode::In, &[]);
943            self.emit_jump(Opcode::IfFalse, next, &[]);
944            starts.push(next);
945            match action {
946                // A store keeps the value under the receiver, which is where
947                // `put_field` expects it.
948                VarAction::Put | VarAction::PutInit => {
949                    self.emit_var(VarAction::Get, with_name);
950                    self.emit(Opcode::Swap, &[]);
951                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
952                }
953                _ => {
954                    self.emit_var(VarAction::Get, with_name);
955                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
956                    self.emit(Opcode::GetArrayEl, &[]);
957                }
958            }
959            self.emit_jump(Opcode::Goto, done, &[]);
960            self.place_label(next);
961        }
962        self.emit_var(action, name);
963        self.place_label(done);
964    }
965
966    fn emit_var(&mut self, action: VarAction, name: &str) {
967        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
968        // stores and keeps the value in one instruction. The reference does this
969        // in a post-pass; folding it at emit time keeps instruction indices
970        // stable, which matters because labels are recorded as indices.
971        //
972        // Only slots have a `set_` form: a global is stored with `put_var` and
973        // read with `get_var`, and the reference does not fold those.
974        //
975        // A label between the two cancels the fold. `set_x v` leaves the value on
976        // the stack, which is only equivalent when the read immediately follows the
977        // store; when a jump target sits in between, the store must *consume* the
978        // value and the read must fetch it afresh. A loop head is exactly that
979        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
980        // condition re-reads it — and folding across the label would make the
981        // condition compare whatever the previous iteration left on the stack.
982        if action == VarAction::Get {
983            let is_slot = self.is_slot(name);
984            let at_label = std::mem::take(&mut self.state().label_since_insn);
985            //
986            // `arguments` is excluded because the reference treats it as a special
987            // binding: it is initialised once and read many times, and folding its
988            // initialisation into a `set_` would leave the object on the stack where
989            // the reference leaves nothing.
990            if is_slot
991                && name != "arguments"
992                && !at_label
993                && let Some(Insn::Var {
994                    action: previous,
995                    name: previous_name,
996                    ..
997                }) = self.state().insns.last_mut()
998                && *previous == VarAction::Put
999                && previous_name == name
1000            {
1001                *previous = VarAction::Set;
1002                return;
1003            }
1004        }
1005        // Inside a `with`, every name lookup consults the with objects first. The
1006        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1007        let guarded = !self.cur().with_names.is_empty()
1008            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1009            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1010            && !self.state().emitting_with_guard;
1011        if guarded {
1012            self.state().emitting_with_guard = true;
1013            self.emit_with_guarded(action, name);
1014            self.state().emitting_with_guard = false;
1015            return;
1016        }
1017        let block = self.cur().current_block;
1018        self.state().label_since_insn = false;
1019        let pos = self.cur().cur_pos;
1020        let in_params = self.cur().in_params;
1021        self.state().insns.push(Insn::Var {
1022            action,
1023            name: name.to_string(),
1024            block,
1025            in_params,
1026        });
1027        self.state().insn_pos.push(pos);
1028    }
1029
1030    fn new_label(&mut self) -> Label {
1031        let state = self.state();
1032        state.labels.push(None);
1033        Label(state.labels.len() as u32 - 1)
1034    }
1035
1036    fn place_label(&mut self, label: Label) {
1037        let index = self.cur().insns.len();
1038        self.state().label_since_insn = true;
1039        self.state().labels[label.0 as usize] = Some(index);
1040    }
1041
1042    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1043        let mut operands = vec![Op::Label(label)];
1044        operands.extend_from_slice(extra);
1045        self.emit(op, &operands);
1046    }
1047
1048    // -- scopes ------------------------------------------------------------
1049
1050    /// Start a new lexical scope inside `parent`.
1051    fn push_block(&mut self, key: u64, parent: u64) {
1052        let state = self.state();
1053        if !state.blocks.iter().any(|b| b.key == key) {
1054            state.blocks.push(Block { key, parent });
1055        }
1056        state.current_block = key;
1057    }
1058
1059    /// Emit the code that runs when a lexical scope is entered.
1060    ///
1061    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1062    /// so entering its block marks it uninitialised. Hoisted function
1063    /// declarations are created here instead, which is why a call before the
1064    /// declaration still works.
1065    ///
1066    /// The order is not obvious: bindings are emitted in *reverse* declaration
1067    /// order, because the reference walks its scope chain, which is built by
1068    /// prepending.
1069    fn emit_scope_enter(&mut self, block: u64) {
1070        let hoisted = std::mem::take(&mut self.state().hoisted);
1071        let mut mine: Vec<(HoistTarget, u32)> = hoisted
1072            .into_iter()
1073            .filter(|(owner, _, _)| *owner == block)
1074            .map(|(_, target, pool_index)| (target, pool_index))
1075            .collect();
1076        mine.sort_by_key(|(target, _)| match target {
1077            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1078            HoistTarget::Global(_) => u32::MAX,
1079        });
1080        for (target, pool_index) in mine {
1081            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1082            match target {
1083                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1084                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1085                HoistTarget::Global(name) => {
1086                    // A global binding lives in a reference cell, so the store
1087                    // goes through `put_var_ref` while reads use `get_var`.
1088                    let block = self.cur().current_block;
1089                    let pos = self.cur().cur_pos;
1090                    let in_params = self.cur().in_params;
1091                    self.state().insns.push(Insn::Var {
1092                        action: VarAction::PutRef,
1093                        name,
1094                        block,
1095                        in_params,
1096                    });
1097                    self.state().insn_pos.push(pos);
1098                }
1099            }
1100        }
1101        for index in self.block_vars_reversed(block) {
1102            self.emit(
1103                Opcode::SetLocUninitialized,
1104                &[Op::Slot(Slot::Loc(index as u32))],
1105            );
1106        }
1107    }
1108
1109    /// Emit the code that runs when a lexical scope is exited.
1110    ///
1111    /// A captured binding has to be closed: detaching its reference cell freezes
1112    /// the value the binding had when the block ended, which is what a closure
1113    /// created inside the block must keep seeing.
1114    fn emit_scope_leave(&mut self, block: u64) {
1115        for index in self.block_vars_reversed(block) {
1116            if self.cur().vars[index].is_captured {
1117                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1118            }
1119        }
1120    }
1121
1122    /// Locals declared in `block`, in reverse declaration order.
1123    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1124        let state = self.cur();
1125        let mut out: Vec<usize> = (0..state.vars.len())
1126            .filter(|index| {
1127                state.var_block.get(*index).copied() == Some(block) && state.vars[*index].is_lexical
1128            })
1129            .collect();
1130        out.reverse();
1131        out
1132    }
1133
1134    /// Declare a local, even at the top level of a script.
1135    ///
1136    /// A `catch` parameter is always a local: the reference puts it in the
1137    /// function's own variable list (`1: catch e`), never in the global object,
1138    /// because it only exists while the handler runs.
1139    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1140        let state = self.state();
1141        let index = state.vars.len() as u32;
1142        // A `catch` parameter belongs to a scope even though it is not lexical: the
1143        // runtime instantiates it per handler entry, but it never sits in the
1144        // temporal dead zone.
1145        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1146            state.current_block
1147        } else {
1148            0
1149        };
1150        state.var_block.push(block);
1151        state.vars.push(def);
1152        index
1153    }
1154
1155    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1156        if self.cur().is_module
1157            && self.cur().current_block == self.cur().body_block
1158            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1159        {
1160            // Only the body's own block: a `let` inside a module-level `{}` is still an
1161            // ordinary local of that block, not a module variable.
1162            //
1163            // A `using` binding is excluded on purpose, and the reference excludes it in
1164            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1165            // "'using' variables are currently not exported in modules"): a module-level
1166            // `using` is an ordinary *local* of the module body function, not a module
1167            // cell. Two things follow, and both are what the reference does — `export {a}`
1168            // of a `using` binding is "exported variable 'a' does not exist", and
1169            // disposal works, because the disposal epilogue addresses locals by slot.
1170            //
1171            // The hidden dispose-method variable is excluded for a stronger reason: it is
1172            // *always* a local (`add_scope_var` in the reference), and it must sit
1173            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1174            return self.declare_module(name, &def);
1175        }
1176        if self.cur().declares_globally(&def) {
1177            self.declare_global(name, &def);
1178            return 0;
1179        }
1180        let state = self.state();
1181        let index = state.vars.len() as u32;
1182        let block = if def.is_lexical {
1183            state.current_block
1184        } else {
1185            0
1186        };
1187        state.var_block.push(block);
1188        state.vars.push(def);
1189        index
1190    }
1191
1192    /// Declare a `using` binding and its cached dispose method, returning both slots.
1193    ///
1194    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1195    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1196    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1197        let mut def = VarDef::lexical(name);
1198        def.kind = VarKind::Using;
1199        let value = self.declare(name, def);
1200        let mut method = VarDef::lexical(using_method_name(name));
1201        method.kind = VarKind::UsingMethod;
1202        let method_slot = self.declare(&using_method_name(name), method);
1203        (value, method_slot)
1204    }
1205
1206    /// The slot a `using` binding's dispose method lives in.
1207    fn using_method_slot(&self, name: &str) -> Option<u32> {
1208        let hidden = using_method_name(name);
1209        self.cur()
1210            .vars
1211            .iter()
1212            .position(|var| var.name == hidden)
1213            .map(|index| index as u32)
1214    }
1215
1216    // -- statements --------------------------------------------------------
1217
1218    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1219        self.stmt_labelled(stmt, &[])
1220    }
1221
1222    /// Compile a statement that a chain of labels names.
1223    ///
1224    /// Only a loop consumes `labels`; every other statement ignores them (the
1225    /// parser has already rejected a label on a statement that cannot use it).
1226    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1227        // Only a *top-level* expression statement supplies the program's value.
1228        let saved = self.cur().leaves_value;
1229        self.state().leaves_value =
1230            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1231        self.state().stmt_depth += 1;
1232        let result = self.stmt_inner(stmt, labels);
1233        self.state().stmt_depth -= 1;
1234        // A nested statement never contributes the program's value, so the flag
1235        // the wrapper set above is what survives.
1236        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1237        self.state().leaves_value = produced;
1238        let _ = saved;
1239        result
1240    }
1241
1242    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1243        match &stmt.kind {
1244            StmtKind::Empty | StmtKind::Debugger => {}
1245            StmtKind::Expr(expr) => {
1246                // The statement's first token is a position the reference records: an
1247                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1248                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1249                // is why an error from a construct with no position of its own (`[...it]`
1250                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1251                let saved = self.cur().cur_pos;
1252                self.state().cur_pos = Some(expr.span.start);
1253                // An expression statement's value is thrown away — except in a
1254                // script, where it becomes the program's result. `assign` reads this
1255                // and clears it, so a nested assignment still produces a value.
1256                self.state().discard_value = !self.cur().is_script;
1257                let result = self.expr(expr);
1258                self.state().discard_value = false;
1259                result?;
1260                if std::mem::take(&mut self.state().no_value) {
1261                    // A store whose value was discarded left nothing to drop.
1262                } else if self.cur().is_script {
1263                    // The program's value lands in the hidden `<ret>` local.
1264                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1265                } else {
1266                    self.emit(Opcode::Drop, &[]);
1267                }
1268                // Restored last: the trailing `drop` is part of the statement, and in the
1269                // reference it simply inherits whatever the expression last recorded.
1270                self.state().cur_pos = saved;
1271            }
1272            StmtKind::Block(body) => {
1273                // The block's declarations were hoisted with its enclosing
1274                // statement list, so there is nothing left to declare here.
1275                let key = stmt.span.start.offset as u64;
1276                let parent = self.cur().current_block;
1277                self.push_block(key, parent);
1278                self.emit_scope_enter(key);
1279                // A block is where a `using` region lives, so its statements have to go
1280                // through `stmts`: that is what emits the disposal epilogue.
1281                self.stmts(body)?;
1282                self.emit_scope_leave(key);
1283                self.state().current_block = parent;
1284            }
1285            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1286            // A function declaration was already instantiated when its scope was
1287            // entered, so the statement itself emits nothing.
1288            StmtKind::FuncDecl(_) => {}
1289            StmtKind::If { test, cons, alt } => {
1290                self.reset_value();
1291                let else_label = self.new_label();
1292                let end_label = self.new_label();
1293                self.expr(test)?;
1294                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1295                self.stmt(cons)?;
1296                if alt.is_some() {
1297                    self.emit_jump(Opcode::Goto, end_label, &[]);
1298                }
1299                self.place_label(else_label);
1300                if let Some(alt) = alt {
1301                    self.stmt(alt)?;
1302                    self.place_label(end_label);
1303                }
1304            }
1305            StmtKind::While { test, body } => {
1306                self.reset_value();
1307                let top = self.new_label();
1308                let end = self.new_label();
1309                self.place_label(top);
1310                self.expr(test)?;
1311                // The condition's false branch and `break` share one target,
1312                // which is why a `while` loop needs only one end label.
1313                self.emit_jump(Opcode::IfFalse, end, &[]);
1314                self.loop_body(body, labels, top, end)?;
1315                self.emit_jump(Opcode::Goto, top, &[]);
1316                self.place_label(end);
1317            }
1318            StmtKind::DoWhile { body, test } => {
1319                self.reset_value();
1320                let top = self.new_label();
1321                let cont = self.new_label();
1322                let end = self.new_label();
1323                self.place_label(top);
1324                // `continue` in a `do…while` runs the test, so it lands on `cont`
1325                // rather than on the loop head.
1326                self.loop_body(body, labels, cont, end)?;
1327                self.place_label(cont);
1328                self.expr(test)?;
1329                self.emit_jump(Opcode::IfTrue, top, &[]);
1330                self.place_label(end);
1331            }
1332            StmtKind::For {
1333                init,
1334                test,
1335                update,
1336                body,
1337            } => {
1338                self.reset_value();
1339                let for_key = stmt.span.start.offset as u64;
1340                let for_parent = self.cur().current_block;
1341                self.push_block(for_key, for_parent);
1342                self.emit_scope_enter(for_key);
1343                if let Some(init) = init {
1344                    match init {
1345                        ForInit::VarDecl(decl) => {
1346                            self.var_decl(decl)?;
1347                        }
1348                        ForInit::Expr(expr) => {
1349                            // The head's value is discarded. Saying so lets an
1350                            // assignment store with `put` instead of `dup`+`put`, which
1351                            // is what the reference emits — and the difference matters:
1352                            // a `dup`/`drop` pair around the store gives the peephole a
1353                            // chance to fold the store into the *condition's* read.
1354                            self.state().discard_value = true;
1355                            let result = self.expr(expr);
1356                            self.state().discard_value = false;
1357                            result?;
1358                            if !std::mem::take(&mut self.state().no_value) {
1359                                self.emit(Opcode::Drop, &[]);
1360                            }
1361                        }
1362                    }
1363                }
1364                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1365                // so a closure made in the body captures that iteration's value
1366                // instead of sharing one. The reference expresses this with
1367                // `close_loc`, which swaps in a new reference cell holding the
1368                // current value; the three points below are the ones it uses — after
1369                // the initialiser, before the update, and after the loop.
1370                let loop_bindings = match init {
1371                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1372                        let mut names: Vec<String> = Vec::new();
1373                        for declarator in &decl.declarators {
1374                            let mut idents = Vec::new();
1375                            declarator.target.bound_names(&mut idents);
1376                            names.extend(idents.into_iter().map(|ident| ident.name));
1377                        }
1378                        names
1379                    }
1380                    _ => Vec::new(),
1381                };
1382                // The reference also closes right after the initialiser, so the first
1383                // iteration's closures get their own cell rather than sharing the one
1384                // the initialiser wrote into.
1385                for name in &loop_bindings {
1386                    let pos = self.cur().cur_pos;
1387                    self.state().insns.push(Insn::CloseCaptured {
1388                        name: name.clone(),
1389                        block: for_key,
1390                    });
1391                    self.state().insn_pos.push(pos);
1392                }
1393                let top = self.new_label();
1394                let cont = self.new_label();
1395                let end = self.new_label();
1396                self.place_label(top);
1397                if let Some(test) = test {
1398                    self.expr(test)?;
1399                    self.emit_jump(Opcode::IfFalse, end, &[]);
1400                }
1401                // `continue` runs the update expression first, so it lands on
1402                // `cont`, which sits just before the update.
1403                self.loop_body(body, labels, cont, end)?;
1404                self.place_label(cont);
1405                // Each iteration ends with a fresh cell, so the closures the body just
1406                // created keep the cell they captured and the update writes to a new
1407                // one. Without this every closure in the loop shares one binding.
1408                let binding_block = for_key;
1409                for name in &loop_bindings {
1410                    let pos = self.cur().cur_pos;
1411                    self.state().insns.push(Insn::CloseCaptured {
1412                        name: name.clone(),
1413                        block: binding_block,
1414                    });
1415                    self.state().insn_pos.push(pos);
1416                }
1417                if let Some(update) = update {
1418                    self.state().discard_value = true;
1419                    let result = self.expr(update);
1420                    self.state().discard_value = false;
1421                    result?;
1422                    if !std::mem::take(&mut self.state().no_value) {
1423                        self.emit(Opcode::Drop, &[]);
1424                    }
1425                }
1426                self.emit_jump(Opcode::Goto, top, &[]);
1427                self.place_label(end);
1428                self.emit_scope_leave(for_key);
1429                self.state().current_block = for_parent;
1430            }
1431            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1432            StmtKind::Throw(expr) => {
1433                self.expr(expr)?;
1434                self.emit(Opcode::Throw, &[]);
1435            }
1436            StmtKind::Break(_) | StmtKind::Continue(_) => {
1437                // Labels and loops are wired up in a later milestone; a bare
1438                // break/continue jumps to the innermost enclosing target, which
1439                // the loop helpers register.
1440                self.control_transfer(stmt)?;
1441            }
1442            StmtKind::Labeled { label, body } => {
1443                self.labeled(label, body, stmt)?;
1444            }
1445            StmtKind::Switch {
1446                discriminant,
1447                cases,
1448            } => {
1449                self.switch(discriminant, cases, stmt)?;
1450            }
1451            StmtKind::Try {
1452                block,
1453                handler,
1454                finalizer,
1455            } => {
1456                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1457            }
1458            StmtKind::ForIn { left, right, body } => {
1459                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1460            }
1461            StmtKind::ForOf {
1462                left,
1463                right,
1464                body,
1465                is_await,
1466            } => {
1467                let kind = if *is_await {
1468                    ForLoopKind::AwaitOf
1469                } else {
1470                    ForLoopKind::Of
1471                };
1472                self.for_in_of(stmt, left, right, body, kind, labels)?;
1473            }
1474            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1475            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1476            // `import` emits nothing: hoisting already bound its names, and the host
1477            // fills their cells before the body runs.
1478            StmtKind::Import(_) => {}
1479            StmtKind::Export(decl) => self.export_stmt(decl)?,
1480        }
1481        Ok(())
1482    }
1483
1484    /// Compile `return`, running every enclosing finalizer on the way out.
1485    ///
1486    /// `nip_catch` is what makes this possible: it discards everything on the stack
1487    /// down to and including the `catch` offset while keeping the return value on
1488    /// top, so the frame the finalizer sees has the same shape as on the normal
1489    /// path.
1490    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1491        let mut has_value = value.is_some();
1492        if let Some(expr) = value {
1493            // `return f(x)` is a tail call *only* when nothing has to happen to the
1494            // value afterwards. A `finally` or an open iterator in scope forces the
1495            // normal path, because the cleanup has to run after the call returns —
1496            // which is exactly what a tail call refuses to do.
1497            let plain = self
1498                .cur()
1499                .jump_targets
1500                .iter()
1501                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1502            if plain && self.expr_if_tail_call(expr)? {
1503                return Ok(());
1504            }
1505            self.expr(expr)?;
1506        }
1507        has_value = self.emit_unwind_for_return(has_value);
1508        // A generator or async function does not return to its caller: it either
1509        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1510        // `return_async` is the "finished" half, and it reads the value off the stack
1511        // rather than carrying it, which is what the resume machinery expects.
1512        if self.cur().is_suspending() {
1513            if !has_value {
1514                self.emit(Opcode::Undefined, &[]);
1515            }
1516            self.emit(Opcode::ReturnAsync, &[]);
1517            return Ok(());
1518        }
1519        if has_value {
1520            self.emit(Opcode::Return, &[]);
1521        } else {
1522            self.emit(Opcode::ReturnUndef, &[]);
1523        }
1524        Ok(())
1525    }
1526
1527    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1528    /// return, and report whether a value is now on the stack for it to carry.
1529    ///
1530    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1531    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1532    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1533    /// running `finally` blocks the body was sitting inside.
1534    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1535        let targets = self.cur().jump_targets.clone();
1536        for target in targets.iter().rev() {
1537            if target.finally_label.is_none() && !target.has_iterator {
1538                continue;
1539            }
1540            if !has_value {
1541                // The cleanup expects a value to pass through; with nothing to
1542                // return, `undefined` stands in.
1543                self.emit(Opcode::Undefined, &[]);
1544                has_value = true;
1545            }
1546            self.emit(Opcode::NipCatch, &[]);
1547            if target.has_iterator {
1548                // Rewind to the loop's own slots, then rotate the return value out
1549                // of the way and hand `iterator_close` a dummy catch offset: the
1550                // loop is being abandoned, so there is nothing left to catch.
1551                self.emit(Opcode::Rot3r, &[]);
1552                self.emit(Opcode::Undefined, &[]);
1553                self.emit(Opcode::IteratorClose, &[]);
1554            } else if let Some(finally) = target.finally_label {
1555                self.emit_jump(Opcode::Gosub, finally, &[]);
1556            }
1557        }
1558        has_value
1559    }
1560
1561    /// Compile a statement list, stopping at the first statement that cannot
1562    /// fall through.
1563    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1564        for (index, stmt) in body.iter().enumerate() {
1565            // A `using` declaration is not just a binding: everything after it, to the end
1566            // of the list, runs inside its disposal region. Compiling the rest of the list
1567            // recursively is what gives nested regions their innermost-first order.
1568            if Self::using_declaration(stmt).is_some() {
1569                return self.using_region(stmt, &body[index + 1..]);
1570            }
1571            self.stmt(stmt)?;
1572            if Self::terminates(stmt) {
1573                break;
1574            }
1575        }
1576        Ok(())
1577    }
1578
1579    /// The declaration a `using` statement carries, if it is one.
1580    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1581        match &stmt.kind {
1582            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1583            _ => None,
1584        }
1585    }
1586
1587    /// Compile `decl` and then the rest of its block, disposing when the block ends.
1588    ///
1589    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1590    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1591    /// exception — and this engine already funnels all of those through `catch` plus
1592    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1593    /// `return` and `break` dispose without knowing anything about `using`.
1594    ///
1595    /// ```text
1596    ///   <declaration>              value -> x, method -> x+1
1597    ///   catch CATCH                <- an exception in the rest lands here
1598    /// REST:
1599    ///   <the rest of the block>
1600    ///   drop                       <- the catch offset, on the fall-through path
1601    ///   undefined; gosub DISPOSE; drop
1602    ///   goto END
1603    /// CATCH:
1604    ///   using_dispose x            <- merges the failure into the pending exception
1605    ///   throw
1606    /// DISPOSE:
1607    ///   using_dispose_init
1608    ///   using_dispose x
1609    ///   using_dispose_end          <- rethrows if a dispose failed
1610    ///   ret
1611    /// END:
1612    /// ```
1613    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1614        let Some(decl) = Self::using_declaration(stmt) else {
1615            unreachable!("using_region is only called for a using declaration");
1616        };
1617        // `using` binds exactly one name and has no pattern form, which the parser
1618        // enforces; the region still has to know *which* slot to dispose.
1619        let name = decl
1620            .declarators
1621            .first()
1622            .and_then(|declarator| match &declarator.target.kind {
1623                PatternKind::Ident(ident) => Some(ident.name.clone()),
1624                _ => None,
1625            });
1626        self.stmt(stmt)?;
1627        let Some(name) = name else {
1628            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
1629            // must not make the compiler panic.
1630            return self.stmts(rest);
1631        };
1632        let Some(value_slot) = self.using_value_slot(&name) else {
1633            // Declared globally, which the parser rules out for a script; a module's
1634            // top level is a scope, and there the disposal stays a known gap.
1635            return self.stmts(rest);
1636        };
1637        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
1638        // exit path already disposed.
1639        let live = !rest.last().is_some_and(Self::terminates);
1640        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
1641    }
1642
1643    /// The slot a `using` binding's value lives in.
1644    fn using_value_slot(&self, name: &str) -> Option<u32> {
1645        self.cur()
1646            .vars
1647            .iter()
1648            .position(|var| var.name == name && var.kind == VarKind::Using)
1649            .map(|index| index as u32)
1650    }
1651
1652    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
1653    ///
1654    /// Shared between a `using` statement — which owns the rest of its block — and a
1655    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
1656    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
1657    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
1658    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
1659    /// target with a `finally_label` is what makes `return` and `break` dispose without
1660    /// knowing anything about `using`.
1661    ///
1662    /// ```text
1663    ///   catch CATCH                <- an exception inside lands here
1664    ///   <inside>
1665    ///   drop                       <- the catch offset, on the fall-through path
1666    ///   undefined; gosub DISPOSE; drop
1667    ///   goto END
1668    /// CATCH:
1669    ///   using_dispose slot         <- merges the failure into the pending exception
1670    ///   throw
1671    /// DISPOSE:
1672    ///   using_dispose_init
1673    ///   using_dispose slot
1674    ///   using_dispose_end          <- rethrows if a dispose failed
1675    ///   ret
1676    /// END:
1677    /// ```
1678    fn using_region_around(
1679        &mut self,
1680        value_slot: u32,
1681        live: bool,
1682        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
1683    ) -> Result<(), SyntaxError> {
1684        let catch_label = self.new_label();
1685        let end_label = self.new_label();
1686        let dispose_label = self.new_label();
1687
1688        self.emit_jump(Opcode::Catch, catch_label, &[]);
1689        self.push_jump_target(JumpTarget {
1690            names: Vec::new(),
1691            break_label: None,
1692            continue_label: None,
1693            // The catch offset is the one thing on the stack that leaving has to remove.
1694            drop_count: 1,
1695            finally_label: Some(dispose_label),
1696            is_regular_stmt: false,
1697            has_iterator: false,
1698        });
1699        inside(self)?;
1700        self.pop_jump_target();
1701
1702        if live {
1703            self.emit(Opcode::Drop, &[]);
1704            self.emit(Opcode::Undefined, &[]);
1705            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
1706            self.emit(Opcode::Drop, &[]);
1707            self.emit_jump(Opcode::Goto, end_label, &[]);
1708        }
1709
1710        // An exception unwinds to here with the thrown value on the stack, which is exactly
1711        // the shape `using_dispose` expects as its error state.
1712        self.place_label(catch_label);
1713        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
1714        self.emit(Opcode::Throw, &[]);
1715
1716        self.place_label(dispose_label);
1717        // Inside the subroutine the return value and the `gosub` return address are both
1718        // live, and neither an outer finalizer nor another region may run before this one
1719        // has finished.
1720        self.push_jump_target(JumpTarget {
1721            names: Vec::new(),
1722            break_label: None,
1723            continue_label: None,
1724            drop_count: 2,
1725            finally_label: None,
1726            is_regular_stmt: false,
1727            has_iterator: false,
1728        });
1729        self.emit(Opcode::UsingDisposeInit, &[]);
1730        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
1731        self.emit(Opcode::UsingDisposeEnd, &[]);
1732        self.pop_jump_target();
1733        self.emit(Opcode::Ret, &[]);
1734        self.place_label(end_label);
1735        Ok(())
1736    }
1737
1738    /// Declare every name a statement list introduces, before compiling any of
1739    /// it, so a reference that appears textually before a declaration still
1740    /// resolves.
1741    ///
1742    /// Declarations are walked in source order because that is the order the
1743    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
1744    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
1745    /// declarations hoist out to the function scope; lexical names belong to the
1746    /// block they were written in, which `block` records.
1747    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
1748        let saved = self.cur().current_block;
1749        self.state().current_block = block;
1750        let result = self.hoist_list(body);
1751        // Only now is every binding of this scope known, so the deferred function
1752        // bodies can be compiled against the finished list. Compiled at its own
1753        // declaration instead, a body that names a `var` written further down would
1754        // have resolved that name as a global.
1755        if result.is_ok() {
1756            let deferred = std::mem::take(&mut self.state().deferred_funcs);
1757            let mut outcome = Ok(());
1758            for (owner, func) in deferred {
1759                let previous = self.cur().current_block;
1760                self.state().current_block = owner;
1761                outcome = self.func_decl(&func);
1762                self.state().current_block = previous;
1763                if outcome.is_err() {
1764                    break;
1765                }
1766            }
1767            self.state().current_block = saved;
1768            return outcome;
1769        }
1770        // `current_block` is restored by the caller for a block statement, since
1771        // it needs it set while compiling; only clean up on the hoist path.
1772        self.state().current_block = saved;
1773        result
1774    }
1775
1776    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1777        for stmt in body {
1778            self.hoist_stmt(stmt)?;
1779        }
1780        Ok(())
1781    }
1782
1783    /// Whether a statement always transfers control away, making everything after
1784    /// it in the same list unreachable.
1785    ///
1786    /// The reference drops such statements in `skip_dead_code`, so `return 1;
1787    /// let x = 2;` compiles to the same bytecode as `return 1;`.
1788    fn terminates(stmt: &Stmt) -> bool {
1789        matches!(
1790            stmt.kind,
1791            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
1792        )
1793    }
1794
1795    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1796        match &stmt.kind {
1797            StmtKind::VarDecl(decl) => {
1798                for declarator in &decl.declarators {
1799                    let mut names = Vec::new();
1800                    declarator.target.bound_names(&mut names);
1801                    for name in names {
1802                        let text = name.name.clone();
1803                        if decl.kind == VarDeclKind::Var {
1804                            let def = VarDef::var(text.clone());
1805                            self.declare_var(&text, def);
1806                        } else if decl.kind.is_using() {
1807                            // Two adjacent slots: the resource, then the dispose method
1808                            // snapshotted at declaration. `using_dispose` reads them as a
1809                            // pair `(slot, slot + 1)`, so nothing may be declared between
1810                            // them — which is why both are declared here, in one step,
1811                            // rather than the method being added at emission time.
1812                            self.declare_using(&text);
1813                        } else {
1814                            let def = if decl.kind == VarDeclKind::Const {
1815                                VarDef::constant(text.clone())
1816                            } else {
1817                                VarDef::lexical(text.clone())
1818                            };
1819                            self.declare(&text, def);
1820                        }
1821                    }
1822                }
1823            }
1824            StmtKind::FuncDecl(func) => {
1825                if let Some(name) = &func.name {
1826                    // A function declaration is a `var` binding that happens to
1827                    // hold a function, not a lexical one.
1828                    let def = VarDef::var(name.name.clone());
1829                    self.declare_var(&name.name.clone(), def);
1830                }
1831                // The function object is created when the scope is entered, so it
1832                // exists before the declaration is reached. Its body is compiled
1833                // *after* this scope's hoisting finishes, so a name it uses resolves
1834                // even when the `var` that declares it comes later in the source.
1835                let owner = self.cur().current_block;
1836                self.state().deferred_funcs.push((owner, func.clone()));
1837            }
1838            StmtKind::ClassDecl(class) => {
1839                if let Some(name) = &class.name {
1840                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
1841                }
1842            }
1843            // A module's imports are bound before any of its code runs, and its exports
1844            // declare the very bindings they export — so both hoist the declarations
1845            // their `StmtKind` arm will later emit code for.
1846            StmtKind::Import(decl) => self.hoist_import(decl)?,
1847            StmtKind::Export(decl) => self.hoist_export(decl)?,
1848            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
1849            StmtKind::If { cons, alt, .. } => {
1850                self.hoist_stmt(cons)?;
1851                if let Some(alt) = alt {
1852                    self.hoist_stmt(alt)?;
1853                }
1854            }
1855            StmtKind::While { body, .. }
1856            | StmtKind::DoWhile { body, .. }
1857            | StmtKind::Labeled { body, .. }
1858            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
1859            StmtKind::For { init, body, .. } => {
1860                // A `for` head gets its own scope even when it declares nothing,
1861                // because `let` in the head is scoped to the loop.
1862                let key = stmt.span.start.offset as u64;
1863                let parent = self.cur().current_block;
1864                self.push_block(key, parent);
1865                if let Some(init) = init
1866                    && let ForInit::VarDecl(decl) = init
1867                {
1868                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
1869                }
1870                self.hoist_stmt(body)?;
1871                self.state().current_block = parent;
1872            }
1873            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
1874                let key = stmt.span.start.offset as u64;
1875                let parent = self.cur().current_block;
1876                self.push_block(key, parent);
1877                if let ForHead::VarDecl(decl) = left {
1878                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
1879                }
1880                self.hoist_stmt(body)?;
1881                self.state().current_block = parent;
1882            }
1883            StmtKind::Try {
1884                block,
1885                handler,
1886                finalizer,
1887            } => {
1888                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
1889                let try_parent = self.cur().current_block;
1890                if let Some(handler) = handler {
1891                    // The catch parameter belongs to the function scope, not to a
1892                    // block: it is a `catch` binding rather than a `let`, so it is
1893                    // never in the temporal dead zone and `emit_scope_enter` must
1894                    // not mark it uninitialised. It still has to be declared before
1895                    // the handler body is hoisted, so it takes the slot the
1896                    // reference gives it (bindings are numbered in source order).
1897                    if let Some(Pattern {
1898                        kind: PatternKind::Ident(name),
1899                        ..
1900                    }) = &handler.param
1901                    {
1902                        // The parameter gets its own scope, so entering the handler
1903                        // does not have to re-declare it. It is not lexical, so it
1904                        // is never marked uninitialised.
1905                        let key = Self::try_block_key(stmt, TryPart::Param);
1906                        let parent = self.cur().current_block;
1907                        self.push_block(key, parent);
1908                        let def = VarDef {
1909                            name: name.name.clone(),
1910                            is_const: false,
1911                            is_lexical: false,
1912                            kind: crate::bytecode::VarKind::Catch,
1913                            is_captured: false,
1914                            scope_level: 0,
1915                            scope_next: None,
1916                        };
1917                        self.declare_local(&name.name.clone(), def);
1918                        // The handler body nests inside the parameter's scope, so the
1919                        // body's bindings chain on to the parameter (the reference
1920                        // prints `let y [next:1]`, pointing at `e`).
1921                        self.state().current_block = key;
1922                    }
1923                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
1924                    // Back to the block the `try` itself lives in, so the finalizer
1925                    // is a sibling of the handler rather than nested in it.
1926                    self.state().current_block = try_parent;
1927                }
1928                if let Some(finalizer) = finalizer {
1929                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
1930                }
1931            }
1932            StmtKind::Switch { cases, .. } => {
1933                let key = stmt.span.start.offset as u64;
1934                let parent = self.cur().current_block;
1935                self.push_block(key, parent);
1936                for case in cases {
1937                    self.hoist_list(&case.body)?;
1938                }
1939                self.state().current_block = parent;
1940            }
1941            _ => {}
1942        }
1943        Ok(())
1944    }
1945
1946    /// Hoist a nested statement list, which is its own lexical scope.
1947    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
1948        let parent = self.cur().current_block;
1949        self.push_block(key, parent);
1950        self.hoist_list(body)?;
1951        self.state().current_block = parent;
1952        Ok(())
1953    }
1954
1955    /// A block key for one part of a `try` statement.
1956    ///
1957    /// The three parts are three separate scopes, so they cannot share the key a
1958    /// statement's own offset would give them: the try block, the handler body and
1959    /// the finalizer would then look like one scope, and their `let` bindings would
1960    /// be marked uninitialised only on entering the first of them.
1961    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
1962        (stmt.span.start.offset as u64) * 4 + part as u64
1963    }
1964
1965    /// Declare a `var`: it lives in the function's own scope, not the block's.
1966    fn declare_var(&mut self, name: &str, def: VarDef) {
1967        if self.cur().is_module {
1968            self.declare_module(name, &def);
1969            return;
1970        }
1971        if self.cur().declares_globally(&def) {
1972            self.declare_global(name, &def);
1973            return;
1974        }
1975        let state = self.state();
1976        // A binding of the *parameter* scope does not count: the body's `var` of the
1977        // same name is a different binding and needs a slot of its own.
1978        if state.vars.iter().enumerate().any(|(index, v)| {
1979            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
1980        }) {
1981            return;
1982        }
1983        // A `var` belongs to the function scope, never to the enclosing block.
1984        state.var_block.push(FUNCTION_SCOPE);
1985        state.vars.push(def);
1986    }
1987
1988    /// Declare `name` as a binding of the parameter scope, returning its slot.
1989    fn declare_param_var(&mut self, name: &str) -> u32 {
1990        declare_param_var_at(self.state(), name)
1991    }
1992
1993    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
1994    /// one.
1995    ///
1996    /// With parameter expressions the reference creates two: an unmapped one in the
1997    /// argument scope, for the defaults and anything they close over, and the body's own.
1998    /// They are separate bindings, which is what makes
1999    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2000    /// report 1 from `p` and 2 from the body.
2001    fn provide_param_arguments(&mut self) {
2002        if !self.cur().has_parameter_expressions {
2003            return;
2004        }
2005        let mentioned = self.cur().needs_param_arguments
2006            || self
2007                .cur()
2008                .insns
2009                .iter()
2010                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2011        if !mentioned {
2012            return;
2013        }
2014        let slot = self.declare_param_var("arguments");
2015        let magic = if self.cur().strict { 0 } else { 1 };
2016        self.prepend_initialiser_to(
2017            slot,
2018            Insn::Fixed {
2019                op: Opcode::SpecialObject,
2020                operands: vec![Op::Int(magic)],
2021            },
2022        );
2023    }
2024
2025    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2026    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2027        let current = self.stack.len() - 1;
2028        let init = [
2029            producer,
2030            Insn::Fixed {
2031                op: Opcode::PutLoc,
2032                operands: vec![Op::Slot(Slot::Loc(slot))],
2033            },
2034        ];
2035        let inserted = init.len();
2036        for (index, instruction) in init.into_iter().enumerate() {
2037            self.stack[current].insns.insert(index, instruction);
2038        }
2039        for placed in self.stack[current].labels.iter_mut().flatten() {
2040            *placed += inserted;
2041        }
2042        self.state().label_since_insn = false;
2043    }
2044
2045    /// Give the function an `arguments` binding if its body mentions one.
2046    ///
2047    /// The check runs on the *instruction* stream rather than the AST: by this point
2048    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2049    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2050    /// would renumber every later local slot and stop the bytecode matching the
2051    /// reference, which only adds the binding when the body uses it.
2052    ///
2053    /// `arguments` is a local, initialised at the top of the body by
2054    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2055    fn provide_arguments(&mut self) {
2056        let current = self.stack.len() - 1;
2057        if self.stack[current].is_script || self.stack[current].is_module {
2058            // A module has no `arguments` binding; referring to it is a ReferenceError,
2059            // which is exactly what an unbound name produces.
2060            return;
2061        }
2062        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2063        // function, which is why `() => arguments` sees the caller's arguments.
2064        if self.stack[current].is_arrow {
2065            if self.mentions("arguments") {
2066                self.ensure_enclosing_arguments();
2067            }
2068            return;
2069        }
2070        // Only a *body* mention needs the body's binding: the parameter list has one of
2071        // its own (see [`Compiler::provide_param_arguments`]).
2072        let mentioned = self.cur().insns.iter().any(|insn| {
2073            matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params)
2074        });
2075        if !mentioned && !self.cur().needs_arguments_local {
2076            return;
2077        }
2078        // The request may have come only from a parameter-list arrow, in which case the
2079        // parameter scope's binding already answers for it and the body needs none.
2080        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2081            return;
2082        }
2083        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping
2084        // itself is not implemented, so the two behave alike for now.
2085        let magic = if self.stack[current].strict { 0 } else { 1 };
2086        self.prepend_binding("arguments", magic);
2087    }
2088
2089    /// Whether a *body* instruction refers to `arguments`.
2090    fn body_mentions_arguments(&self) -> bool {
2091        self.cur()
2092            .insns
2093            .iter()
2094            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2095    }
2096
2097    /// Whether the function body's instruction stream refers to `name`.
2098    fn mentions(&self, name: &str) -> bool {
2099        let current = self.stack.len() - 1;
2100        // A binding of the parameter scope does not answer for the body: the body's own
2101        // `arguments` (or self-name) still has to be provided for it.
2102        if self.stack[current]
2103            .vars
2104            .iter()
2105            .enumerate()
2106            .any(|(index, v)| {
2107                v.name == name
2108                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2109            })
2110        {
2111            return false;
2112        }
2113        self.stack[current]
2114            .insns
2115            .iter()
2116            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2117    }
2118
2119    /// Bind the name a named function expression uses to refer to itself.
2120    ///
2121    /// The value is `special_object 2`, the function currently running, so the binding
2122    /// is the closure itself and not a copy. It is a local of this function, which is
2123    /// what keeps `g` out of the enclosing scope.
2124    /// Give the function a local `this`, for an arrow inside it to capture.
2125    fn provide_this_local(&mut self) {
2126        let current = self.stack.len() - 1;
2127        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2128            return;
2129        }
2130        if !self.stack[current]
2131            .vars
2132            .iter()
2133            .any(|var| var.name == "this")
2134        {
2135            self.declare_hidden_local("this", VarKind::Normal);
2136        }
2137        self.prepend_initialiser(
2138            "this",
2139            Insn::Fixed {
2140                op: Opcode::PushThis,
2141                operands: vec![],
2142            },
2143        );
2144    }
2145
2146    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2147    /// to read through `super`.
2148    fn provide_home_object_local(&mut self) {
2149        let current = self.stack.len() - 1;
2150        if !self.stack[current].needs_home_object_local {
2151            return;
2152        }
2153        if !self.stack[current]
2154            .vars
2155            .iter()
2156            .any(|var| var.name == HOME_OBJECT)
2157        {
2158            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2159        }
2160        self.prepend_initialiser(
2161            HOME_OBJECT,
2162            Insn::Fixed {
2163                op: Opcode::SpecialObject,
2164                operands: vec![Op::Int(4)],
2165            },
2166        );
2167    }
2168
2169    fn provide_self_name(&mut self) {
2170        let current = self.stack.len() - 1;
2171        let Some(name) = self.stack[current].self_name.clone() else {
2172            return;
2173        };
2174        if self.stack[current].self_name_initialized {
2175            return;
2176        }
2177        // Either the body refers to the name, or a nested function already forced the
2178        // binding into existence while being resolved. A direct `eval` can name it
2179        // without mentioning it, so its presence is a third reason: in strict mode
2180        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2181        // that only happens if the binding exists.
2182        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2183        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2184            return;
2185        }
2186        self.stack[current].self_name_initialized = true;
2187        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2188    }
2189
2190    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2191    ///
2192    /// Prepending shifts every label that has been placed, so they are all moved by
2193    /// the number of instructions inserted.
2194    fn prepend_binding(&mut self, name: &str, magic: i32) {
2195        self.prepend_binding_with(name, magic, VarKind::Normal);
2196    }
2197
2198    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2199    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2200        let current = self.stack.len() - 1;
2201        // A function-expression's own name is immutable in strict mode, which is what
2202        // makes `f = 1` inside a strict body throw instead of being dropped.
2203        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2204        self.declare_var(
2205            name,
2206            VarDef {
2207                kind,
2208                is_const,
2209                ..VarDef::var(name)
2210            },
2211        );
2212        let init = [
2213            Insn::Fixed {
2214                op: Opcode::SpecialObject,
2215                operands: vec![Op::Int(magic)],
2216            },
2217            Insn::Var {
2218                // An initialisation, not an assignment: sloppy mode drops stores to a
2219                // function-expression's own name, and the prologue is what puts the
2220                // value there in the first place.
2221                action: if kind == VarKind::FunctionName {
2222                    VarAction::PutInit
2223                } else {
2224                    VarAction::Put
2225                },
2226                name: name.to_string(),
2227                block: 0,
2228                in_params: false,
2229            },
2230        ];
2231        let inserted = init.len();
2232        for (index, instruction) in init.into_iter().enumerate() {
2233            self.stack[current].insns.insert(index, instruction);
2234        }
2235        for placed in self.stack[current].labels.iter_mut().flatten() {
2236            *placed += inserted;
2237        }
2238        // A store sits at the insertion point now, so the `put`/`get` fold must not
2239        // reach across it.
2240        self.stack[current].label_since_insn = true;
2241    }
2242
2243    /// Record a top-level script declaration as a global.
2244    ///
2245    /// A script's top-level `var`/`let`/`function` create properties of the
2246    /// global object, not slots in the script's frame, so they show up as closure
2247    /// variables instead.
2248    fn declare_global(&mut self, name: &str, def: &VarDef) {
2249        let state = self.state();
2250        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2251            // The name was already referenced, from a function compiled before this
2252            // declaration was reached — `function a(){ b() } function b(){}` resolves
2253            // `b` while `b` is still unknown, and that guess has to be corrected here.
2254            // Leaving it as a plain global meant the declaration was never registered,
2255            // so the binding did not exist at run time and `a()` threw
2256            // `b is not defined`.
2257            if matches!(existing.closure_type, ClosureType::Global) {
2258                existing.closure_type = ClosureType::GlobalDecl;
2259                existing.is_const = def.is_const;
2260                existing.is_lexical = def.is_lexical;
2261            }
2262            return;
2263        }
2264        state.closure_vars.push(ClosureVar {
2265            name: name.to_string(),
2266            is_const: def.is_const,
2267            is_lexical: def.is_lexical,
2268            closure_type: ClosureType::GlobalDecl,
2269            var_idx: 0,
2270        });
2271    }
2272
2273    /// Record a module-level declaration as a module variable.
2274    ///
2275    /// The binding is a closure variable of the module body, so reads and writes are
2276    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2277    /// *who fills the cell*: the module record does, before the body runs, and an import
2278    /// points its cell at the exporting module's, which is what makes bindings live and
2279    /// cycles work.
2280    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2281        let state = self.state();
2282        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2283            // The name may have been referenced before this declaration was hoisted,
2284            // which resolved it as a plain global. Correct that here, the way
2285            // `declare_global` does.
2286            if matches!(existing.closure_type, ClosureType::Global) {
2287                existing.closure_type = ClosureType::ModuleDecl;
2288                existing.is_const = def.is_const;
2289                existing.is_lexical = def.is_lexical;
2290            }
2291            return 0;
2292        }
2293        state.closure_vars.push(ClosureVar {
2294            name: name.to_string(),
2295            is_const: def.is_const,
2296            is_lexical: def.is_lexical,
2297            closure_type: ClosureType::ModuleDecl,
2298            var_idx: 0,
2299        });
2300        0
2301    }
2302
2303    /// Declare a module variable and answer its closure-variable index.
2304    ///
2305    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2306    /// module variable is not one. The import table needs the real index instead, because
2307    /// that is the position the host writes the cell into.
2308    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2309        self.declare_module(name, def);
2310        self.cur()
2311            .closure_vars
2312            .iter()
2313            .position(|c| c.name == name)
2314            .map(|index| index as u32)
2315            .unwrap_or(0)
2316    }
2317
2318    /// Declare one imported binding as a module variable.
2319    ///
2320    /// Returns the closure-variable index, which is what the import table records: the
2321    /// host writes the exporter's cell into that slot before the body runs.
2322    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2323        let state = self.state();
2324        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2325            // Keep the slot, fix the kind: the name may already have been referenced.
2326            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2327            state.closure_vars[index].is_const = is_const;
2328            return index as u32;
2329        }
2330        state.closure_vars.push(ClosureVar {
2331            name: name.to_string(),
2332            // An imported binding cannot be assigned: `x = 1` on an import is a
2333            // `TypeError` at run time, which the const flag is what produces.
2334            is_const: true,
2335            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2336            // the cell an import is in its dead zone, and reading it there must say so
2337            // rather than answer `undefined`.
2338            is_lexical: true,
2339            closure_type: ClosureType::ModuleImport,
2340            var_idx: 0,
2341        });
2342        state.closure_vars.len() as u32 - 1
2343    }
2344
2345    /// Emit the code an `export` needs.
2346    ///
2347    /// Only `export default <expr>` has any: everything else is a table entry whose
2348    /// binding is declared elsewhere. The expression is stored into the hidden
2349    /// `*default*` variable rather than returned, because the module body has no value
2350    /// to speak of.
2351    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2352        match &decl.kind {
2353            ExportKind::Declaration(stmt) => self.stmt(stmt),
2354            ExportKind::Default(expr) => {
2355                // A named default function/class is already a module binding; the export
2356                // points at it and there is nothing to evaluate.
2357                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2358                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2359                {
2360                    return Ok(());
2361                }
2362                self.expr(expr)?;
2363                let index = self.declare_export_default();
2364                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2365                Ok(())
2366            }
2367            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2368        }
2369    }
2370
2371    /// A module name as the string it denotes.
2372    fn module_name_text(name: &ModuleName) -> &str {
2373        match name {
2374            ModuleName::Ident(ident) => &ident.name,
2375            ModuleName::Str(text) => text,
2376        }
2377    }
2378
2379    /// Bind `import`'s local names and record where each one comes from.
2380    ///
2381    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2382    /// binding's cell will be filled before the body runs. The cell lands in the module's
2383    /// environment at a fixed index, and the host fills it from the exporter's cell —
2384    /// which is why a cyclic import can bind before the other module has evaluated.
2385    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2386        let request = self.module_request(&decl.source, &decl.attributes);
2387        for specifier in &decl.specifiers {
2388            let (local, name, is_star) = match specifier {
2389                ImportSpecifier::Default(ident) => {
2390                    (ident.name.clone(), "default".to_string(), false)
2391                }
2392                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2393                ImportSpecifier::Named { imported, local } => (
2394                    local.name.clone(),
2395                    Self::module_name_text(imported).to_string(),
2396                    false,
2397                ),
2398            };
2399            // `import * as ns` is *not* a live binding of another module's variable —
2400            // it is a value of its own, which is why the reference declares it like a
2401            // module variable and the host stores the namespace object in that cell.
2402            let var_idx = if is_star {
2403                // `const`: a namespace object is a value, and the binding is immutable.
2404                self.declare_module_var(&local, &VarDef::constant(local.clone()))
2405            } else {
2406                self.declare_import(&local, true)
2407            };
2408            self.module_meta().imports.push(ImportEntry {
2409                module: request,
2410                name,
2411                var_idx,
2412                is_star,
2413            });
2414        }
2415        Ok(())
2416    }
2417
2418    /// Record what an `export` offers, declaring the binding it exports.
2419    ///
2420    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2421    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2422        match &decl.kind {
2423            ExportKind::Declaration(stmt) => {
2424                // The inner declaration keeps its own hoisting, then every name it binds
2425                // becomes an export of the same name.
2426                self.hoist_stmt(stmt)?;
2427                let mut names = Vec::new();
2428                Self::declared_names(stmt, &mut names);
2429                for name in names {
2430                    let var_idx = self.module_binding_index(&name);
2431                    self.exports_local(&name, var_idx);
2432                }
2433            }
2434            ExportKind::Default(expr) => {
2435                // The reference puts a default export in a hidden `*default*` variable,
2436                // so `export default function f(){}` can export a *value* while `f` stays
2437                // a binding of the module.
2438                if let ExprKind::Function(func) = &expr.kind
2439                    && let Some(name) = &func.name
2440                {
2441                    let text = name.name.clone();
2442                    self.hoist_stmt(&Stmt {
2443                        kind: StmtKind::FuncDecl(func.clone()),
2444                        span: expr.span,
2445                    })?;
2446                    let var_idx = self.module_binding_index(&text);
2447                    self.module_meta().exports.push(ExportEntry::Local {
2448                        export_name: "default".to_string(),
2449                        var_idx,
2450                    });
2451                    return Ok(());
2452                }
2453                if let ExprKind::Class(class) = &expr.kind
2454                    && let Some(name) = &class.name
2455                {
2456                    let text = name.name.clone();
2457                    self.hoist_stmt(&Stmt {
2458                        kind: StmtKind::ClassDecl(class.clone()),
2459                        span: expr.span,
2460                    })?;
2461                    let var_idx = self.module_binding_index(&text);
2462                    let _ = var_idx;
2463                }
2464                let var_idx = self.declare_export_default();
2465                self.module_meta().exports.push(ExportEntry::Local {
2466                    export_name: "default".to_string(),
2467                    var_idx,
2468                });
2469            }
2470            ExportKind::Named {
2471                specifiers,
2472                source,
2473                attributes,
2474            } => match source {
2475                Some(source) => {
2476                    let request = self.module_request(source, attributes);
2477                    for specifier in specifiers {
2478                        self.module_meta().exports.push(ExportEntry::Indirect {
2479                            export_name: Self::module_name_text(&specifier.exported).to_string(),
2480                            module: request,
2481                            import_name: Self::module_name_text(&specifier.local).to_string(),
2482                        });
2483                    }
2484                }
2485                None => {
2486                    for specifier in specifiers {
2487                        let local = Self::module_name_text(&specifier.local).to_string();
2488                        let var_idx = self.module_binding_index(&local);
2489                        let export_name = Self::module_name_text(&specifier.exported).to_string();
2490                        self.module_meta().exports.push(ExportEntry::Local {
2491                            export_name,
2492                            var_idx,
2493                        });
2494                    }
2495                }
2496            },
2497            ExportKind::All {
2498                source,
2499                exported,
2500                attributes,
2501            } => {
2502                let request = self.module_request(source, attributes);
2503                match exported {
2504                    Some(name) => {
2505                        self.module_meta().exports.push(ExportEntry::StarAs {
2506                            export_name: Self::module_name_text(name).to_string(),
2507                            module: request,
2508                        });
2509                    }
2510                    None => {
2511                        self.module_meta()
2512                            .exports
2513                            .push(ExportEntry::Star { module: request });
2514                    }
2515                }
2516            }
2517        }
2518        Ok(())
2519    }
2520
2521    /// The names a declaration binds, which is what `export <decl>` exports.
2522    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
2523        match &stmt.kind {
2524            StmtKind::VarDecl(decl) => {
2525                for declarator in &decl.declarators {
2526                    let mut names = Vec::new();
2527                    declarator.target.bound_names(&mut names);
2528                    out.extend(names.into_iter().map(|name| name.name));
2529                }
2530            }
2531            StmtKind::FuncDecl(func) => {
2532                if let Some(name) = &func.name {
2533                    out.push(name.name.clone());
2534                }
2535            }
2536            StmtKind::ClassDecl(class) => {
2537                if let Some(name) = &class.name {
2538                    out.push(name.name.clone());
2539                }
2540            }
2541            _ => {}
2542        }
2543    }
2544
2545    /// The closure-variable index of a module binding, declaring it if the name was
2546    /// exported without being declared here.
2547    ///
2548    /// `export { x }` where `x` is not declared in the module is a link-time
2549    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
2550    fn module_binding_index(&mut self, name: &str) -> u32 {
2551        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
2552            return index as u32;
2553        }
2554        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
2555    }
2556
2557    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
2558        self.module_meta().exports.push(ExportEntry::Local {
2559            export_name: export_name.to_string(),
2560            var_idx,
2561        });
2562    }
2563
2564    /// The hidden `*default*` binding `export default <expr>` stores into.
2565    fn declare_export_default(&mut self) -> u32 {
2566        const DEFAULT: &str = "*default*";
2567        if let Some(index) = self
2568            .cur()
2569            .closure_vars
2570            .iter()
2571            .position(|c| c.name == DEFAULT)
2572        {
2573            return index as u32;
2574        }
2575        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
2576    }
2577
2578    /// The module tables, which only the top-level state has.
2579    fn module_meta(&mut self) -> &mut ModuleMeta {
2580        self.state()
2581            .module
2582            .as_mut()
2583            .expect("module tables are only touched while compiling a module")
2584    }
2585
2586    /// The index of `specifier`'s request, adding it if it is new.
2587    ///
2588    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
2589    /// JSON and once as text is two modules with two different contents, which is exactly
2590    /// what `hello_module.js` does.
2591    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
2592        let attributes: Vec<(String, String)> = attributes
2593            .iter()
2594            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
2595            .collect();
2596        let meta = self.module_meta();
2597        if let Some(index) = meta
2598            .requests
2599            .iter()
2600            .position(|request| request.specifier == specifier && request.attributes == attributes)
2601        {
2602            return index as u32;
2603        }
2604        meta.requests.push(ModuleRequest {
2605            specifier: specifier.to_string(),
2606            attributes,
2607        });
2608        meta.requests.len() as u32 - 1
2609    }
2610
2611    /// Compile a loop body with a `break`/`continue` target pushed for it.
2612    fn loop_body(
2613        &mut self,
2614        body: &Stmt,
2615        labels: &[String],
2616        continue_label: Label,
2617        break_label: Label,
2618    ) -> Result<(), SyntaxError> {
2619        self.push_jump_target(JumpTarget {
2620            names: labels.to_vec(),
2621            break_label: Some(break_label),
2622            continue_label: Some(continue_label),
2623            // A loop leaves nothing of its own on the value stack.
2624            drop_count: 0,
2625            finally_label: None,
2626            is_regular_stmt: false,
2627            has_iterator: false,
2628        });
2629        let result = self.stmt(body);
2630        self.pop_jump_target();
2631        result
2632    }
2633
2634    fn push_jump_target(&mut self, target: JumpTarget) {
2635        self.state().jump_targets.push(target);
2636    }
2637
2638    fn pop_jump_target(&mut self) {
2639        self.state().jump_targets.pop();
2640    }
2641
2642    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2643        let (label, is_break) = match &stmt.kind {
2644            StmtKind::Break(label) => (label.as_ref(), true),
2645            StmtKind::Continue(label) => (label.as_ref(), false),
2646            _ => unreachable!("control_transfer is only called for break and continue"),
2647        };
2648
2649        // Walk outward from the innermost construct. Everything considered before
2650        // the match is a construct control is leaving, and leaving it has a cost:
2651        // its stack slots go, and its finalizer runs.
2652        let targets = self.cur().jump_targets.clone();
2653        for target in targets.iter().rev() {
2654            let destination = match (label, is_break) {
2655                // An unlabelled `break` skips a labelled non-loop statement: `break`
2656                // may name one, but the bare form only means "leave the loop".
2657                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
2658                (None, false) => target.continue_label,
2659                (Some(name), true) => target
2660                    .break_label
2661                    .filter(|_| target.names.contains(&name.name)),
2662                (Some(name), false) => target
2663                    .continue_label
2664                    .filter(|_| target.names.contains(&name.name)),
2665            };
2666
2667            if let Some(destination) = destination {
2668                self.emit_jump(Opcode::Goto, destination, &[]);
2669                return Ok(());
2670            }
2671
2672            // Closing the iterator consumes the three slots the loop keeps on the
2673            // stack (iterator, next method, catch offset), so those are not dropped
2674            // again below.
2675            let mut remaining = target.drop_count;
2676            if target.has_iterator {
2677                self.emit(Opcode::IteratorClose, &[]);
2678                remaining = remaining.saturating_sub(3);
2679            }
2680            for _ in 0..remaining {
2681                self.emit(Opcode::Drop, &[]);
2682            }
2683            if let Some(finally) = target.finally_label {
2684                // The finalizer runs as a subroutine and is handed a dummy return
2685                // value, which is dropped afterwards to keep the stack the depth it
2686                // had before.
2687                self.emit(Opcode::Undefined, &[]);
2688                self.emit_jump(Opcode::Gosub, finally, &[]);
2689                self.emit(Opcode::Drop, &[]);
2690            }
2691        }
2692
2693        // The parser rejects a break/continue with no target, so reaching here
2694        // means the compiler's own bookkeeping is wrong.
2695        Err(SyntaxError::new(
2696            if is_break {
2697                "break has no enclosing loop or switch"
2698            } else {
2699                "continue has no enclosing loop"
2700            },
2701            stmt.span,
2702        ))
2703    }
2704
2705    /// Compile a labelled statement.
2706    ///
2707    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
2708    /// that loop's targets, so the chain is collected and handed to the loop. A
2709    /// label on a non-loop statement only provides a `break` target, because
2710    /// `continue` may not target it.
2711    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
2712        let mut names = vec![label.name.clone()];
2713        let mut inner = body;
2714        while let StmtKind::Labeled {
2715            label: next,
2716            body: deeper,
2717        } = &inner.kind
2718        {
2719            names.push(next.name.clone());
2720            inner = deeper;
2721        }
2722        if Self::is_loop(inner) {
2723            return self.stmt_labelled(inner, &names);
2724        }
2725        let end = self.new_label();
2726        self.push_jump_target(JumpTarget {
2727            names,
2728            break_label: Some(end),
2729            continue_label: None,
2730            drop_count: 0,
2731            finally_label: None,
2732            is_regular_stmt: true,
2733            has_iterator: false,
2734        });
2735        let result = self.stmt(inner);
2736        self.pop_jump_target();
2737        result?;
2738        self.place_label(end);
2739        let _ = stmt;
2740        Ok(())
2741    }
2742
2743    /// Whether a statement is a loop, i.e. a valid target for `continue`.
2744    fn is_loop(stmt: &Stmt) -> bool {
2745        matches!(
2746            stmt.kind,
2747            StmtKind::While { .. }
2748                | StmtKind::DoWhile { .. }
2749                | StmtKind::For { .. }
2750                | StmtKind::ForIn { .. }
2751                | StmtKind::ForOf { .. }
2752        )
2753    }
2754
2755    /// Compile `switch`.
2756    ///
2757    /// The discriminant is evaluated once and stays on the value stack while the
2758    /// clauses compare against copies of it, so it is dropped at the end — which is
2759    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
2760    /// clause's body jumps over the *next* clause's tests straight into its body.
2761    ///
2762    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
2763    /// the next run's tests. Only the last run's miss reaches the `default` body, or
2764    /// the end of the switch when there is no `default`. That failure path can point
2765    /// backwards (`default` written first), so the runs and their labels are worked
2766    /// out before any code is emitted.
2767    fn switch(
2768        &mut self,
2769        discriminant: &Expr,
2770        cases: &[SwitchCase],
2771        stmt: &Stmt,
2772    ) -> Result<(), SyntaxError> {
2773        self.reset_value();
2774        // The discriminant is evaluated outside the switch's block scope, before
2775        // any `case` clause exists.
2776        self.expr(discriminant)?;
2777
2778        let switch_key = stmt.span.start.offset as u64;
2779        let switch_parent = self.cur().current_block;
2780        self.push_block(switch_key, switch_parent);
2781        self.emit_scope_enter(switch_key);
2782
2783        let break_label = self.new_label();
2784        self.push_jump_target(JumpTarget {
2785            names: Vec::new(),
2786            break_label: Some(break_label),
2787            // `switch` is a valid `break` target but not a `continue` target.
2788            continue_label: None,
2789            // The discriminant stays on the value stack for the whole statement, so
2790            // a `break` aimed further out has to discard it.
2791            drop_count: 1,
2792            finally_label: None,
2793            is_regular_stmt: false,
2794            has_iterator: false,
2795        });
2796
2797        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
2798        // its label to the clause after it, so both tests reach the same body.
2799        let mut runs: Vec<(usize, usize)> = Vec::new();
2800        let mut scan = 0;
2801        while scan < cases.len() {
2802            if cases[scan].test.is_some() {
2803                let mut last = scan;
2804                while last + 1 < cases.len()
2805                    && cases[last].test.is_some()
2806                    && cases[last].body.is_empty()
2807                    && cases[last + 1].test.is_some()
2808                {
2809                    last += 1;
2810                }
2811                runs.push((scan, last));
2812                scan = last + 1;
2813            } else {
2814                scan += 1;
2815            }
2816        }
2817
2818        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
2819        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
2820        let default_at = cases.iter().position(|case| case.test.is_none());
2821        // Where the last run sends control when nothing matched.
2822        let miss_target = match default_at {
2823            Some(index) => body_labels[index],
2824            None => break_label,
2825        };
2826
2827        // When `default` comes first, control has to jump over it to reach the
2828        // tests. It only needs to when some clause actually has a test; otherwise
2829        // the default body is the entry point.
2830        let mut entry = None;
2831        if default_at == Some(0) && !runs.is_empty() {
2832            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
2833            entry = Some(run_labels[0]);
2834        }
2835
2836        let mut index = 0;
2837        let mut run = 0;
2838        let result = (|| -> Result<(), SyntaxError> {
2839            while index < cases.len() {
2840                if cases[index].test.is_some() {
2841                    let (first, last) = runs[run];
2842                    // Reaching these tests from the preceding body is a
2843                    // fallthrough, which continues inside the body and skips them.
2844                    if index > 0 {
2845                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
2846                    }
2847                    if let Some(label) = entry.take() {
2848                        self.place_label(label);
2849                    }
2850                    self.place_label(run_labels[run]);
2851
2852                    for (offset, case) in cases[first..=last].iter().enumerate() {
2853                        let test = case.test.as_ref().unwrap();
2854                        self.emit(Opcode::Dup, &[]);
2855                        self.expr(test)?;
2856                        self.emit(Opcode::StrictEq, &[]);
2857                        if first + offset < last {
2858                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
2859                        } else {
2860                            // Hand over to the next run's tests, or give up.
2861                            let next = match runs.get(run + 1) {
2862                                Some(_) => run_labels[run + 1],
2863                                None => miss_target,
2864                            };
2865                            self.emit_jump(Opcode::IfFalse, next, &[]);
2866                        }
2867                    }
2868
2869                    self.place_label(body_labels[index]);
2870                    for case in &cases[first..=last] {
2871                        self.stmts(&case.body)?;
2872                    }
2873                    index = last + 1;
2874                    run += 1;
2875                } else {
2876                    // `default`: control arrives here either by falling through or
2877                    // because every test missed.
2878                    self.place_label(body_labels[index]);
2879                    self.stmts(&cases[index].body)?;
2880                    index += 1;
2881                }
2882            }
2883            Ok(())
2884        })();
2885
2886        if result.is_ok() {
2887            self.place_label(break_label);
2888            // Discard the discriminant now that no test needs it.
2889            self.emit(Opcode::Drop, &[]);
2890        }
2891
2892        self.pop_jump_target();
2893        self.emit_scope_leave(switch_key);
2894        self.state().current_block = switch_parent;
2895        result
2896    }
2897
2898    /// Compile `try`/`catch`/`finally`.
2899    ///
2900    /// The shape is an exception table built out of `catch` instructions, each of
2901    /// which records where control goes if the instructions that follow raise:
2902    ///
2903    /// ```text
2904    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
2905    ///   <guarded block>
2906    ///   drop                   <- discard the catch offset
2907    ///   undefined; gosub FINALLY; drop
2908    ///   goto END
2909    /// HANDLER:
2910    ///   <bind the catch parameter>
2911    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
2912    ///   <handler body>
2913    ///   drop; undefined; gosub FINALLY; drop; goto END
2914    /// CATCH2:
2915    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
2916    /// FINALLY:
2917    ///   <finalizer>
2918    ///   ret                    <- return to the `gosub`
2919    /// END:
2920    /// ```
2921    ///
2922    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
2923    /// of the finalizer serves the normal path, the handler path and the
2924    /// propagating-exception path.
2925    ///
2926    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
2927    /// runs with `ret_value` on the stack, and the normal path has no value to
2928    /// keep, so it pushes one to keep the stack depth identical on every path.
2929    fn try_stmt(
2930        &mut self,
2931        stmt: &Stmt,
2932        block: &[Stmt],
2933        handler: &Option<CatchClause>,
2934        finalizer: Option<&[Stmt]>,
2935    ) -> Result<(), SyntaxError> {
2936        self.reset_value();
2937
2938        let catch_label = self.new_label();
2939        let catch2_label = self.new_label();
2940        let finally_label = self.new_label();
2941        let end_label = self.new_label();
2942
2943        self.emit_jump(Opcode::Catch, catch_label, &[]);
2944
2945        // The guarded block. `break` may not target it, so its entry exists purely
2946        // to unwind: a jump out has to discard the catch offset and run the
2947        // finalizer.
2948        self.push_jump_target(JumpTarget {
2949            names: Vec::new(),
2950            break_label: None,
2951            continue_label: None,
2952            drop_count: 1,
2953            finally_label: Some(finally_label),
2954            is_regular_stmt: false,
2955            has_iterator: false,
2956        });
2957
2958        let block_key = Self::try_block_key(stmt, TryPart::Block);
2959        let block_parent = self.cur().current_block;
2960        self.push_block(block_key, block_parent);
2961        self.emit_scope_enter(block_key);
2962        self.stmts(block)?;
2963        self.emit_scope_leave(block_key);
2964        self.state().current_block = block_parent;
2965        // A guarded block that ends in a `return`/`throw` never reaches the
2966        // epilogue, so the reference does not emit one.
2967        self.pop_jump_target();
2968        let block_live = !block.last().is_some_and(Self::terminates);
2969
2970        if block_live {
2971            self.emit(Opcode::Drop, &[]);
2972            self.emit(Opcode::Undefined, &[]);
2973            self.emit_jump(Opcode::Gosub, finally_label, &[]);
2974            self.emit(Opcode::Drop, &[]);
2975            self.emit_jump(Opcode::Goto, end_label, &[]);
2976        }
2977
2978        if let Some(handler) = handler {
2979            self.place_label(catch_label);
2980            // The thrown value is on top of the stack: bind it, or discard it for
2981            // `catch { }`.
2982            match &handler.param {
2983                Some(Pattern {
2984                    kind: PatternKind::Ident(name),
2985                    ..
2986                }) => {
2987                    // The store resolves the name, so it has to run inside the
2988                    // parameter's own scope; otherwise a same-named `catch` further
2989                    // out could win.
2990                    let param_key = Self::try_block_key(stmt, TryPart::Param);
2991                    let param_parent = self.cur().current_block;
2992                    self.push_block(param_key, param_parent);
2993                    self.emit_var(VarAction::Put, &name.name);
2994                    self.state().current_block = param_parent;
2995                }
2996                Some(other) => {
2997                    return Err(SyntaxError::new(
2998                        "destructuring catch parameters are not supported by the compiler yet",
2999                        other.span,
3000                    ));
3001                }
3002                None => self.emit(Opcode::Drop, &[]),
3003            }
3004            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3005
3006            self.push_jump_target(JumpTarget {
3007                names: Vec::new(),
3008                break_label: None,
3009                continue_label: None,
3010                drop_count: 1,
3011                finally_label: Some(finally_label),
3012                is_regular_stmt: false,
3013                has_iterator: false,
3014            });
3015            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3016            let catch_parent = self.cur().current_block;
3017            self.push_block(catch_key, catch_parent);
3018            self.emit_scope_enter(catch_key);
3019            self.stmts(&handler.body)?;
3020            self.emit_scope_leave(catch_key);
3021            self.state().current_block = catch_parent;
3022            self.pop_jump_target();
3023            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3024
3025            if handler_live {
3026                self.emit(Opcode::Drop, &[]);
3027                self.emit(Opcode::Undefined, &[]);
3028                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3029                self.emit(Opcode::Drop, &[]);
3030                self.emit_jump(Opcode::Goto, end_label, &[]);
3031            }
3032
3033            // An error raised inside the handler still has to run the finalizer.
3034            self.place_label(catch2_label);
3035            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3036            self.emit(Opcode::Throw, &[]);
3037        } else {
3038            // `try`/`finally` with no handler: the finalizer runs, then the error
3039            // keeps propagating.
3040            self.place_label(catch_label);
3041            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3042            self.emit(Opcode::Throw, &[]);
3043        }
3044
3045        self.place_label(finally_label);
3046        // Inside the finalizer, leaving has a different cost: the return value and
3047        // the `gosub` return address are both on the stack, and neither finalizer nor
3048        // any outer one may run before the block has finished.
3049        self.push_jump_target(JumpTarget {
3050            names: Vec::new(),
3051            break_label: None,
3052            continue_label: None,
3053            drop_count: 2,
3054            finally_label: None,
3055            is_regular_stmt: false,
3056            has_iterator: false,
3057        });
3058        if let Some(finalizer) = finalizer {
3059            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3060            let finally_parent = self.cur().current_block;
3061            self.push_block(finally_key, finally_parent);
3062            self.emit_scope_enter(finally_key);
3063            self.stmts(finalizer)?;
3064            self.emit_scope_leave(finally_key);
3065            self.state().current_block = finally_parent;
3066        }
3067        self.pop_jump_target();
3068        self.emit(Opcode::Ret, &[]);
3069        self.place_label(end_label);
3070        Ok(())
3071    }
3072
3073    /// Compile `for`/`in` and `for`/`of`.
3074    ///
3075    /// Both keep an enumeration record on the value stack for the whole loop, which
3076    /// is what makes leaving early expensive: the record has to be dropped, or the
3077    /// iterator closed. The layout is
3078    ///
3079    /// ```text
3080    ///   <iterated expression>
3081    ///   for_in_start | for_of_start      <- pushes the record
3082    ///   goto TEST
3083    /// NEXT:
3084    ///   <bind the loop variable>
3085    ///   <body>
3086    /// TEST:
3087    ///   for_in_next | for_of_next 0
3088    ///   if_false NEXT                    <- not finished: next iteration
3089    ///   drop                             <- finished: discard the leftover value
3090    /// BREAK:
3091    ///   drop | iterator_close            <- the one cleanup `break` also uses
3092    /// ```
3093    ///
3094    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3095    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3096    /// of its own, and only a jump that passes *through* the loop pays for its record.
3097    fn for_in_of(
3098        &mut self,
3099        stmt: &Stmt,
3100        left: &ForHead,
3101        right: &Expr,
3102        body: &Stmt,
3103        kind: ForLoopKind,
3104        labels: &[String],
3105    ) -> Result<(), SyntaxError> {
3106        self.reset_value();
3107
3108        let loop_key = stmt.span.start.offset as u64;
3109        let loop_parent = self.cur().current_block;
3110        self.push_block(loop_key, loop_parent);
3111        self.emit_scope_enter(loop_key);
3112
3113        // The iterated expression is evaluated inside the loop's scope, after the
3114        // bindings exist in the temporal dead zone.
3115        self.expr(right)?;
3116
3117        let next = self.new_label();
3118        let test = self.new_label();
3119        let break_target = self.new_label();
3120
3121        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3122        match kind {
3123            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3124            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3125            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3126        }
3127        self.emit_jump(Opcode::Goto, test, &[]);
3128
3129        self.push_jump_target(JumpTarget {
3130            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3131            // loop had no label to break to, and the compiler reported "break has no
3132            // enclosing loop" for a loop that was plainly enclosing it.
3133            names: labels.to_vec(),
3134            break_label: Some(break_target),
3135            continue_label: Some(test),
3136            // Passing through the loop has to dispose of its record. A `for`/`of`
3137            // record is three slots, and closing the iterator consumes all of them.
3138            drop_count: if has_iterator { 3 } else { 1 },
3139            finally_label: None,
3140            is_regular_stmt: false,
3141            has_iterator,
3142        });
3143
3144        self.place_label(next);
3145        self.bind_loop_variable(left)?;
3146        // The reference marks the body with its own label here. Nothing jumps to it
3147        // once the loop is laid out, but it is not decoration: a label between the
3148        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3149        // `set_loc v` when the body starts by reading the loop variable.
3150        let body_label = self.new_label();
3151        self.place_label(body_label);
3152        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3153        // region rather than the whole loop: the resource is the element that this
3154        // iteration produced.
3155        let using_slot = match left {
3156            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3157                decl.declarators
3158                    .first()
3159                    .and_then(|declarator| match &declarator.target.kind {
3160                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3161                        _ => None,
3162                    })
3163            }
3164            _ => None,
3165        };
3166        match using_slot {
3167            Some(slot) => {
3168                let live = !Self::terminates(body);
3169                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3170            }
3171            None => self.stmt(body)?,
3172        }
3173
3174        self.place_label(test);
3175        match kind {
3176            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3177            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3178            ForLoopKind::AwaitOf => {
3179                // The reference's shape: step, `await` the result, then unpack it.
3180                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3181                self.emit(Opcode::Await, &[]);
3182                self.state().has_await = true;
3183                self.emit(Opcode::IteratorGetValueDone, &[]);
3184            }
3185        }
3186        self.emit_jump(Opcode::IfFalse, next, &[]);
3187        // The loop is finished; `for_xx_next` left an `undefined` behind.
3188        self.emit(Opcode::Drop, &[]);
3189
3190        self.pop_jump_target();
3191        self.place_label(break_target);
3192        if has_iterator {
3193            self.emit(Opcode::IteratorClose, &[]);
3194        } else {
3195            self.emit(Opcode::Drop, &[]);
3196        }
3197
3198        self.emit_scope_leave(loop_key);
3199        self.state().current_block = loop_parent;
3200        Ok(())
3201    }
3202
3203    /// Store the value `for_xx_next` left on the stack into the loop variable.
3204    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3205        // A declaration *initialises* the binding, which is what takes a `let` out of
3206        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3207        // binding declared elsewhere is an ordinary write and keeps its check.
3208        let (pattern, action) = match left {
3209            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3210            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3211        };
3212        match &pattern.kind {
3213            PatternKind::Ident(name) => {
3214                // `for (using x of …)` validates and snapshots each iteration's value
3215                // before the body runs, which is what makes a non-disposable element fail
3216                // on the iteration that produced it rather than at the end of the loop.
3217                if let ForHead::VarDecl(decl) = left
3218                    && decl.kind.is_using()
3219                {
3220                    let method_slot = self
3221                        .using_method_slot(&name.name)
3222                        .expect("a using binding was declared during hoisting");
3223                    self.emit(
3224                        Opcode::UsingCheck,
3225                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3226                    );
3227                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3228                }
3229                self.emit_var(action, &name.name);
3230                Ok(())
3231            }
3232            // Every other target stores through the same path an assignment pattern
3233            // uses, which is what makes `for (a[0] in obj)` write each key into the
3234            // property instead of refusing the loop outright.
3235            _ => self.destructure(
3236                pattern,
3237                match left {
3238                    ForHead::VarDecl(decl) => Some(decl.kind),
3239                    ForHead::Assign(_) => None,
3240                },
3241            ),
3242        }
3243    }
3244
3245    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3246        for declarator in &decl.declarators {
3247            let Some(init) = &declarator.init else {
3248                // `var x;` stays `undefined`. A lexical binding is different: it
3249                // has to be *initialised* to leave the temporal dead zone, so the
3250                // compiler supplies an explicit `undefined`.
3251                if decl.kind.is_lexical() {
3252                    // A lexical binding has to be *initialised* to leave the temporal
3253                    // dead zone, and a destructuring one is no different — `let {a}`
3254                    // with no initialiser is a syntax error, but `let [a] = []` still
3255                    // needs `a` to be initialised from an empty source, which the
3256                    // pattern does on its own.
3257                    self.emit(Opcode::Undefined, &[]);
3258                    self.destructure(&declarator.target, Some(decl.kind))?;
3259                }
3260                continue;
3261            };
3262            match &declarator.target.kind {
3263                PatternKind::Ident(name) => {
3264                    self.expr(init)?;
3265                    self.set_name_if_anonymous(init, &name.name);
3266                    if decl.kind.is_using() {
3267                        // `using_check` validates the value and snapshots its dispose
3268                        // method: `value -> value, method`. The snapshot is what makes a
3269                        // later change to `Symbol.dispose` irrelevant, and validating here
3270                        // is what keeps the body from running at all when the value is not
3271                        // disposable.
3272                        let method_slot = self
3273                            .using_method_slot(&name.name)
3274                            .expect("a using binding was declared during hoisting");
3275                        self.emit(
3276                            Opcode::UsingCheck,
3277                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3278                        );
3279                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3280                        self.emit_var(VarAction::PutInit, &name.name);
3281                        continue;
3282                    }
3283                    // A declaration statement produces no value, so nothing is
3284                    // duplicated onto the stack.
3285                    match decl.kind {
3286                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3287                        _ => self.emit_var(VarAction::PutInit, &name.name),
3288                    }
3289                }
3290                _ => {
3291                    // A destructuring declaration keeps nothing on the stack: the
3292                    // pattern consumes the initialiser.
3293                    self.expr(init)?;
3294                    self.destructure(&declarator.target, Some(decl.kind))?;
3295                }
3296            }
3297        }
3298        Ok(())
3299    }
3300
3301    /// Bind a destructuring pattern from the value on top of the stack.
3302    ///
3303    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3304    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3305    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3306    /// *assignment*, where a member expression is a legal target and the store is an
3307    /// ordinary property write.
3308    ///
3309    /// The value is consumed. An assignment expression's own result is the right-hand
3310    /// side, which the caller keeps separately — the spec does not make the pattern's
3311    /// last store produce it.
3312    fn destructure(
3313        &mut self,
3314        pattern: &Pattern,
3315        decl: Option<VarDeclKind>,
3316    ) -> Result<(), SyntaxError> {
3317        match &pattern.kind {
3318            PatternKind::Ident(name) => {
3319                match decl {
3320                    Some(VarDeclKind::Var) | None => {
3321                        self.emit_var(VarAction::Put, &name.name);
3322                    }
3323                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3324                }
3325                Ok(())
3326            }
3327            PatternKind::Assign { target, default } => {
3328                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3329                // keeps `null`.
3330                let use_default = self.new_label();
3331                let done = self.new_label();
3332                self.emit(Opcode::Dup, &[]);
3333                self.emit(Opcode::IsUndefined, &[]);
3334                self.emit_jump(Opcode::IfTrue, use_default, &[]);
3335                self.destructure(target, decl)?;
3336                self.emit_jump(Opcode::Goto, done, &[]);
3337                self.place_label(use_default);
3338                self.emit(Opcode::Drop, &[]);
3339                self.expr(default)?;
3340                // `var {f = function(){}} = {}` names the function `f`, like a plain
3341                // `var f = function(){}` does.
3342                self.destructure(target, decl)?;
3343                self.place_label(done);
3344                Ok(())
3345            }
3346            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3347            PatternKind::Object { properties, rest } => {
3348                self.destructure_object(properties, rest, decl, pattern)
3349            }
3350            PatternKind::Member(member) if decl.is_none() => {
3351                // An assignment pattern may store into a property. The value is on the
3352                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3353                // put the three in the order `put_array_el`/`put_field` expect.
3354                self.expr(&member.object)?;
3355                match &member.property {
3356                    MemberProp::Ident(name) => {
3357                        // `value obj` -> `obj value`, the order `put_field` takes.
3358                        // Nothing needs to be left behind: a pattern element's value is
3359                        // consumed by its own store.
3360                        self.emit(Opcode::Swap, &[]);
3361                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3362                    }
3363                    MemberProp::Computed(index) => {
3364                        self.expr(index)?;
3365                        // `value obj key` -> `obj key value`.
3366                        self.emit(Opcode::Rot3l, &[]);
3367                        self.emit(Opcode::PutArrayEl, &[]);
3368                    }
3369                    MemberProp::Private(_) => {
3370                        return Err(SyntaxError::new(
3371                            "private fields are not supported by the compiler yet",
3372                            member.span,
3373                        ));
3374                    }
3375                }
3376                Ok(())
3377            }
3378            PatternKind::Rest(inner) => self.destructure(inner, decl),
3379            PatternKind::Invalid(expr) => {
3380                Err(SyntaxError::new("invalid assignment target", expr.span))
3381            }
3382            _ => Err(SyntaxError::new(
3383                "this destructuring target is not supported by the compiler yet",
3384                pattern.span,
3385            )),
3386        }
3387    }
3388
3389    /// `[…]` on the left: drain an iterator, binding one target per element.
3390    fn destructure_array(
3391        &mut self,
3392        elements: &[Option<PatternElement>],
3393        rest: &Option<Box<RestElement>>,
3394        decl: Option<VarDeclKind>,
3395    ) -> Result<(), SyntaxError> {
3396        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3397        // pattern accepts any iterable and closes the iterator when the pattern ends
3398        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3399        // first because it is on top.
3400        self.emit(Opcode::ForOfStart, &[]);
3401        for element in elements {
3402            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3403            self.emit(Opcode::Drop, &[]);
3404            match element {
3405                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3406                Some(PatternElement::Property { span, .. }) => {
3407                    return Err(SyntaxError::new(
3408                        "a property pattern is not a valid array element",
3409                        *span,
3410                    ));
3411                }
3412                // An elision skips the value, which is already on the stack.
3413                None => self.emit(Opcode::Drop, &[]),
3414            }
3415        }
3416        if let Some(rest) = rest {
3417            // The remaining values go into a fresh array. The target and its running
3418            // index stay on the stack above the iterator, which is what the operand of
3419            // `for_of_next` accounts for: two values sit above the iterator triple.
3420            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3421            self.emit(Opcode::Push0, &[]);
3422            let top = self.new_label();
3423            self.place_label(top);
3424            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3425            let done = self.new_label();
3426            self.emit_jump(Opcode::IfTrue, done, &[]);
3427            self.emit(Opcode::DefineArrayEl, &[]);
3428            self.emit(Opcode::Inc, &[]);
3429            self.emit_jump(Opcode::Goto, top, &[]);
3430            self.place_label(done);
3431            self.emit(Opcode::Drop, &[]);
3432            self.emit(Opcode::Drop, &[]);
3433            self.destructure_rest(rest, decl)?;
3434        }
3435        self.emit(Opcode::IteratorClose, &[]);
3436        Ok(())
3437    }
3438
3439    /// `{…}` on the left: read properties off one boxed source object.
3440    fn destructure_object(
3441        &mut self,
3442        properties: &[Option<PatternElement>],
3443        rest: &Option<Box<RestElement>>,
3444        decl: Option<VarDeclKind>,
3445        pattern: &Pattern,
3446    ) -> Result<(), SyntaxError> {
3447        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3448        // aside for the rest element below.
3449        self.emit(Opcode::ToObject, &[]);
3450        let mut taken: Vec<String> = Vec::new();
3451        // Whether any key was computed, which a rest element cannot exclude.
3452        let mut computed = false;
3453        for property in properties {
3454            let Some(PatternElement::Property {
3455                key, value, span, ..
3456            }) = property
3457            else {
3458                return Err(SyntaxError::new(
3459                    "a bare pattern is not a valid object property",
3460                    properties
3461                        .iter()
3462                        .flatten()
3463                        .map(|element| match element {
3464                            PatternElement::Pattern(pattern) => pattern.span,
3465                            PatternElement::Property { span, .. } => *span,
3466                        })
3467                        .next()
3468                        .unwrap_or(pattern.span),
3469                ));
3470            };
3471            // Every read needs the source twice: once to read from, once to keep for
3472            // the next property. `get_field2` is not used here because the value has to
3473            // come off a stack that also holds the source.
3474            self.emit(Opcode::Dup, &[]);
3475            match key {
3476                PropName::Literal(literal) => {
3477                    let name = self.property_key_text(literal, *span)?;
3478                    taken.push(name.clone());
3479                    self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name))]);
3480                }
3481                PropName::Computed(index) => {
3482                    // A computed key has no name to exclude ahead of time, so a rest
3483                    // element that has to skip it is refused below rather than silently
3484                    // copying the property into the rest object.
3485                    computed = true;
3486                    self.expr(index)?;
3487                    self.emit(Opcode::GetArrayEl, &[]);
3488                }
3489                PropName::Private(_) => {
3490                    return Err(SyntaxError::new(
3491                        "private fields are not supported by the compiler yet",
3492                        value.span,
3493                    ));
3494                }
3495            }
3496            self.destructure(value, decl)?;
3497        }
3498        match rest {
3499            Some(rest) => {
3500                if computed {
3501                    return Err(SyntaxError::new(
3502                        "a computed key with a rest element is not supported by the compiler yet",
3503                        Self::rest_span(rest),
3504                    ));
3505                }
3506                // `target src exclude`: the exclusion list is an array of the keys the
3507                // literal part already took, so the rest object gets only the others.
3508                self.emit(Opcode::Object, &[]);
3509                self.emit(Opcode::Swap, &[]);
3510                for name in &taken {
3511                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
3512                }
3513                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
3514                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
3515                self.emit(Opcode::Drop, &[]);
3516                self.emit(Opcode::Drop, &[]);
3517                self.destructure_rest(rest, decl)?;
3518            }
3519            // The source was only kept for a rest element.
3520            None => self.emit(Opcode::Drop, &[]),
3521        }
3522        Ok(())
3523    }
3524
3525    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
3526    fn destructure_rest(
3527        &mut self,
3528        rest: &RestElement,
3529        decl: Option<VarDeclKind>,
3530    ) -> Result<(), SyntaxError> {
3531        match rest {
3532            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
3533            // `[...a.b] = c` stores into a property.
3534            RestElement::Member(member) => {
3535                let pattern = Pattern {
3536                    kind: PatternKind::Member(member.clone()),
3537                    span: member.span,
3538                };
3539                self.destructure(&pattern, decl)
3540            }
3541        }
3542    }
3543
3544    /// The source range of a rest element, for error messages.
3545    fn rest_span(rest: &RestElement) -> Span {
3546        match rest {
3547            RestElement::Pattern(pattern) => pattern.span,
3548            RestElement::Member(member) => member.span,
3549        }
3550    }
3551
3552    /// Compile a function declaration and queue it for instantiation at scope
3553    /// entry.
3554    ///
3555    /// A declaration is visible before the statement that declares it, so the
3556    /// code that creates the function object belongs at the top of the enclosing
3557    /// scope, not at the declaration.
3558    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
3559        let name = func.name.as_ref().expect("a declaration has a name");
3560        let function = self.compile_function(func)?;
3561        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
3562        let target = self.hoist_target(&name.name);
3563        let block = self.cur().current_block;
3564        self.state().hoisted.push((block, target, pool_index));
3565        Ok(())
3566    }
3567
3568    /// Where a name lives, for a hoisted declaration.
3569    fn hoist_target(&self, name: &str) -> HoistTarget {
3570        let state = self.cur();
3571        if let Some(index) = state.args.iter().position(|a| a.name == name) {
3572            return HoistTarget::Arg(index as u32);
3573        }
3574        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
3575            return HoistTarget::Loc(index as u32);
3576        }
3577        // A global function declaration is not a slot at all.
3578        HoistTarget::Global(name.to_string())
3579    }
3580
3581    // -- expressions -------------------------------------------------------
3582
3583    /// Compile one expression, recording where its instructions sit.
3584    ///
3585    /// The position is the node's operator when it has one and its first token
3586    /// otherwise, and it is restored on the way out so a parent's own instructions —
3587    /// which are emitted *after* its children — are blamed on the parent. Without the
3588    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
3589    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
3590        let saved = self.cur().cur_pos;
3591        // Only the node kinds the reference calls `emit_source_pos` for record a position:
3592        // the operator a node exists for, and a variable *read*, which the reference
3593        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
3594        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
3595        // start, a parenthesised group, an anonymous function expression — leaves the
3596        // previous position in place, because a table entry the reference never writes is
3597        // one we must not write either: the instruction that inherits a position (the
3598        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
3599        // report a more recent token than the reference does.
3600        let pos = expr.op_pos.or(match &expr.kind {
3601            ExprKind::Ident(ident) => Some(ident.span.start),
3602            _ => None,
3603        });
3604        match pos {
3605            Some(pos) => self.state().cur_pos = Some(pos),
3606            // A node the reference records nothing for: its own instructions stay
3607            // unpositioned, so they inherit whatever was written last — which is what an
3608            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
3609            // enclosing position instead would blame them on a token the reference has not
3610            // reached yet: a spread's `iterator_open` reports the expression it follows, and
3611            // a template's `to_propkey` the interpolation.
3612            None => self.state().cur_pos = None,
3613        }
3614        // Note a direct `eval` call before compiling it, because the *whole* function
3615        // is affected: an eval can name any binding the function declares, so every one
3616        // of them has to live in a cell for a closure it creates to capture it.
3617        if Self::is_direct_eval(expr) {
3618            // Every enclosing function is affected too: the eval sees the whole scope
3619            // chain, and a closure it creates can capture a binding of any of them.
3620            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
3621            // cell, because the closure the eval builds outlives the loop iteration.
3622            for state in &mut self.stack {
3623                state.has_direct_eval = true;
3624            }
3625            let block = self.cur().current_block;
3626            let in_params = self.cur().in_params;
3627            self.state()
3628                .pending_eval_sites
3629                .push((expr.span, block, in_params));
3630        }
3631        let result = self.expr_inner(expr);
3632        self.state().cur_pos = saved;
3633        result
3634    }
3635
3636    /// Record which bindings are in scope at a direct `eval` call.
3637    ///
3638    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
3639    /// resolves names from a string at run time, so the only chance to pin down *which*
3640    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
3641    /// its block is the current block, an enclosing one, or the function scope.
3642    fn materialize_eval_sites(&mut self) {
3643        let pending = std::mem::take(&mut self.state().pending_eval_sites);
3644        for (span, site_block, in_params) in pending {
3645            self.resolve_eval_site(span, site_block, in_params);
3646        }
3647    }
3648
3649    /// Resolve the bindings visible at one `eval` call.
3650    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
3651        /// How near a binding is: function distance first, then block depth, then the
3652        /// later declaration (which shadows the earlier one in the same block).
3653        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
3654
3655        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
3656        // walked, innermost function first: a direct `eval` sees every enclosing
3657        // function's bindings, and none of them can be resolved at run time because the
3658        // runtime only has names to go on.
3659        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
3660        let deepest = self.stack.len() - 1;
3661        for (level, state) in self.stack.iter().enumerate().rev() {
3662            let owner = (deepest - level) as u32;
3663            // The innermost function's block is the one the call sat in, which is not
3664            // the block the compiler is in now; the enclosing functions are still at
3665            // the point where this one was created.
3666            let here = if level == deepest {
3667                site_block
3668            } else {
3669                state.current_block
3670            };
3671            // The chain of live blocks, innermost first, with a depth for each. The walk
3672            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
3673            // block can start at source offset zero.
3674            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
3675            let mut block = here;
3676            while let Some(parent) = state
3677                .blocks
3678                .iter()
3679                .find(|candidate| candidate.key == block)
3680                .map(|candidate| candidate.parent)
3681                .filter(|parent| *parent != NO_PARENT)
3682                .filter(|parent| parent != &block)
3683            {
3684                live.push((parent, live.len()));
3685                block = parent;
3686            }
3687            let depth_of = |key: u64| {
3688                live.iter()
3689                    .find(|(candidate, _)| *candidate == key)
3690                    .map(|(_, depth)| *depth)
3691                    // The function scope is the outermost depth there is. A binding of a
3692                    // block this site is not inside lands here too, which pushes it
3693                    // behind every live one — the right answer: it is out of scope.
3694                    .unwrap_or(live.len())
3695            };
3696            for (index, arg) in state.args.iter().enumerate() {
3697                bindings.push((
3698                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
3699                    EvalVisible {
3700                        name: arg.name.clone(),
3701                        is_arg: true,
3702                        index: index as u32,
3703                        owner,
3704                    },
3705                ));
3706            }
3707            // A parameter list cannot see the body, so a body `var` is not a binding the
3708            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
3709            // not let that eval write the body's `c`.
3710            let hides_body = if level == deepest {
3711                site_in_params
3712            } else {
3713                state.created_in_params
3714            };
3715            for (index, var) in state.vars.iter().enumerate() {
3716                let block = state
3717                    .var_block
3718                    .get(index)
3719                    .copied()
3720                    .unwrap_or(FUNCTION_SCOPE);
3721                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
3722                    continue;
3723                }
3724                bindings.push((
3725                    (
3726                        owner as usize,
3727                        depth_of(block),
3728                        std::cmp::Reverse(index as u32),
3729                    ),
3730                    EvalVisible {
3731                        name: var.name.clone(),
3732                        is_arg: false,
3733                        index: index as u32,
3734                        owner,
3735                    },
3736                ));
3737            }
3738        }
3739        // Innermost function first, then innermost block, then the later declaration
3740        // (which shadows the earlier one within a block).
3741        bindings.sort_by_key(|(priority, _)| *priority);
3742        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
3743        self.state().eval_sites.push(EvalSite {
3744            line: span.start.line,
3745            column: span.start.column,
3746            bindings,
3747        });
3748    }
3749
3750    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
3751    ///
3752    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
3753    /// a bare identifier callee counts.
3754    fn is_direct_eval(expr: &Expr) -> bool {
3755        matches!(
3756            &expr.kind,
3757            ExprKind::Call { callee, .. }
3758                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
3759        )
3760    }
3761
3762    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
3763        match &expr.kind {
3764            ExprKind::Number(value) => self.push_number(*value),
3765            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
3766            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
3767            ExprKind::Null => self.emit(Opcode::Null, &[]),
3768            ExprKind::String(text) => self.push_string(text),
3769            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
3770            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
3771            ExprKind::This => self.this_expression(),
3772            ExprKind::NewTarget => self.new_target_expression(),
3773            ExprKind::Paren(inner) => self.expr(inner)?,
3774            ExprKind::Binary { op, left, right } => {
3775                self.expr(left)?;
3776                self.expr(right)?;
3777                self.emit(binary_opcode(*op), &[]);
3778            }
3779            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
3780            ExprKind::Unary {
3781                op: UnaryOp::Minus,
3782                argument,
3783            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
3784                let ExprKind::Number(value) = argument.unparen().kind else {
3785                    unreachable!("matched above")
3786                };
3787                // The reference folds a negative literal only when the negation is
3788                // exact in the integer range: `-1` becomes `push_minus1` and
3789                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
3790                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
3791                // `-Infinity`, not `Infinity` — and folding a fraction would change
3792                // which instruction the reference emits.
3793                let negated = -value;
3794                // `-2147483648` is deliberately excluded: its magnitude is one past
3795                // `i32::MAX`, so the reference sends it through the constant pool and
3796                // negates at run time instead.
3797                if value > 0.0
3798                    && negated == negated.trunc()
3799                    && negated >= -(i32::MAX as f64)
3800                    && negated < 0.0
3801                {
3802                    self.push_number(negated);
3803                } else {
3804                    self.push_number(value);
3805                    self.emit(Opcode::Neg, &[]);
3806                }
3807            }
3808            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
3809            ExprKind::Conditional { test, cons, alt } => {
3810                let else_label = self.new_label();
3811                let end_label = self.new_label();
3812                self.expr(test)?;
3813                self.emit_jump(Opcode::IfFalse, else_label, &[]);
3814                self.expr(cons)?;
3815                self.emit_jump(Opcode::Goto, end_label, &[]);
3816                self.place_label(else_label);
3817                self.expr(alt)?;
3818                self.place_label(end_label);
3819            }
3820            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
3821            ExprKind::Update {
3822                op,
3823                argument,
3824                prefix,
3825            } => self.update(*op, argument, *prefix)?,
3826            ExprKind::Sequence(items) => {
3827                for (index, item) in items.iter().enumerate() {
3828                    self.expr(item)?;
3829                    if index + 1 != items.len() {
3830                        self.emit(Opcode::Drop, &[]);
3831                    }
3832                }
3833            }
3834            ExprKind::Call { .. } => self.chain_link_top(expr)?,
3835            ExprKind::Member { .. } => self.chain_link_top(expr)?,
3836            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
3837            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
3838            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
3839            ExprKind::Template(template) => self.template_literal(template)?,
3840            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
3841            ExprKind::New { callee, arguments } => {
3842                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
3843                // The `dup` is not redundant: `call_constructor` takes the
3844                // constructor twice, once as the target and once as `new.target`,
3845                // which is what makes `new.target === C` inside the body.
3846                self.expr(callee)?;
3847                self.emit(Opcode::Dup, &[]);
3848                let args = arguments.as_deref().unwrap_or(&[]);
3849                if Self::has_spread(args) {
3850                    // `C C array`: the duplicated callee is already both the target
3851                    // and `new.target`, so no reordering is needed before `apply 1`.
3852                    self.argument_array(args)?;
3853                    self.emit(Opcode::Apply, &[Op::Int(1)]);
3854                    return Ok(());
3855                }
3856                for argument in args {
3857                    self.expr(argument)?;
3858                }
3859                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
3860            }
3861            ExprKind::Class(class) => self.class_definition(class, true)?,
3862            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
3863            ExprKind::Yield { argument, delegate } => {
3864                self.yield_expression(argument.as_deref(), *delegate)?
3865            }
3866            ExprKind::Await(argument) => self.await_expression(argument)?,
3867            ExprKind::RegExp { pattern, flags } => {
3868                // A literal is compiled *here*, at parse time, not when the line runs. The
3869                // spec is explicit that an invalid pattern is an early error (§12.9.4:
3870                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
3871                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
3872                // also validates `\p{…}` names: 163 conformance cases are patterns that have
3873                // to be rejected before any code runs.
3874                //
3875                // This is the whole reason the engine lives in its own crate rather than
3876                // inside `quickjs-pure`: the compiler could not depend on the interpreter
3877                // (`pure` depends on `compile`), but both need this.
3878                // The lexer already rejected an unknown or repeated flag, so an unparsable
3879                // flag string here would be a bug in the lexer rather than in the script;
3880                // fall back to the default flags instead of inventing a second message.
3881                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
3882                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
3883                    SyntaxError::new(
3884                        format!("invalid regular expression: {}", error.message),
3885                        expr.span,
3886                    )
3887                })?;
3888                // The tree is thrown away and rebuilt when the literal first runs: keeping it
3889                // would mean serialising the syntax tree into the function's constant pool,
3890                // and a literal is created once per evaluation of its expression anyway.
3891                let _ = parsed;
3892                // The pattern and its flags travel as two string constants; `regexp` builds
3893                // the object. A dedicated opcode (rather than a call to the constructor) is
3894                // what the reference does too, so that a literal never goes through the
3895                // public `RegExp` function and its string-coercion rules.
3896                self.push_string(pattern);
3897                self.push_string(flags);
3898                self.emit(Opcode::Regexp, &[]);
3899            }
3900            ExprKind::Arrow(func) => {
3901                let function = self.compile_function(func)?;
3902                let index = self.push_constant(Constant::Function(Box::new(function)));
3903                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
3904            }
3905            ExprKind::Function(func) => {
3906                let function = self.compile_function_with_name(func, true)?;
3907                let index = self.push_constant(Constant::Function(Box::new(function)));
3908                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
3909            }
3910            // `import.meta`: the host fills a per-module object at link time.
3911            ExprKind::ImportMeta => {
3912                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
3913            }
3914            // `import("x")` compiles to a two-slot push followed by one opcode: the
3915            // specifier, then the options object (`undefined` here, since this compiler
3916            // does not accept the second argument yet).
3917            ExprKind::ImportCall(specifier) => {
3918                self.expr(specifier)?;
3919                self.emit(Opcode::Undefined, &[]);
3920                self.emit(Opcode::Import, &[]);
3921            }
3922            _ => {
3923                return Err(SyntaxError::new(
3924                    "this expression form is not supported by the compiler yet",
3925                    expr.span,
3926                ));
3927            }
3928        }
3929        Ok(())
3930    }
3931
3932    /// Build one array holding the evaluated call arguments, which is how a call
3933    /// containing a spread is compiled: the reference does the same, building the
3934    /// list on the stack and handing it to `apply`.
3935    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
3936        let elements: Vec<Option<ArrayElement>> = arguments
3937            .iter()
3938            .map(|argument| match &argument.unparen().kind {
3939                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
3940                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
3941            })
3942            .collect();
3943        self.array_literal(&elements, Span::default())
3944    }
3945
3946    /// Whether any argument is a spread, which is what selects the `apply` form.
3947    fn has_spread(arguments: &[Expr]) -> bool {
3948        arguments
3949            .iter()
3950            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
3951    }
3952
3953    /// Compile `a${x}b`.
3954    ///
3955    /// A template is a `+` chain built left to right: the leading chunk (or an empty
3956    /// string when the template starts with a substitution), then for each
3957    /// substitution its value, `to_propkey` and `add`, then the following chunk when
3958    /// it is not empty. `to_propkey` is what makes a number or object substitute the
3959    /// way `ToString` would while leaving the result a string for `add` to
3960    /// concatenate.
3961    ///
3962    /// The chunk is an atom rather than a constant-pool string, because a non-empty
3963    /// chunk always lands where a value is pushed and `push_atom_value` is the
3964    /// instruction the reference uses for it; the empty first chunk has its own
3965    /// zero-byte form.
3966    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
3967        let first = template.quasis.first();
3968        match first.and_then(|quasi| quasi.cooked.clone()) {
3969            Some(text) if !text.is_empty() => {
3970                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
3971            }
3972            // Either the template begins with a substitution, or the chunk is
3973            // empty — in both cases the chain needs a string to start from.
3974            _ => self.emit(Opcode::PushEmptyString, &[]),
3975        }
3976        for (index, expression) in template.expressions.iter().enumerate() {
3977            self.expr(expression)?;
3978            self.emit(Opcode::ToPropkey, &[]);
3979            self.emit(Opcode::Add, &[]);
3980            if let Some(text) = template
3981                .quasis
3982                .get(index + 1)
3983                .and_then(|quasi| quasi.cooked.clone())
3984                && !text.is_empty()
3985            {
3986                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
3987                self.emit(Opcode::Add, &[]);
3988            }
3989        }
3990        Ok(())
3991    }
3992
3993    /// Compile an object literal.
3994    ///
3995    /// The object is built in place: `object` pushes it, and each property leaves it
3996    /// on the stack with one field more, so no temporary is needed and later
3997    /// properties can overwrite earlier ones.
3998    ///
3999    /// The instruction depends on *how* the property was written, not on what kind
4000    /// of value it holds:
4001    ///
4002    /// | source | instruction |
4003    /// |---|---|
4004    /// | `{ a: v }` | `define_field a` |
4005    /// | `{ __proto__: v }` | `set_proto` |
4006    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4007    /// | `{ m() {} }` | `define_method m,4` |
4008    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4009    /// | `{ [k]() {} }` | `define_method_computed 4` |
4010    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4011    ///
4012    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4013    /// key itself, which is why the trailing `drop` is absent there too.
4014    /// `tag`…``: a call whose first argument is the call site's template object.
4015    ///
4016    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4017    /// array beside it, so `String.raw` can read the source text back. It is a constant
4018    /// because its contents never change; the reference builds one per call site and
4019    /// reuses it, while this builds one per evaluation, which only `tag` code that
4020    /// compares template objects across calls could tell apart.
4021    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4022        let cooked = quasi
4023            .quasis
4024            .iter()
4025            .map(|chunk| chunk.cooked.clone())
4026            .collect();
4027        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4028        let index = self.push_constant(Constant::Template { cooked, raw });
4029        let count = quasi.expressions.len() + 1;
4030        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4031        if let ExprKind::Member {
4032            object, property, ..
4033        } = &tag.unparen().kind
4034        {
4035            self.expr(object)?;
4036            match property {
4037                MemberProp::Ident(name) => {
4038                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4039                }
4040                MemberProp::Computed(key) => {
4041                    self.expr(key)?;
4042                    self.emit(Opcode::GetArrayEl2, &[]);
4043                }
4044                MemberProp::Private(_) => {
4045                    return Err(SyntaxError::new(
4046                        "private fields are not supported by the compiler yet",
4047                        tag.span,
4048                    ));
4049                }
4050            }
4051            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4052            for expression in &quasi.expressions {
4053                self.expr(expression)?;
4054            }
4055            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4056            return Ok(());
4057        }
4058        self.expr(tag)?;
4059        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4060        for expression in &quasi.expressions {
4061            self.expr(expression)?;
4062        }
4063        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4064        Ok(())
4065    }
4066
4067    fn object_literal(
4068        &mut self,
4069        properties: &[ObjectProperty],
4070        span: Span,
4071    ) -> Result<(), SyntaxError> {
4072        self.emit(Opcode::Object, &[]);
4073        for property in properties {
4074            match property {
4075                ObjectProperty::Spread(value) => {
4076                    // `copy_data_properties` takes the target, the source and an
4077                    // exclusion list; a literal `null` means "exclude nothing".
4078                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4079                    // exclusion list by stack offset.
4080                    self.expr(spread_argument(value))?;
4081                    self.emit(Opcode::Null, &[]);
4082                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4083                    self.emit(Opcode::Drop, &[]);
4084                    self.emit(Opcode::Drop, &[]);
4085                }
4086                ObjectProperty::Property {
4087                    key,
4088                    value,
4089                    kind,
4090                    shorthand,
4091                    span: property_span,
4092                } => match key {
4093                    PropName::Computed(key_expr) => {
4094                        self.expr(key_expr)?;
4095                        match kind {
4096                            PropertyKind::Value => {
4097                                self.emit(Opcode::ToPropkey, &[]);
4098                                self.expr(value)?;
4099                                self.set_name_if_anonymous_computed(value);
4100                                self.emit(Opcode::DefineArrayEl, &[]);
4101                                // `define_array_el` leaves the object and the key;
4102                                // the key is no longer needed.
4103                                self.emit(Opcode::Drop, &[]);
4104                            }
4105                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4106                                self.emit_method_function(value)?;
4107                                self.emit(
4108                                    Opcode::DefineMethodComputed,
4109                                    &[Op::Int(define_method_flags(*kind))],
4110                                );
4111                            }
4112                        }
4113                    }
4114                    PropName::Literal(key) => {
4115                        let name = self.property_key_text(key, *property_span)?;
4116                        match kind {
4117                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4118                                self.emit_method_function(value)?;
4119                                self.emit(
4120                                    Opcode::DefineMethod,
4121                                    &[
4122                                        Op::Atom(Atom::from_text(&name)),
4123                                        Op::Int(define_method_flags(*kind)),
4124                                    ],
4125                                );
4126                            }
4127                            PropertyKind::Value => {
4128                                self.expr(value)?;
4129                                // `{__proto__: x}` sets the prototype instead of
4130                                // creating a property; the shorthand `{__proto__}`
4131                                // is an ordinary property and does not.
4132                                if name == "__proto__" && !shorthand {
4133                                    self.emit(Opcode::SetProto, &[]);
4134                                } else {
4135                                    self.set_name_if_anonymous(value, &name);
4136                                    self.emit(
4137                                        Opcode::DefineField,
4138                                        &[Op::Atom(Atom::from_text(&name))],
4139                                    );
4140                                }
4141                            }
4142                        }
4143                    }
4144                    PropName::Private(_) => {
4145                        return Err(SyntaxError::new(
4146                            "private names are not valid in object literals",
4147                            *property_span,
4148                        ));
4149                    }
4150                },
4151            }
4152        }
4153        let _ = span;
4154        Ok(())
4155    }
4156
4157    /// Emit the function a method/accessor property defines.
4158    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4159        self.expr(value)
4160    }
4161
4162    /// The name a literal property key contributes.
4163    ///
4164    /// String keys are used as written. A numeric key is converted the way
4165    /// `ToString` would convert it, because the atom is made from that spelling:
4166    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4167    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<String, SyntaxError> {
4168        match key {
4169            PropKey::Str(text) => Ok(text.clone()),
4170            PropKey::Num(value) => numeric_key_text(*value, span),
4171        }
4172    }
4173
4174    /// Compile an optional chain.
4175    ///
4176    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4177    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4178    /// `undefined`. So the chain is compiled with one end label and every guard
4179    /// jumps to it. The parser hands us the extent of that spine as an
4180    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4181    /// exactly the scope the label has to cover.
4182    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4183        let end = self.new_label();
4184        self.chain_link(inner, end)?;
4185        self.place_label(end);
4186        Ok(())
4187    }
4188
4189    /// A member access or call reached from outside any optional chain.
4190    ///
4191    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4192    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4193    /// still created because [`Self::chain_link`] takes it, and placing it at the
4194    /// end is a no-op that keeps a single code path.
4195    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4196        let end = self.new_label();
4197        self.chain_link(expr, end)?;
4198        self.place_label(end);
4199        Ok(())
4200    }
4201
4202    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4203    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4204        match &expr.kind {
4205            ExprKind::Member {
4206                object,
4207                property,
4208                optional,
4209            } => {
4210                // `super.x` is not a lookup on a value: it starts at the home object's
4211                // prototype and keeps `this` as the receiver, so it cannot go through
4212                // `chain_link` and the ordinary field read.
4213                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4214                    self.super_base();
4215                    match property {
4216                        MemberProp::Ident(name) => self.emit(
4217                            Opcode::PushAtomValue,
4218                            &[Op::Atom(Atom::from_text(&name.name))],
4219                        ),
4220                        MemberProp::Computed(index) => self.expr(index)?,
4221                        MemberProp::Private(_) => {
4222                            return Err(SyntaxError::new(
4223                                "private fields are not supported by the compiler yet",
4224                                expr.span,
4225                            ));
4226                        }
4227                    }
4228                    self.emit(Opcode::GetSuperValue, &[]);
4229                    return Ok(());
4230                }
4231                self.chain_link(object, end)?;
4232                if *optional {
4233                    self.optional_guard(end);
4234                }
4235                match property {
4236                    // `.length` has its own opcode. The reference emits it for every
4237                    // object, not just arrays, so a name-based rule is right and
4238                    // cheaper than the generic field read.
4239                    MemberProp::Ident(name) if name.name == "length" => {
4240                        self.emit(Opcode::GetLength, &[]);
4241                    }
4242                    MemberProp::Ident(name) => {
4243                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4244                    }
4245                    MemberProp::Computed(index) => {
4246                        self.expr(index)?;
4247                        self.emit(Opcode::GetArrayEl, &[]);
4248                    }
4249                    MemberProp::Private(_) => {
4250                        return Err(SyntaxError::new(
4251                            "private fields are not supported by the compiler yet",
4252                            expr.span,
4253                        ));
4254                    }
4255                }
4256                Ok(())
4257            }
4258            ExprKind::Call {
4259                callee,
4260                arguments,
4261                optional,
4262            } => {
4263                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4264                // cannot: it reads the function and then calls it with no
4265                // receiver at all. The reference's answer is to keep the object
4266                // under the function value — `get_field2` reads a field and leaves
4267                // its base in place — and to use `call_method`, which takes the
4268                // receiver from the stack. Missing this does not just cost an
4269                // instruction, it loses the `this` binding.
4270                if let ExprKind::Member {
4271                    object,
4272                    property,
4273                    optional: member_optional,
4274                } = &callee.unparen().kind
4275                {
4276                    // `super.m()` reads the method off the home object's prototype but
4277                    // calls it with `this`, so the receiver goes under the read instead of
4278                    // being replaced by it.
4279                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4280                        self.super_base();
4281                        match property {
4282                            MemberProp::Ident(name) => self.emit(
4283                                Opcode::PushAtomValue,
4284                                &[Op::Atom(Atom::from_text(&name.name))],
4285                            ),
4286                            MemberProp::Computed(index) => self.expr(index)?,
4287                            MemberProp::Private(_) => {
4288                                return Err(SyntaxError::new(
4289                                    "private fields are not supported by the compiler yet",
4290                                    expr.span,
4291                                ));
4292                            }
4293                        }
4294                        // The two-output form would drop the receiver; this one replaces
4295                        // the prototype and the key, leaving `this` underneath.
4296                        self.emit(Opcode::GetArrayEl, &[]);
4297                        if Self::has_spread(arguments) {
4298                            self.argument_array(arguments)?;
4299                            self.emit(Opcode::Perm3, &[]);
4300                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4301                            return Ok(());
4302                        }
4303                        for argument in arguments {
4304                            self.expr(argument)?;
4305                        }
4306                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4307                        return Ok(());
4308                    }
4309                    self.chain_link(object, end)?;
4310                    if *member_optional {
4311                        self.optional_guard(end);
4312                    }
4313                    match property {
4314                        MemberProp::Ident(name) => {
4315                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4316                        }
4317                        MemberProp::Computed(index) => {
4318                            self.expr(index)?;
4319                            // The key is not needed after the read, so this is the
4320                            // two-output form: object, value.
4321                            self.emit(Opcode::GetArrayEl2, &[]);
4322                        }
4323                        MemberProp::Private(_) => {
4324                            return Err(SyntaxError::new(
4325                                "private fields are not supported by the compiler yet",
4326                                expr.span,
4327                            ));
4328                        }
4329                    }
4330                    if Self::has_spread(arguments) {
4331                        // Stack is `obj func`; the array goes on top, then `perm3`
4332                        // reorders to the `func this array` that `apply` wants.
4333                        self.argument_array(arguments)?;
4334                        self.emit(Opcode::Perm3, &[]);
4335                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4336                        return Ok(());
4337                    }
4338                    for argument in arguments {
4339                        self.expr(argument)?;
4340                    }
4341                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4342                    return Ok(());
4343                }
4344                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4345                // with `get_field2` so the base stays under it, and on the short-circuit
4346                // path pushes an extra `undefined` as a placeholder receiver — the call
4347                // then throws, which is what calling a missing optional chain should do.
4348                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4349                    && let ExprKind::Member {
4350                        object,
4351                        property,
4352                        optional: member_optional,
4353                    } = &inner.unparen().kind
4354                {
4355                    let call = self.new_label();
4356                    // A guard target of its own: the outer `end` skips the whole
4357                    // expression, and a short-circuited receiver still has to reach the
4358                    // call so that calling it throws.
4359                    let short = self.new_label();
4360                    self.chain_link(object, end)?;
4361                    if *member_optional {
4362                        self.optional_guard(short);
4363                    }
4364                    match property {
4365                        MemberProp::Ident(name) => {
4366                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4367                        }
4368                        MemberProp::Computed(index) => {
4369                            self.expr(index)?;
4370                            self.emit(Opcode::GetArrayEl2, &[]);
4371                        }
4372                        MemberProp::Private(_) => {
4373                            return Err(SyntaxError::new(
4374                                "private fields are not supported by the compiler yet",
4375                                expr.span,
4376                            ));
4377                        }
4378                    }
4379                    self.emit_jump(Opcode::Goto, call, &[]);
4380                    self.place_label(short);
4381                    self.emit(Opcode::Undefined, &[]);
4382                    self.place_label(call);
4383                    if Self::has_spread(arguments) {
4384                        self.argument_array(arguments)?;
4385                        self.emit(Opcode::Perm3, &[]);
4386                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4387                        return Ok(());
4388                    }
4389                    for argument in arguments {
4390                        self.expr(argument)?;
4391                    }
4392                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4393                    return Ok(());
4394                }
4395                self.chain_link(callee, end)?;
4396                if *optional {
4397                    self.optional_guard(end);
4398                }
4399                if Self::has_spread(arguments) {
4400                    // `func array -> func undefined array`, which is the plain-call
4401                    // form of `apply`: the receiver is `undefined`.
4402                    self.argument_array(arguments)?;
4403                    self.emit(Opcode::Undefined, &[]);
4404                    self.emit(Opcode::Swap, &[]);
4405                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4406                    return Ok(());
4407                }
4408                for argument in arguments {
4409                    self.expr(argument)?;
4410                }
4411                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4412                Ok(())
4413            }
4414            _ => self.expr(expr),
4415        }
4416    }
4417
4418    /// Compile `expr` as a tail call when it is one, reporting whether it was.
4419    ///
4420    /// `tail_call` reuses the current frame instead of pushing a new one, so a
4421    /// tail-recursive function runs in constant stack space. It also has to be the
4422    /// *last* thing the function does, which is why only a `return` reaches here.
4423    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4424        let ExprKind::Call {
4425            callee,
4426            arguments,
4427            optional: false,
4428        } = &expr.unparen().kind
4429        else {
4430            return Ok(false);
4431        };
4432        let end = self.new_label();
4433        if let ExprKind::Member {
4434            object,
4435            property,
4436            optional: false,
4437        } = &callee.unparen().kind
4438        {
4439            // `super.m()` in tail position is still an ordinary method call with `this`
4440            // as the receiver; only the read of the method differs.
4441            if matches!(object.unparen().kind, ExprKind::SuperProp) {
4442                self.super_base();
4443                match property {
4444                    MemberProp::Ident(name) => self.emit(
4445                        Opcode::PushAtomValue,
4446                        &[Op::Atom(Atom::from_text(&name.name))],
4447                    ),
4448                    MemberProp::Computed(index) => self.expr(index)?,
4449                    MemberProp::Private(_) => return Ok(false),
4450                }
4451                self.emit(Opcode::GetArrayEl, &[]);
4452                for argument in arguments {
4453                    self.expr(argument)?;
4454                }
4455                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4456                self.place_label(end);
4457                return Ok(true);
4458            }
4459            self.chain_link(object, end)?;
4460            match property {
4461                MemberProp::Ident(name) => {
4462                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4463                }
4464                MemberProp::Computed(index) => {
4465                    self.expr(index)?;
4466                    self.emit(Opcode::GetArrayEl2, &[]);
4467                }
4468                MemberProp::Private(_) => return Ok(false),
4469            }
4470            for argument in arguments {
4471                self.expr(argument)?;
4472            }
4473            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4474            self.place_label(end);
4475            return Ok(true);
4476        }
4477        self.chain_link(callee, end)?;
4478        for argument in arguments {
4479            self.expr(argument)?;
4480        }
4481        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
4482        self.place_label(end);
4483        Ok(true)
4484    }
4485
4486    /// The `?.` guard: keep the value if it is neither null nor undefined,
4487    /// otherwise replace it with `undefined` and leave the whole chain.
4488    fn optional_guard(&mut self, end: Label) {
4489        let cont = self.new_label();
4490        self.emit(Opcode::Dup, &[]);
4491        self.emit(Opcode::IsUndefinedOrNull, &[]);
4492        self.emit_jump(Opcode::IfFalse, cont, &[]);
4493        self.emit(Opcode::Drop, &[]);
4494        self.emit(Opcode::Undefined, &[]);
4495        self.emit_jump(Opcode::Goto, end, &[]);
4496        self.place_label(cont);
4497    }
4498
4499    fn push_number(&mut self, value: f64) {
4500        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
4501        // goes into the constant pool.
4502        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
4503            let int = value as i32;
4504            if (-1..=7).contains(&int) {
4505                self.emit(Opcode::PushI32, &[Op::Int(int)]);
4506                return;
4507            }
4508            if (-128..=127).contains(&int) {
4509                self.emit(Opcode::PushI8, &[Op::Int(int)]);
4510                return;
4511            }
4512            if (-32768..=32767).contains(&int) {
4513                self.emit(Opcode::PushI16, &[Op::Int(int)]);
4514                return;
4515            }
4516            self.emit(Opcode::PushI32, &[Op::Int(int)]);
4517            return;
4518        }
4519        let index = self.push_constant(Constant::Number(value));
4520        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4521    }
4522
4523    /// Push a `BigInt` literal.
4524    ///
4525    /// A value that fits an `i32` uses the immediate form, which is what the reference
4526    /// emits too; anything larger goes into the constant pool, because the operand of
4527    /// `push_bigint` is only four bytes wide.
4528    fn push_bigint(&mut self, digits: &str, radix: u32) {
4529        if radix == 10
4530            && let Ok(value) = digits.parse::<i64>()
4531            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
4532        {
4533            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
4534            return;
4535        }
4536        let index = self.push_constant(Constant::BigInt {
4537            digits: digits.to_string(),
4538            radix,
4539        });
4540        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4541    }
4542
4543    fn push_string(&mut self, text: &str) {
4544        if text.is_empty() {
4545            self.emit(Opcode::PushEmptyString, &[]);
4546            return;
4547        }
4548        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(text))]);
4549    }
4550
4551    /// Name an anonymous function from the binding it is assigned to.
4552    ///
4553    /// `var f = function(){}` produces a function whose `name` is `f`, which the
4554    /// runtime cannot know without being told: the function object is created
4555    /// before the store. `set_name` carries the name across.
4556    fn set_name_if_anonymous(&mut self, value: &Expr, name: &str) {
4557        if value.is_anonymous_function_definition() {
4558            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(name))]);
4559        }
4560    }
4561
4562    /// The same, for a computed key: the name comes from the value on the stack
4563    /// rather than from an atom, so a different instruction carries it.
4564    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
4565        if value.is_anonymous_function_definition() {
4566            self.emit(Opcode::SetNameComputed, &[]);
4567        }
4568    }
4569
4570    /// Compile a function body that exists only in the compiler's head — a class's
4571    /// implicit constructor or its field initialiser.
4572    ///
4573    /// Everything structural is the same as a written function: a fresh `FnState`, its
4574    /// own body block, and resolution while the frame is still on the stack. Only the
4575    /// statements differ.
4576    fn compile_synthetic_function(
4577        &mut self,
4578        name: &str,
4579        strict: bool,
4580        span: Span,
4581        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
4582    ) -> Result<CompiledFunction, SyntaxError> {
4583        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
4584        state.strict = strict;
4585        state.created_in_block = self.cur().current_block;
4586        state.with_names = self.cur().with_names.clone();
4587        state.line = span.start.line;
4588        state.column = span.start.column;
4589        let depth = self.stack.len();
4590        self.stack.push(state);
4591        let body_key = span.start.offset as u64;
4592        self.push_block(body_key, NO_PARENT);
4593        self.state().body_block = body_key;
4594        let result = (|| {
4595            self.emit_scope_enter(body_key);
4596            body(self)?;
4597            if self.end_is_reachable() {
4598                self.emit(Opcode::ReturnUndef, &[]);
4599            }
4600            Ok(())
4601        })();
4602        if result.is_err() {
4603            self.stack.truncate(depth);
4604            return result.map(|()| unreachable!());
4605        }
4606        Ok(self.finish_current())
4607    }
4608
4609    /// The implicit return of a class constructor.
4610    ///
4611    /// A constructor that falls off the end initialises its instance fields first, and a
4612    /// derived one returns `this` — which is what makes `new D()` the object `super()`
4613    /// built rather than `undefined`.
4614    fn emit_class_constructor_tail(&mut self) {
4615        match self.cur().ctor_kind {
4616            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
4617            CtorKind::Base => {
4618                if self.cur().has_instance_fields {
4619                    self.call_field_initialiser();
4620                }
4621                self.emit(Opcode::ReturnUndef, &[]);
4622            }
4623            CtorKind::Derived => {
4624                if self.cur().has_instance_fields {
4625                    self.call_field_initialiser();
4626                }
4627                // `get_loc_check` rather than `get_loc`: reaching the end without ever
4628                // running `super()` is a ReferenceError, not `undefined`.
4629                self.emit_var(VarAction::Get, "this");
4630                self.emit(Opcode::Return, &[]);
4631            }
4632        }
4633    }
4634
4635    /// `yield expr` / `yield* expr`.
4636    ///
4637    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
4638    /// it to the caller and parks the frame. On resume the stack holds the value the
4639    /// caller passed *and* a "magic" number saying which method resumed it — `next`
4640    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
4641    /// `if_false <continue>` asks whether this was an ordinary `next`:
4642    ///
4643    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
4644    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
4645    ///   and uses the value sitting under the magic number.
4646    ///
4647    /// A `throw` never reaches here: the interpreter unwinds instead (see
4648    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
4649    fn yield_expression(
4650        &mut self,
4651        argument: Option<&Expr>,
4652        delegate: bool,
4653    ) -> Result<(), SyntaxError> {
4654        if delegate {
4655            return self.yield_star(argument);
4656        }
4657        match argument {
4658            Some(value) => self.expr(value)?,
4659            None => self.emit(Opcode::Undefined, &[]),
4660        }
4661        self.emit(Opcode::Yield, &[]);
4662        let resume = self.new_label();
4663        self.emit_jump(Opcode::IfFalse, resume, &[]);
4664        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
4665        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
4666        // finished the generator and never ran the `finally`.
4667        self.emit_unwind_for_return(true);
4668        self.emit(Opcode::ReturnAsync, &[]);
4669        self.place_label(resume);
4670        // Nothing is emitted here: the value the caller passed to `next` *is* the value
4671        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
4672        // it through the ordinary expression-statement discard.
4673        Ok(())
4674    }
4675
4676    /// `yield* iterable`.
4677    ///
4678    /// The shape is the reference's, and it is a fall-through chain rather than a
4679    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
4680    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
4681    /// the inner iterator and finishes, `throw` forwards the exception into it and
4682    /// continues only if it has a `throw` method.
4683    ///
4684    /// The stack is `iter next catch value` throughout, `catch` being the offset
4685    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
4686    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
4687        match argument {
4688            Some(value) => self.expr(value)?,
4689            // The parser rejects a bare `yield*`, so this is unreachable in practice.
4690            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
4691        }
4692        // `for_of_start` validates the iterable and pushes the iterator triple, which is
4693        // the same protocol `for (… of …)` uses.
4694        self.emit(Opcode::ForOfStart, &[]);
4695        self.emit(Opcode::Drop, &[]);
4696        self.emit(Opcode::Undefined, &[]);
4697        self.emit(Opcode::Undefined, &[]);
4698        let next = self.new_label();
4699        let resume = self.new_label();
4700        let finished = self.new_label();
4701        let rethrow = self.new_label();
4702        let throw_no_method = self.new_label();
4703        let done = self.new_label();
4704        self.place_label(next);
4705        self.emit(Opcode::IteratorNext, &[]);
4706        self.emit(Opcode::IteratorCheckObject, &[]);
4707        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
4708        self.emit_jump(Opcode::IfTrue, done, &[]);
4709        // `yield_star` suspends with the inner result's value; `resume` is where the
4710        // caller's answer arrives, as the value followed by the magic number.
4711        self.place_label(resume);
4712        self.emit(Opcode::YieldStar, &[]);
4713        self.emit(Opcode::Dup, &[]);
4714        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
4715        self.emit(Opcode::Drop, &[]);
4716        self.emit_jump(Opcode::Goto, next, &[]);
4717
4718        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
4719        self.place_label(rethrow);
4720        self.emit(Opcode::PushI32, &[Op::Int(2)]);
4721        self.emit(Opcode::StrictEq, &[]);
4722        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
4723        // A `return` closes the inner iterator; if it had none, the delegate simply
4724        // finishes with the requested value.
4725        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
4726        self.emit_jump(Opcode::IfTrue, finished, &[]);
4727        self.emit(Opcode::IteratorCheckObject, &[]);
4728        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
4729        self.emit_jump(Opcode::IfFalse, resume, &[]);
4730        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
4731        self.place_label(finished);
4732        self.emit(Opcode::Nip, &[]);
4733        self.emit(Opcode::Nip, &[]);
4734        self.emit(Opcode::Nip, &[]);
4735        self.emit(Opcode::ReturnAsync, &[]);
4736
4737        // `throw(e)`: forward it into the inner iterator.
4738        self.place_label(throw_no_method);
4739        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
4740        let no_throw = self.new_label();
4741        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
4742        self.emit(Opcode::IteratorCheckObject, &[]);
4743        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
4744        self.emit_jump(Opcode::IfFalse, resume, &[]);
4745        self.emit_jump(Opcode::Goto, done, &[]);
4746        // No `throw` method: close the iterator, then report the spec's TypeError.
4747        self.place_label(no_throw);
4748        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
4749        self.emit(Opcode::Drop, &[]);
4750        self.emit(
4751            Opcode::ThrowError,
4752            &[Op::Atom(Atom::from_text("")), Op::Int(4)],
4753        );
4754
4755        // The inner iterator finished: the delegate's value is the `yield*` expression's
4756        // value, so it is left on the stack for whatever consumes it.
4757        self.place_label(done);
4758        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
4759        self.emit(Opcode::Nip, &[]);
4760        self.emit(Opcode::Nip, &[]);
4761        self.emit(Opcode::Nip, &[]);
4762        Ok(())
4763    }
4764
4765    /// `await expr`: exactly one instruction.
4766    ///
4767    /// No resume-magic branch follows it. The reference's `await` leaves a single value
4768    /// on the stack and completion is signalled by the `return_async` at the end of the
4769    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
4770    /// reference never emits, and a `for await` loop — which reaches `await` through the
4771    /// same opcode — would then spill a value the loop's unpacking does not expect.
4772    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
4773        self.expr(argument)?;
4774        self.emit(Opcode::Await, &[]);
4775        self.state().has_await = true;
4776        Ok(())
4777    }
4778
4779    /// The `super` base: the receiver followed by the home object's prototype.
4780    ///
4781    /// Everything `super` does needs both. A *read* starts at the prototype but reports
4782    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
4783    /// prototype but calls it with the receiver.
4784    fn super_base(&mut self) {
4785        self.this_expression();
4786        self.home_object();
4787        self.emit(Opcode::GetSuper, &[]);
4788    }
4789
4790    /// `[[HomeObject]]` as `super` sees it.
4791    ///
4792    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
4793    /// put it there — so for them the special object *is* the answer. An arrow and a
4794    /// static block have none: they read the enclosing function's, which has to be
4795    /// materialised into a local, exactly as `this` is for an arrow.
4796    ///
4797    /// The name matches what the reference stores, so the disassembly agrees; it is not a
4798    /// name any program can write.
4799    fn home_object(&mut self) {
4800        if !self.cur().is_arrow {
4801            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
4802            return;
4803        }
4804        if let Some(target) = self.enclosing_function() {
4805            self.state_at(target).needs_home_object_local = true;
4806            self.declare_at(target, HOME_OBJECT);
4807        }
4808        self.emit_var(VarAction::Get, HOME_OBJECT);
4809    }
4810
4811    /// `super(args)`: construct the parent class and adopt the result as `this`.
4812    ///
4813    /// The parent is the prototype of the constructor that is running, which is exactly
4814    /// what `extends` set up. `new.target` is passed through unchanged so that
4815    /// `new.target` inside the parent is the class actually being constructed.
4816    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4817        self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
4818        self.emit(Opcode::GetSuper, &[]);
4819        self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
4820        if Self::has_spread(arguments) {
4821            self.argument_array(arguments)?;
4822            self.emit(Opcode::Apply, &[Op::Int(1)]);
4823        } else {
4824            for argument in arguments {
4825                self.expr(argument)?;
4826            }
4827            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
4828        }
4829        // The value stays on the stack: `super()` is an expression, and a derived
4830        // constructor's `this` may only be initialised once.
4831        self.emit(Opcode::Dup, &[]);
4832        self.emit_var(VarAction::PutInitChecked, "this");
4833        Ok(())
4834    }
4835
4836    /// `this` as a local, which every class constructor and field initialiser needs.
4837    ///
4838    /// The reference materialises the receiver into a local rather than reading
4839    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
4840    /// and a field initialiser has to see the final value.
4841    fn begin_this_local(&mut self) {
4842        self.declare_hidden_local("this", VarKind::Normal);
4843        self.emit(Opcode::PushThis, &[]);
4844        self.emit_var(VarAction::Put, "this");
4845        // The store is already at the top of the body, so `provide_this_local` has
4846        // nothing left to prepend. Without this the initialiser ended up with
4847        // `push_this; put_loc0 this` twice whenever the class also held a field
4848        // initialiser whose body read `this` through an arrow.
4849        self.state().has_this_prologue = true;
4850    }
4851
4852    /// Compile a constructor the class wrote.
4853    ///
4854    /// The flags have to be in place before the body is compiled, but
4855    /// `compile_function_with_name` creates its own state — so the caller's state is
4856    /// marked instead and the new one inherits it. That is the same trick the parameter
4857    /// prologue uses, and it keeps one code path for both.
4858    fn compile_class_constructor(
4859        &mut self,
4860        func: &ast::Function,
4861        has_heritage: bool,
4862        has_instance_fields: bool,
4863    ) -> Result<CompiledFunction, SyntaxError> {
4864        let saved = (self.cur().ctor_kind, self.cur().has_instance_fields);
4865        self.state().class_ctor_pending = Some((
4866            if has_heritage {
4867                CtorKind::Derived
4868            } else {
4869                CtorKind::Base
4870            },
4871            has_instance_fields,
4872        ));
4873        let result = self.compile_function_with_name(func, false);
4874        self.state().ctor_kind = saved.0;
4875        self.state().has_instance_fields = saved.1;
4876        self.state().class_ctor_pending = None;
4877        result
4878    }
4879
4880    /// The constructor a class gets when it does not declare one.
4881    ///
4882    /// A base class's is empty; a derived class's forwards every argument to the parent
4883    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
4884    /// instance field initialiser afterwards when the class has fields, which is why the
4885    /// initialiser is captured rather than inlined.
4886    fn compile_implicit_constructor(
4887        &mut self,
4888        class: &Class,
4889        has_heritage: bool,
4890    ) -> Result<CompiledFunction, SyntaxError> {
4891        let has_fields = class.elements.iter().any(|element| {
4892            matches!(
4893                element,
4894                ClassElement::Field {
4895                    is_static: false,
4896                    ..
4897                }
4898            )
4899        });
4900        self.compile_synthetic_function(
4901            "",
4902            true,
4903            Span::new(class.body_end, class.body_end),
4904            |compiler| {
4905                if has_heritage {
4906                    // A derived constructor's `this` does not exist until `super()` returns,
4907                    // so it starts in the dead zone and `init_ctor` fills it.
4908                    compiler.declare("this", VarDef::lexical("this"));
4909                    compiler.emit(
4910                        Opcode::SetLocUninitialized,
4911                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
4912                    );
4913                    compiler.emit(Opcode::InitCtor, &[]);
4914                    compiler.emit(
4915                        Opcode::PutLocCheckInit,
4916                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
4917                    );
4918                } else {
4919                    compiler.begin_this_local();
4920                    compiler.emit(Opcode::CheckCtor, &[]);
4921                }
4922                if has_fields {
4923                    compiler.call_field_initialiser();
4924                }
4925                // A derived constructor returns `this`, the object `super()` built. Without
4926                // this the implicit constructor fell through to `return_undef`, and `new B()`
4927                // handed back the empty object `construct` had made instead of the one the
4928                // parent constructor initialised.
4929                if has_heritage {
4930                    compiler.emit_var(VarAction::Get, "this");
4931                    compiler.emit(Opcode::Return, &[]);
4932                }
4933                Ok(())
4934            },
4935        )
4936    }
4937
4938    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
4939    ///
4940    /// A class with no instance fields leaves the binding `undefined`, and calling it
4941    /// would throw; the reference emits the same guard rather than branching at compile
4942    /// time because a class can be extended by a subclass whose fields still have to run.
4943    fn call_field_initialiser(&mut self) {
4944        let skip = self.new_label();
4945        self.emit_var(VarAction::Get, "<class_fields_init>");
4946        self.emit(Opcode::Dup, &[]);
4947        self.emit_jump(Opcode::IfFalse, skip, &[]);
4948        self.emit_var(VarAction::Get, "this");
4949        self.emit(Opcode::Swap, &[]);
4950        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
4951        self.place_label(skip);
4952        self.emit(Opcode::Drop, &[]);
4953    }
4954
4955    /// The function that defines one class's fields on `this`, and runs its static blocks.
4956    ///
4957    /// `define_field` rather than `put_field`: a field is an own property created
4958    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
4959    /// `x = 1` field must not call the setter.
4960    ///
4961    /// One function serves the whole class: it is called once per instance (or once, for
4962    /// the static half) and walks the members in source order. Static blocks are compiled
4963    /// into the same function because they *are* part of the same sequence — `static a =
4964    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
4965    /// different values, so the two kinds cannot be split apart.
4966    fn compile_field_initialiser(
4967        &mut self,
4968        items: &[StaticInitItem<'_>],
4969        span: Span,
4970    ) -> Result<CompiledFunction, SyntaxError> {
4971        self.compile_synthetic_function("", true, span, |compiler| {
4972            compiler.begin_this_local();
4973            for item in items {
4974                match item {
4975                    StaticInitItem::Field(key, value) => {
4976                        compiler.emit_var(VarAction::Get, "this");
4977                        match value {
4978                            Some(value) => compiler.expr(value)?,
4979                            None => compiler.emit(Opcode::Undefined, &[]),
4980                        }
4981                        match key {
4982                            PropName::Literal(literal) => {
4983                                let text = compiler.property_key_text(literal, span)?;
4984                                compiler
4985                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_text(&text))]);
4986                            }
4987                            PropName::Computed(index) => {
4988                                compiler.expr(index)?;
4989                                compiler.emit(Opcode::DefineArrayEl, &[]);
4990                                compiler.emit(Opcode::Drop, &[]);
4991                            }
4992                            PropName::Private(_) => {
4993                                return Err(SyntaxError::new(
4994                                    "private class fields are not supported by the compiler yet",
4995                                    span,
4996                                ));
4997                            }
4998                        }
4999                        compiler.emit(Opcode::Drop, &[]);
5000                    }
5001                    StaticInitItem::Block { body, body_start } => {
5002                        let block = compiler.compile_static_block(body, *body_start)?;
5003                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5004                        // `this fclosure`, so `call_method` finds the receiver below the
5005                        // callee: the block runs with `this` bound to the class.
5006                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5007                        compiler.emit_var(VarAction::Get, "this");
5008                        compiler.emit(Opcode::Swap, &[]);
5009                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5010                        // Nothing the block evaluates is wanted; its effects are the point.
5011                        compiler.emit(Opcode::Drop, &[]);
5012                    }
5013                }
5014            }
5015            Ok(())
5016        })
5017    }
5018
5019    /// Compile a `static { … }` body into the function the class calls for it.
5020    ///
5021    /// Shaped like an arrow, because that is the one function form with no `this`,
5022    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5023    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5024    /// rejects the reference — but `this` and `super` both depend on it.
5025    ///
5026    /// The body is hoisted like a function body's, because the reference parses it as one:
5027    /// `var` inside a block is a local of the block's function, not of whatever encloses
5028    /// the class.
5029    fn compile_static_block(
5030        &mut self,
5031        body: &[Stmt],
5032        body_start: Position,
5033    ) -> Result<CompiledFunction, SyntaxError> {
5034        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5035        // Class bodies are strict, so a static block is too.
5036        state.strict = true;
5037        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5038        // so `this` and `super` come from the initialiser that calls it.
5039        state.is_arrow = true;
5040        state.created_in_block = self.cur().current_block;
5041        state.with_names = self.cur().with_names.clone();
5042        state.line = body_start.line;
5043        state.column = body_start.column;
5044        let depth = self.stack.len();
5045        self.stack.push(state);
5046        let body_key = body_start.offset as u64;
5047        self.push_block(body_key, NO_PARENT);
5048        self.state().body_block = body_key;
5049        let result = (|| {
5050            self.hoist(body, body_key)?;
5051            self.emit_scope_enter(body_key);
5052            for statement in body {
5053                self.stmt(statement)?;
5054            }
5055            if self.end_is_reachable() {
5056                self.emit(Opcode::ReturnUndef, &[]);
5057            }
5058            Ok(())
5059        })();
5060        if result.is_err() {
5061            self.stack.truncate(depth);
5062            return result.map(|()| unreachable!());
5063        }
5064        Ok(self.finish_current())
5065    }
5066
5067    /// Compile a class, leaving the constructor on the stack when `keep`.
5068    ///
5069    /// The shape follows the reference: the class body is its own scope holding the
5070    /// class's *inner* name as a `const` — which is what lets a method refer to the
5071    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5072    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5073    /// on the top of the stack: the prototype for instance members, the constructor
5074    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5075    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5076        let parent_block = self.cur().current_block;
5077        let key = class.span.start.offset as u64;
5078        self.push_block(key, parent_block);
5079        let name = class.name.as_ref().map(|ident| ident.name.clone());
5080        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5081        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5082        // binding, and `define_class` is handed the empty name.
5083        if let Some(name) = &name {
5084            self.declare(name, VarDef::constant(name.clone()));
5085        }
5086        // `let` rather than `const`: the binding starts in the dead zone and is filled
5087        // once the initialiser has been compiled, which a `const` would refuse as a second
5088        // store.
5089        self.declare(
5090            "<class_fields_init>",
5091            VarDef::lexical("<class_fields_init>"),
5092        );
5093        self.emit_scope_enter(key);
5094
5095        // The heritage clause is evaluated outside the class's own scope: it cannot see
5096        // the class binding it is about to initialise.
5097        let saved_block = self.cur().current_block;
5098        self.state().current_block = parent_block;
5099        match &class.super_class {
5100            Some(parent) => self.expr(parent)?,
5101            None => self.emit(Opcode::Undefined, &[]),
5102        }
5103        self.state().current_block = saved_block;
5104        let has_heritage = class.super_class.is_some();
5105
5106        // The constructor is compiled before `define_class` because that instruction
5107        // consumes it; a class without one gets the implicit version.
5108        let constructor = class.elements.iter().find_map(|element| match element {
5109            ClassElement::Method {
5110                kind: MethodKind::Constructor,
5111                func,
5112                ..
5113            } => Some(&**func),
5114            _ => None,
5115        });
5116        // A constructor is compiled differently from a method: it owns `this`. The flags
5117        // go on the *enclosing* state because a constructor is a nested function and
5118        // `compile_function_with_name` starts a fresh one.
5119        let has_instance_fields = class.elements.iter().any(|element| {
5120            matches!(
5121                element,
5122                ClassElement::Field {
5123                    is_static: false,
5124                    ..
5125                }
5126            )
5127        });
5128        let ctor = match constructor {
5129            Some(func) => {
5130                self.compile_class_constructor(func, has_heritage, has_instance_fields)?
5131            }
5132            None => self.compile_implicit_constructor(class, has_heritage)?,
5133        };
5134        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5135        // A closure, not the bare constant: the constructor captures
5136        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5137        // has to hold the cell rather than a copy of its value.
5138        self.emit(Opcode::Fclosure, &[Op::Const(ctor_index)]);
5139        let flags = if has_heritage { 1 } else { 0 };
5140        self.emit(
5141            Opcode::DefineClass,
5142            &[
5143                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5144                Op::Int(flags),
5145            ],
5146        );
5147
5148        // Instance fields and static fields are two different functions: the first runs
5149        // per instance from the constructor, the second runs once, here.
5150        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5151        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5152        for element in &class.elements {
5153            match element {
5154                ClassElement::Method {
5155                    key: member_key,
5156                    is_static,
5157                    kind,
5158                    func,
5159                    span,
5160                } => {
5161                    if *kind == MethodKind::Constructor {
5162                        continue;
5163                    }
5164                    // `static(x)` is a *method* named `static`, not a static method; the
5165                    // parser already decided which by putting it in `kind`.
5166                    if *is_static {
5167                        self.emit(Opcode::Swap, &[]);
5168                    }
5169                    let function = self.compile_function_with_name(func, true)?;
5170                    let index = self.push_constant(Constant::Function(Box::new(function)));
5171                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5172                    match member_key {
5173                        PropName::Computed(key) => {
5174                            self.emit(Opcode::Swap, &[]);
5175                            self.expr(key)?;
5176                            self.emit(
5177                                Opcode::DefineMethodComputed,
5178                                &[Op::Int(class_method_flags(*kind))],
5179                            );
5180                            // `define_method_computed` leaves the key; drop it.
5181                            self.emit(Opcode::Drop, &[]);
5182                        }
5183                        PropName::Literal(literal) => {
5184                            let text = self.property_key_text(literal, *span)?;
5185                            self.emit(
5186                                Opcode::DefineMethod,
5187                                &[
5188                                    Op::Atom(Atom::from_text(&text)),
5189                                    Op::Int(class_method_flags(*kind)),
5190                                ],
5191                            );
5192                        }
5193                        PropName::Private(_) => {
5194                            return Err(SyntaxError::new(
5195                                "private class members are not supported by the compiler yet",
5196                                *span,
5197                            ));
5198                        }
5199                    }
5200                    if *is_static {
5201                        self.emit(Opcode::Swap, &[]);
5202                    }
5203                }
5204                ClassElement::Field {
5205                    key: field_key,
5206                    is_static,
5207                    value,
5208                    span,
5209                } => {
5210                    if matches!(field_key, PropName::Private(_)) {
5211                        return Err(SyntaxError::new(
5212                            "private class fields are not supported by the compiler yet",
5213                            *span,
5214                        ));
5215                    }
5216                    if *is_static {
5217                        static_items.push(StaticInitItem::Field(field_key, value.as_deref()));
5218                    } else {
5219                        instance_fields.push(StaticInitItem::Field(field_key, value.as_deref()));
5220                    }
5221                }
5222                ClassElement::StaticBlock {
5223                    body, body_start, ..
5224                } => static_items.push(StaticInitItem::Block {
5225                    body,
5226                    body_start: *body_start,
5227                }),
5228            }
5229        }
5230
5231        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
5232        // class has no instance fields. The constructor calls it only when it is defined.
5233        if instance_fields.is_empty() {
5234            self.emit(Opcode::Undefined, &[]);
5235        } else {
5236            let initialiser = self.compile_field_initialiser(&instance_fields, class.span)?;
5237            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5238            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5239            // `set_home_object` reads `obj func`, so the prototype stays where it is.
5240            self.emit(Opcode::SetHomeObject, &[]);
5241        }
5242        self.emit_var(VarAction::PutInit, "<class_fields_init>");
5243        // The prototype has done its job: every instance member is defined on it. What
5244        // is left under it is the constructor.
5245        self.emit(Opcode::Drop, &[]);
5246
5247        // The class binding is initialised *before* static fields run, so a static field
5248        // can refer to the class by name (`static y = S.x`).
5249        // `set_loc` leaves the constructor on the stack, which is what the static field
5250        // call and the outer store both consume.
5251        //
5252        // Only when there *is* such a binding: an anonymous class expression declares no
5253        // class-scope name, and asking for one by the empty string resolved to nothing —
5254        // which made `var x = class {}` assign `undefined` and put a bogus global store in
5255        // the instruction stream.
5256        if let Some(name) = &name {
5257            self.emit_var(VarAction::SetInit, name);
5258        }
5259        if !static_items.is_empty() {
5260            let initialiser = self.compile_field_initialiser(&static_items, class.span)?;
5261            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5262            self.emit(Opcode::Dup, &[]);
5263            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5264            self.emit(Opcode::SetHomeObject, &[]);
5265            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5266            self.emit(Opcode::Drop, &[]);
5267        }
5268        self.emit_scope_leave(key);
5269        self.state().current_block = parent_block;
5270        if keep {
5271            // A class *expression* is its own value; the class-scope binding was only
5272            // ever an alias for it.
5273            return Ok(());
5274        }
5275        // A declaration stores into the binding the enclosing statement declared.
5276        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
5277        Ok(())
5278    }
5279
5280    fn push_this(&mut self) {
5281        self.emit(Opcode::PushThis, &[]);
5282    }
5283
5284    /// `this`, which an arrow does not have of its own.
5285    ///
5286    /// The reference gives the enclosing function a local named `this`, initialised from
5287    /// `push_this` at the top of its body, and the arrow then reads it as a captured
5288    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
5289    /// the arrow is called with none.
5290    fn this_expression(&mut self) {
5291        // In a class constructor `this` is a local: a derived constructor only gets one
5292        // when `super()` returns, and reading the raw receiver would give the *outer*
5293        // one instead.
5294        if self.cur().ctor_kind != CtorKind::None {
5295            self.emit_var(VarAction::Get, "this");
5296            return;
5297        }
5298        if !self.cur().is_arrow {
5299            self.push_this();
5300            return;
5301        }
5302        if let Some(target) = self.enclosing_function() {
5303            self.state_at(target).needs_this_local = true;
5304            self.declare_at(target, "this");
5305        }
5306        self.emit_var(VarAction::Get, "this");
5307    }
5308
5309    /// `new.target`, which an arrow likewise does not own.
5310    fn new_target_expression(&mut self) {
5311        if !self.cur().is_arrow {
5312            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
5313            return;
5314        }
5315        if let Some(target) = self.enclosing_function() {
5316            self.state_at(target).needs_new_target_local = true;
5317            self.declare_at(target, "new_target");
5318        }
5319        self.emit_var(VarAction::Get, "new_target");
5320    }
5321
5322    /// Give the function a local `new.target`, for an arrow inside it to capture.
5323    fn provide_new_target_local(&mut self) {
5324        let current = self.stack.len() - 1;
5325        if !self.stack[current].needs_new_target_local {
5326            return;
5327        }
5328        if !self.stack[current]
5329            .vars
5330            .iter()
5331            .any(|var| var.name == "new_target")
5332        {
5333            self.declare_hidden_local("new_target", VarKind::Normal);
5334        }
5335        self.prepend_initialiser(
5336            "new_target",
5337            Insn::Fixed {
5338                op: Opcode::SpecialObject,
5339                operands: vec![Op::Int(3)],
5340            },
5341        );
5342    }
5343
5344    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
5345    /// function.
5346    fn ensure_enclosing_arguments(&mut self) {
5347        // An arrow created in a parameter list needs the *parameter* scope's
5348        // `arguments`, not the body's: the two are separate bindings and the arrow was
5349        // born before the body existed.
5350        let from_params = self.cur().created_in_params;
5351        if let Some(target) = self.enclosing_function() {
5352            self.state_at(target).needs_arguments_local = true;
5353            if from_params {
5354                self.state_at(target).needs_param_arguments = true;
5355                // Declare it now, not at the enclosing function's `finish_current`: the
5356                // arrow resolves its own `arguments` before that runs, and a binding that
5357                // does not exist yet resolves as a global.
5358                declare_param_var_at(&mut self.stack[target], "arguments");
5359            }
5360            self.declare_at(target, "arguments");
5361        }
5362    }
5363
5364    /// The innermost enclosing frame that is a real function — an arrow inherits from it
5365    /// rather than starting a scope of its own.
5366    fn enclosing_function(&self) -> Option<usize> {
5367        (0..self.stack.len())
5368            .rev()
5369            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
5370    }
5371
5372    fn state_at(&mut self, index: usize) -> &mut FnState {
5373        &mut self.stack[index]
5374    }
5375
5376    /// Declare a `var` binding directly in a specific frame.
5377    fn declare_at(&mut self, index: usize, name: &str) {
5378        let state = &mut self.stack[index];
5379        if state.vars.iter().any(|var| var.name == name) {
5380            return;
5381        }
5382        state.var_block.push(FUNCTION_SCOPE);
5383        state.vars.push(VarDef::var(name));
5384    }
5385
5386    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
5387    /// the reference calls a `special_object` gets initialised on entry.
5388    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
5389        let current = self.stack.len() - 1;
5390        let init = [
5391            producer,
5392            Insn::Var {
5393                action: VarAction::Put,
5394                name: name.to_string(),
5395                block: 0,
5396                // A prologue initialiser runs before the body proper, but it is body
5397                // code: `this` and `arguments` are provided for it, not by it.
5398                in_params: false,
5399            },
5400        ];
5401        let inserted = init.len();
5402        for (index, instruction) in init.into_iter().enumerate() {
5403            self.stack[current].insns.insert(index, instruction);
5404        }
5405        for placed in self.stack[current].labels.iter_mut().flatten() {
5406            *placed += inserted;
5407        }
5408        self.stack[current].label_since_insn = true;
5409    }
5410
5411    fn push_constant(&mut self, constant: Constant) -> u32 {
5412        let state = self.state();
5413        let index = state.cpool.len() as u32;
5414        state.cpool.push(constant);
5415        index
5416    }
5417
5418    /// Compile `a && b`, `a || b`, `a ?? b`.
5419    ///
5420    /// A run of the *same* operator shares one end label, so `a || b || c` tests
5421    /// `a` once and jumps past everything when it is truthy, instead of falling
5422    /// into `b`'s test. The parser builds such a run left-associated —
5423    /// `((a || b) || c)` — so the operands are collected off the left spine.
5424    ///
5425    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
5426    /// `||`'s label, because the inner chain really does end before `&&` begins.
5427    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
5428        let mut operands = Vec::new();
5429        collect_same_operator(op, left, &mut operands);
5430        operands.push(right);
5431
5432        let end = self.new_label();
5433        // Every operand but the last decides whether the chain stops here.
5434        let last = operands.pop().expect("the right operand is always present");
5435        for operand in operands {
5436            self.expr(operand)?;
5437            self.emit(Opcode::Dup, &[]);
5438            match op {
5439                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
5440                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
5441                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
5442                // `0 || b` is `b`. The dedicated test keeps the value unless it is
5443                // null-ish, so the jump is taken on `false`.
5444                LogicalOp::Coalesce => {
5445                    self.emit(Opcode::IsUndefinedOrNull, &[]);
5446                    self.emit_jump(Opcode::IfFalse, end, &[]);
5447                }
5448            }
5449            self.emit(Opcode::Drop, &[]);
5450        }
5451        self.expr(last)?;
5452        self.place_label(end);
5453        Ok(())
5454    }
5455
5456    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
5457        match op {
5458            UnaryOp::Typeof => {
5459                // `typeof x` must not throw on an undeclared name.
5460                if let ExprKind::Ident(name) = &argument.kind {
5461                    self.emit_var(VarAction::GetUndef, &name.name);
5462                } else {
5463                    self.expr(argument)?;
5464                }
5465                self.emit(Opcode::Typeof, &[]);
5466            }
5467            UnaryOp::Delete => {
5468                // `delete obj.prop` really deletes, and answers whether it could.
5469                // Deleting a *binding* is always `false`: a local, an argument and a
5470                // declared global are all non-configurable, which the reference encodes
5471                // as a constant `push_false` rather than a runtime check. Only a
5472                // property access has anything to do at run time.
5473                // `delete super.x` is not a delete at all: the spec refuses it, and the
5474                // reference encodes the refusal as a `throw_error`. The receiver and the
5475                // key are still evaluated first, which is what keeps the evaluation order
5476                // of the operand intact.
5477                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
5478                // nothing to delete, and a failed delete is not the same as a skipped
5479                // one. The reference emits the guards so they land on a `drop; push_true`
5480                // tail, which is what this reproduces.
5481                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
5482                    && let ExprKind::Member {
5483                        object, property, ..
5484                    } = &inner.unparen().kind
5485                {
5486                    let end = self.new_label();
5487                    let done = self.new_label();
5488                    self.chain_link(object, end)?;
5489                    match property {
5490                        MemberProp::Ident(name) => self.emit(
5491                            Opcode::PushAtomValue,
5492                            &[Op::Atom(Atom::from_text(&name.name))],
5493                        ),
5494                        MemberProp::Computed(index) => self.expr(index)?,
5495                        MemberProp::Private(_) => {
5496                            return Err(SyntaxError::new(
5497                                "deleting a private field is not allowed",
5498                                argument.span,
5499                            ));
5500                        }
5501                    }
5502                    self.emit(Opcode::Delete, &[]);
5503                    self.emit_jump(Opcode::Goto, done, &[]);
5504                    self.place_label(end);
5505                    self.emit(Opcode::Drop, &[]);
5506                    self.emit(Opcode::PushTrue, &[]);
5507                    self.place_label(done);
5508                    return Ok(());
5509                }
5510                if let ExprKind::Member { object, .. } = &argument.unparen().kind
5511                    && matches!(object.unparen().kind, ExprKind::SuperProp)
5512                {
5513                    self.super_base();
5514                    self.emit(
5515                        Opcode::ThrowError,
5516                        &[Op::Atom(Atom::from_text("")), Op::Int(3)],
5517                    );
5518                    return Ok(());
5519                }
5520                match &argument.kind {
5521                    ExprKind::Member {
5522                        object, property, ..
5523                    } => {
5524                        self.expr(object)?;
5525                        match property {
5526                            MemberProp::Ident(name) => {
5527                                self.emit(
5528                                    Opcode::PushAtomValue,
5529                                    &[Op::Atom(Atom::from_text(&name.name))],
5530                                );
5531                            }
5532                            MemberProp::Computed(index) => self.expr(index)?,
5533                            MemberProp::Private(_) => {
5534                                return Err(SyntaxError::new(
5535                                    "deleting a private field is not allowed",
5536                                    argument.span,
5537                                ));
5538                            }
5539                        }
5540                        self.emit(Opcode::Delete, &[]);
5541                    }
5542                    ExprKind::Ident(name) => {
5543                        // `delete name`: a declared global, a local and an argument all
5544                        // answer `false`, but an *implicit* global (`x = 1` with no
5545                        // declaration) is a configurable property of the global object
5546                        // and really goes away. Which of those a name is only the
5547                        // resolver knows, so the decision waits for it.
5548                        let pos = self.cur().cur_pos;
5549                        self.state().insns.push(Insn::DeleteVar {
5550                            name: name.name.clone(),
5551                        });
5552                        self.state().insn_pos.push(pos);
5553                    }
5554                    _ => self.emit(Opcode::PushFalse, &[]),
5555                }
5556            }
5557            UnaryOp::Void => {
5558                self.expr(argument)?;
5559                self.emit(Opcode::Drop, &[]);
5560                self.emit(Opcode::Undefined, &[]);
5561            }
5562            UnaryOp::Minus => {
5563                self.expr(argument)?;
5564                self.emit(Opcode::Neg, &[]);
5565            }
5566            UnaryOp::Plus => {
5567                self.expr(argument)?;
5568                self.emit(Opcode::Plus, &[]);
5569            }
5570            UnaryOp::Not => {
5571                self.expr(argument)?;
5572                self.emit(Opcode::Lnot, &[]);
5573            }
5574            UnaryOp::BitNot => {
5575                self.expr(argument)?;
5576                self.emit(Opcode::Not, &[]);
5577            }
5578        }
5579        Ok(())
5580    }
5581
5582    /// Compile an assignment.
5583    ///
5584    /// Three operator families, three shapes:
5585    ///
5586    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
5587    ///   the value is kept, because `put_field`/`put_array_el` consume both the
5588    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
5589    ///   the pair it wants and leaves a copy on top.
5590    /// * **compound** `+=` … — read the place, apply the operator, store. A member
5591    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
5592    ///   index) underneath the value precisely so the store can follow.
5593    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
5594    ///   right-hand side. The test *keeps* the current value and skips the store
5595    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
5596    ///   `a` is already truthy.
5597    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
5598        // Reading the flag clears it: only the outermost assignment of an
5599        // expression statement may drop its value.
5600        let keep = !std::mem::take(&mut self.state().discard_value);
5601        match &target.kind {
5602            PatternKind::Ident(name) => {
5603                // A *simple* store is blamed on the identifier, not on the `=`: a
5604                // strict-mode `not_def = 1` raises when the name is written, which the
5605                // reference reports at the name's column. A compound store is blamed on
5606                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
5607                // which the reference reports at the `+=`), so only the simple case
5608                // moves the position.
5609                let saved = self.cur().cur_pos;
5610                let name_pos = Some(name.span.start);
5611                if matches!(op, AssignOp::Assign) {
5612                    self.state().cur_pos = name_pos;
5613                }
5614                // A *compound* store reads the binding before it combines, and that read
5615                // is blamed on the identifier: `not_def += 2` fails while reading
5616                // `not_def`, so the position is the name's, not the `+=`'s. The
5617                // combination that follows is blamed on the operator, which is why
5618                // `cur_pos` is put back to the operator position before it is emitted.
5619                self.state().cur_pos = name_pos;
5620                match op {
5621                    AssignOp::Assign => {
5622                        self.expr(value)?;
5623                        self.set_name_if_anonymous(value, &name.name);
5624                        // A discarded store to a *slot* consumes its value, so no copy
5625                        // is needed. A global store goes through `put_var`, which the
5626                        // reference always pairs with a `dup` — matching it keeps the
5627                        // bytecode identical. Getting this wrong is not only an extra
5628                        // instruction: a stray copy gives the peephole a chance to fold
5629                        // the store into an unrelated later read.
5630                        let slot = self.is_slot(&name.name);
5631                        if keep || !slot {
5632                            self.emit(Opcode::Dup, &[]);
5633                        }
5634                        self.state().no_value = !keep && slot;
5635                        self.emit_var(VarAction::Put, &name.name);
5636                    }
5637                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
5638                        let end = self.new_label();
5639                        self.emit_var(VarAction::Get, &name.name);
5640                        self.state().cur_pos = saved;
5641                        self.emit(Opcode::Dup, &[]);
5642                        self.emit_logical_test(op);
5643                        self.emit_jump(logical_jump(op), end, &[]);
5644                        self.emit(Opcode::Drop, &[]);
5645                        self.expr(value)?;
5646                        self.emit(Opcode::Dup, &[]);
5647                        self.emit_var(VarAction::Put, &name.name);
5648                        self.place_label(end);
5649                    }
5650                    _ => {
5651                        self.emit_var(VarAction::Get, &name.name);
5652                        self.expr(value)?;
5653                        self.state().cur_pos = saved;
5654                        self.emit(compound_opcode(op), &[]);
5655                        self.emit(Opcode::Dup, &[]);
5656                        self.emit_var(VarAction::Put, &name.name);
5657                    }
5658                }
5659                self.state().cur_pos = saved;
5660                Ok(())
5661            }
5662            PatternKind::Member(member) => {
5663                // `super.x = v` is not a store through a value: it starts at the home
5664                // object's prototype but writes to `this`, so it goes through
5665                // `put_super_value` rather than `put_field`. The receiver, prototype, key
5666                // and value are handed over together.
5667                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
5668                    return self.assign_super(member, op, value);
5669                }
5670                // A store is blamed on the selector punctuator (`.` or `[`), the same
5671                // token a load is blamed on — the reference records `put_field obj.a`
5672                // at the `.`, so a setter that throws reports that column and not the
5673                // `=` of the assignment it sits in. The inner expressions restore their
5674                // own positions, so the selector's sticks for the store instructions.
5675                let saved = self.cur().cur_pos;
5676                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
5677                self.expr(&member.object)?;
5678                match &member.property {
5679                    MemberProp::Ident(property) => {
5680                        let atom = Atom::from_text(&property.name);
5681                        match op {
5682                            AssignOp::Assign => {
5683                                self.expr(value)?;
5684                                // `put_field` consumes the object and the value, so
5685                                // without `insert2` nothing is left over for the
5686                                // statement to drop.
5687                                self.state().no_value = !keep;
5688                                if keep {
5689                                    self.emit(Opcode::Insert2, &[]);
5690                                }
5691                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
5692                            }
5693                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
5694                                // `get_field2` leaves the object under the value, so
5695                                // the keep path has an object to dispose of. The store
5696                                // path must jump *over* that cleanup: falling into it
5697                                // would `nip` a stack that only holds the value.
5698                                let (keep_label, end) = (self.new_label(), self.new_label());
5699                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
5700                                self.emit(Opcode::Dup, &[]);
5701                                self.emit_logical_test(op);
5702                                self.emit_jump(logical_jump(op), keep_label, &[]);
5703                                self.emit(Opcode::Drop, &[]);
5704                                self.expr(value)?;
5705                                self.emit(Opcode::Insert2, &[]);
5706                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
5707                                self.emit_jump(Opcode::Goto, end, &[]);
5708                                self.place_label(keep_label);
5709                                self.emit(Opcode::Nip, &[]);
5710                                self.place_label(end);
5711                            }
5712                            _ => {
5713                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
5714                                self.expr(value)?;
5715                                self.emit(compound_opcode(op), &[]);
5716                                self.state().no_value = !keep;
5717                                if keep {
5718                                    self.emit(Opcode::Insert2, &[]);
5719                                }
5720                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
5721                            }
5722                        }
5723                    }
5724                    MemberProp::Computed(index) => {
5725                        self.expr(index)?;
5726                        match op {
5727                            AssignOp::Assign => {
5728                                self.expr(value)?;
5729                                self.state().no_value = !keep;
5730                                if keep {
5731                                    self.emit(Opcode::Insert3, &[]);
5732                                }
5733                                self.emit(Opcode::PutArrayEl, &[]);
5734                            }
5735                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
5736                                let (keep_label, end) = (self.new_label(), self.new_label());
5737                                self.emit(Opcode::GetArrayEl3, &[]);
5738                                self.emit(Opcode::Dup, &[]);
5739                                self.emit_logical_test(op);
5740                                self.emit_jump(logical_jump(op), keep_label, &[]);
5741                                self.emit(Opcode::Drop, &[]);
5742                                self.expr(value)?;
5743                                self.emit(Opcode::Insert3, &[]);
5744                                self.emit(Opcode::PutArrayEl, &[]);
5745                                self.emit_jump(Opcode::Goto, end, &[]);
5746                                self.place_label(keep_label);
5747                                // Both the object and the index are left over.
5748                                self.emit(Opcode::Nip, &[]);
5749                                self.emit(Opcode::Nip, &[]);
5750                                self.place_label(end);
5751                            }
5752                            _ => {
5753                                self.emit(Opcode::GetArrayEl3, &[]);
5754                                self.expr(value)?;
5755                                self.emit(compound_opcode(op), &[]);
5756                                self.state().no_value = !keep;
5757                                if keep {
5758                                    self.emit(Opcode::Insert3, &[]);
5759                                }
5760                                self.emit(Opcode::PutArrayEl, &[]);
5761                            }
5762                        }
5763                    }
5764                    MemberProp::Private(_) => {
5765                        return Err(SyntaxError::new(
5766                            "private fields are not supported by the compiler yet",
5767                            member.span,
5768                        ));
5769                    }
5770                }
5771                self.state().cur_pos = saved;
5772                Ok(())
5773            }
5774            // A destructuring assignment: the right-hand side is the expression's own
5775            // value, so it is evaluated once and kept under the pattern's stores.
5776            PatternKind::Array { .. } | PatternKind::Object { .. } => {
5777                self.expr(value)?;
5778                if keep {
5779                    self.emit(Opcode::Dup, &[]);
5780                }
5781                self.destructure(target, None)?;
5782                self.state().no_value = !keep;
5783                Ok(())
5784            }
5785            _ => Err(SyntaxError::new(
5786                "this assignment target is not supported by the compiler yet",
5787                target.span,
5788            )),
5789        }
5790    }
5791
5792    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
5793    ///
5794    /// The stack has to carry four values — receiver, prototype, key, value — because
5795    /// `put_super_value` takes them together; the receiver is what makes a setter found on
5796    /// the prototype run with `this`, and the key has to survive until the store, which is
5797    /// why a compound form converts it to a property key once and `dup3`s rather than
5798    /// evaluating it twice.
5799    fn assign_super(
5800        &mut self,
5801        member: &MemberPattern,
5802        op: AssignOp,
5803        value: &Expr,
5804    ) -> Result<(), SyntaxError> {
5805        let saved = self.cur().cur_pos;
5806        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
5807        self.super_base();
5808        match &member.property {
5809            MemberProp::Ident(property) => self.emit(
5810                Opcode::PushAtomValue,
5811                &[Op::Atom(Atom::from_text(&property.name))],
5812            ),
5813            MemberProp::Computed(index) => self.expr(index)?,
5814            MemberProp::Private(_) => {
5815                return Err(SyntaxError::new(
5816                    "private fields are not supported by the compiler yet",
5817                    member.span,
5818                ));
5819            }
5820        }
5821        match op {
5822            AssignOp::Assign => {
5823                // The key is only converted once, by `put_super_value` itself, so a
5824                // computed key's `toString` runs exactly once.
5825                self.expr(value)?;
5826                self.emit(Opcode::Insert4, &[]);
5827                self.emit(Opcode::PutSuperValue, &[]);
5828            }
5829            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
5830                let (keep_label, end) = (self.new_label(), self.new_label());
5831                self.emit(Opcode::ToPropkey, &[]);
5832                self.emit(Opcode::Dup3, &[]);
5833                self.emit(Opcode::GetSuperValue, &[]);
5834                self.emit(Opcode::Dup, &[]);
5835                self.emit_logical_test(op);
5836                self.emit_jump(logical_jump(op), keep_label, &[]);
5837                self.emit(Opcode::Drop, &[]);
5838                self.expr(value)?;
5839                self.emit(Opcode::Insert4, &[]);
5840                self.emit(Opcode::PutSuperValue, &[]);
5841                self.emit_jump(Opcode::Goto, end, &[]);
5842                self.place_label(keep_label);
5843                // The prototype and the key are still under the value that was read.
5844                self.emit(Opcode::Nip, &[]);
5845                self.emit(Opcode::Nip, &[]);
5846                self.emit(Opcode::Nip, &[]);
5847                self.place_label(end);
5848            }
5849            _ => {
5850                self.emit(Opcode::ToPropkey, &[]);
5851                self.emit(Opcode::Dup3, &[]);
5852                self.emit(Opcode::GetSuperValue, &[]);
5853                self.expr(value)?;
5854                self.emit(compound_opcode(op), &[]);
5855                self.emit(Opcode::Insert4, &[]);
5856                self.emit(Opcode::PutSuperValue, &[]);
5857            }
5858        }
5859        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
5860        // is still on the stack when the store finishes, and the expression statement is
5861        // what disposes of it — the same arrangement as `put_field`, reached from the other
5862        // side: there the store consumes the value (`no_value`), here it leaves it
5863        // (`keep` already false, so nothing tells the statement otherwise).
5864        self.state().cur_pos = saved;
5865        Ok(())
5866    }
5867
5868    /// The test a logical assignment applies to the current value.
5869    ///
5870    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
5871    /// assign, while `0 ||= b` must not.
5872    fn emit_logical_test(&mut self, op: AssignOp) {
5873        if op == AssignOp::Coalesce {
5874            self.emit(Opcode::IsUndefinedOrNull, &[]);
5875        }
5876    }
5877
5878    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
5879        let instruction = match (op, prefix) {
5880            (UpdateOp::Increment, true) => Opcode::Inc,
5881            (UpdateOp::Increment, false) => Opcode::PostInc,
5882            (UpdateOp::Decrement, true) => Opcode::Dec,
5883            (UpdateOp::Decrement, false) => Opcode::PostDec,
5884        };
5885        if let ExprKind::Member {
5886            object,
5887            property,
5888            optional: _,
5889        } = &argument.kind
5890        {
5891            // `o.x++` needs the receiver twice, so the last link is read with the
5892            // `get_*2`/`get_*3` form that keeps it, and the update is written back
5893            // with `put_field`/`put_array_el`. The reordering in between is what puts
5894            // the old value below the receiver for a postfix update and the new one
5895            // above it for a prefix one:
5896            //
5897            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
5898            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
5899            //
5900            // This mirrors the reference instruction for instruction.
5901            self.expr(object)?;
5902            match property {
5903                MemberProp::Ident(name) => {
5904                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5905                    self.emit(instruction, &[]);
5906                    self.emit(
5907                        if prefix {
5908                            Opcode::Insert2
5909                        } else {
5910                            Opcode::Perm3
5911                        },
5912                        &[],
5913                    );
5914                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
5915                }
5916                MemberProp::Computed(index) => {
5917                    self.expr(index)?;
5918                    self.emit(Opcode::GetArrayEl3, &[]);
5919                    self.emit(instruction, &[]);
5920                    self.emit(
5921                        if prefix {
5922                            Opcode::Insert3
5923                        } else {
5924                            Opcode::Perm4
5925                        },
5926                        &[],
5927                    );
5928                    self.emit(Opcode::PutArrayEl, &[]);
5929                }
5930                MemberProp::Private(_) => {
5931                    return Err(SyntaxError::new(
5932                        "private fields are not supported by the compiler yet",
5933                        argument.span,
5934                    ));
5935                }
5936            }
5937            return Ok(());
5938        }
5939        let ExprKind::Ident(name) = &argument.kind else {
5940            return Err(SyntaxError::new(
5941                "increment of a non-variable is not supported by the compiler yet",
5942                argument.span,
5943            ));
5944        };
5945        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
5946        // reference's `inc_loc` folds those three into one, but it does so only in some
5947        // positions (a `for` update and not a bare statement, and never for a lexical
5948        // binding), so emitting it unconditionally would move *away* from its output.
5949        // The instruction is equivalent either way; matching the reference matters more
5950        // than saving two instructions.
5951        let _ = !std::mem::take(&mut self.state().discard_value);
5952        self.emit_var(VarAction::Get, &name.name);
5953        self.emit(instruction, &[]);
5954        if prefix {
5955            self.emit(Opcode::Dup, &[]);
5956        }
5957        self.emit_var(VarAction::Put, &name.name);
5958        Ok(())
5959    }
5960
5961    /// Compile an array literal.
5962    ///
5963    /// The reference splits this into three phases, and the split is load-bearing
5964    /// rather than an optimisation detail:
5965    ///
5966    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
5967    ///    the array in one instruction.
5968    /// 2. **Everything up to the first spread** is appended with explicit indices
5969    ///    (`define_field <index>`), because a hole has no element to pass to
5970    ///    `array_from`. A hole here is what makes `length` need fixing up: an
5971    ///    explicit index does not extend the array the way a pushed element does.
5972    /// 3. **From the first spread on** the index lives on the stack, so `append` and
5973    ///    `define_array_el` can consume it and `inc` advances it.
5974    ///
5975    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
5976    /// forces phase 2, and `[...a]` forces phase 3.
5977    fn array_literal(
5978        &mut self,
5979        elements: &[Option<ArrayElement>],
5980        span: Span,
5981    ) -> Result<(), SyntaxError> {
5982        let _ = span;
5983        let mut index: u32 = 0;
5984        let mut cursor = 0usize;
5985
5986        // Phase 1: a leading run of plain elements, at most 32 of them.
5987        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
5988            if index >= 32 {
5989                break;
5990            }
5991            self.expr(element)?;
5992            index += 1;
5993            cursor += 1;
5994        }
5995        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
5996
5997        // Phase 2: explicit indices, up to the first spread.
5998        let mut need_length = false;
5999        while let Some(element) = elements.get(cursor) {
6000            if matches!(element, Some(ArrayElement::Spread(_))) {
6001                break;
6002            }
6003            need_length = true;
6004            if let Some(ArrayElement::Expr(expression)) = element {
6005                self.expr(expression)?;
6006                self.emit_define_index(index);
6007                need_length = false;
6008            }
6009            index += 1;
6010            cursor += 1;
6011        }
6012
6013        if cursor >= elements.len() {
6014            if need_length {
6015                // `define_field` cannot set `length`, which is not configurable.
6016                self.emit(Opcode::Dup, &[]);
6017                self.push_number(index as f64);
6018                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6019            }
6020            return Ok(());
6021        }
6022
6023        // Phase 3: the index moves onto the stack for the spreading tail.
6024        //
6025        // `need_length` deliberately carries over from phase 2: a hole before the
6026        // first spread still has to be reflected in `length`, and only the final
6027        // check can do it because the array is not finished until the tail is
6028        // appended.
6029        self.push_number(index as f64);
6030        while let Some(element) = elements.get(cursor) {
6031            match element {
6032                Some(ArrayElement::Spread(expression)) => {
6033                    // `append` copies an iterable and leaves the next index behind,
6034                    // so no `inc` is needed here.
6035                    self.expr(spread_argument(expression))?;
6036                    self.emit(Opcode::Append, &[]);
6037                }
6038                None | Some(ArrayElement::Expr(_)) => {
6039                    need_length = true;
6040                    if let Some(ArrayElement::Expr(expression)) = element {
6041                        self.expr(expression)?;
6042                        self.emit(Opcode::DefineArrayEl, &[]);
6043                        need_length = false;
6044                    }
6045                    self.emit(Opcode::Inc, &[]);
6046                }
6047            }
6048            cursor += 1;
6049        }
6050        if need_length {
6051            self.emit(Opcode::Dup1, &[]);
6052            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6053        } else {
6054            self.emit(Opcode::Drop, &[]);
6055        }
6056        Ok(())
6057    }
6058
6059    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
6060    fn emit_define_index(&mut self, index: u32) {
6061        self.emit(
6062            Opcode::DefineField,
6063            &[Op::Atom(Atom::from_text(&index.to_string()))],
6064        );
6065    }
6066
6067    // -- functions ---------------------------------------------------------
6068
6069    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
6070        self.compile_function_with_name(func, false)
6071    }
6072
6073    /// Compile a function, recording whether it is a *named function expression*.
6074    ///
6075    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
6076    /// must not leak outside. The reference does that by declaring `g` as a local of
6077    /// the function itself and initialising it with `special_object 2` (the current
6078    /// function), which is why this has to be known at compile time.
6079    fn compile_function_with_name(
6080        &mut self,
6081        func: &ast::Function,
6082        is_expression: bool,
6083    ) -> Result<CompiledFunction, SyntaxError> {
6084        let kind = match (func.is_generator, func.is_async) {
6085            (false, false) => FunctionKind::Normal,
6086            (true, false) => FunctionKind::Generator,
6087            (false, true) => FunctionKind::Async,
6088            (true, true) => FunctionKind::AsyncGenerator,
6089        };
6090        let mut state = FnState::new(
6091            func.name
6092                .as_ref()
6093                .map(|n| n.name.clone())
6094                .unwrap_or_default(),
6095            kind,
6096        );
6097        // The function's own mode, recorded by the parser. Inheriting the enclosing
6098        // function's instead let a nested `"use strict"` directive be ignored, so the
6099        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
6100        state.strict = func.strict;
6101        // A function defined inside a `with` block keeps seeing that object: the guard
6102        // chain names the enclosing `<with>` locals, which resolve outward into closure
6103        // variables exactly like any other captured binding.
6104        state.with_names = self.cur().with_names.clone();
6105        state.is_arrow = func.is_arrow;
6106        state.created_in_block = self.cur().current_block;
6107        // A default anywhere in the parameter list is what gives the function two
6108        // variable environments. The reference decides this the same way: it scans the
6109        // parenthesis for a top-level `=`, so a destructured name without a default
6110        // stays a plain function-scope binding.
6111        state.in_params = false;
6112        state.has_parameter_expressions = func
6113            .params
6114            .iter()
6115            .any(|param| matches!(param.kind, PatternKind::Assign { .. }));
6116        // A function born inside a parameter list inherits the prohibition: it must not
6117        // see the body bindings of the function it was created in.
6118        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
6119        // A class constructor knows what it is only because the class told it.
6120        if let Some((kind, has_fields)) = self.cur().class_ctor_pending {
6121            state.ctor_kind = kind;
6122            state.has_instance_fields = has_fields;
6123        }
6124        // A named *expression* binds its own name; a declaration's name is already
6125        // bound in the enclosing scope.
6126        state.self_name = if is_expression && !func.is_arrow {
6127            func.name.as_ref().map(|n| n.name.clone())
6128        } else {
6129            None
6130        };
6131        state.line = func.span.start.line;
6132        state.column = func.span.start.column;
6133        // A function body has no hidden `<ret>` local; the value comes back on
6134        // the stack. Only a script keeps one.
6135        // Parameters are positional, so even a pattern occupies one argument slot. A
6136        // simple name is that slot itself; anything else (a pattern, a default, a rest
6137        // parameter) takes an anonymous slot and is unpicked into locals at the top of
6138        // the body, which is the only way one argument can bind several names.
6139        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
6140        // `.length` stops at the first parameter that can be substituted: a default
6141        // fills a missing argument in, and a rest parameter absorbs the rest.
6142        let mut defined_args = func.params.len() as u32;
6143        for (index, param) in func.params.iter().enumerate() {
6144            match &param.kind {
6145                PatternKind::Ident(name) => state.args.push(VarDef::var(name.name.clone())),
6146                _ => {
6147                    state.args.push(VarDef::var("<null>"));
6148                    prologue.push((index, param.clone()));
6149                }
6150            }
6151        }
6152        // A default anywhere before the end also ends the count, which the loop above
6153        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
6154        for (position, param) in func.params.iter().enumerate() {
6155            if matches!(
6156                param.kind,
6157                PatternKind::Assign { .. } | PatternKind::Rest(_)
6158            ) {
6159                defined_args = position as u32;
6160                break;
6161            }
6162        }
6163        state.defined_args = defined_args;
6164        state.param_prologue = prologue;
6165        let depth = self.stack.len();
6166        self.stack.push(state);
6167        let result = self.compile_function_body(func);
6168        if result.is_err() {
6169            // A failed compile must not leave its `FnState` behind. Every caller
6170            // reads `self.state()` as "the function being compiled", so a leftover
6171            // frame silently retargets all later bookkeeping at a dead function.
6172            self.stack.truncate(depth);
6173        }
6174        result
6175    }
6176
6177    /// The body of a function, with its frame already pushed.
6178    fn compile_function_body(
6179        &mut self,
6180        func: &ast::Function,
6181    ) -> Result<CompiledFunction, SyntaxError> {
6182        let body_key = func.params_span.end.offset as u64;
6183        // Where the body begins, in source order. The runtime needs this to tell a
6184        // closure created by a default expression from one the body creates — the two see
6185        // different variable environments — and a bytecode offset would not survive the
6186        // instruction shuffling that building the frame does. Positions are in source
6187        // order, so a comparison answers it.
6188        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
6189        self.push_block(body_key, NO_PARENT);
6190        self.state().body_block = body_key;
6191        // An arrow with an expression body has no statements; the expression is
6192        // its `return`. Building the statement here keeps one code path below, and
6193        // matters for correctness beyond convenience: returning early with the new
6194        // `FnState` still on the stack would leave the compiler looking at the
6195        // wrong function, which surfaces as an unrelated underflow later.
6196        let concise = match &func.body {
6197            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
6198                StmtKind::Return(Some(Box::new((**value).clone()))),
6199                value.span,
6200            )),
6201            js_parse::ast::FunctionBody::Block(_) => None,
6202        };
6203        let body: &[Stmt] = match &concise {
6204            Some(stmt) => std::slice::from_ref(stmt),
6205            None => func
6206                .body
6207                .statements()
6208                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
6209        };
6210        // A pattern parameter binds its names as function-scope locals, so they have to
6211        // exist — and be unpicked from the argument — before the body runs.
6212        let prologue = std::mem::take(&mut self.state().param_prologue);
6213        for (_, pattern) in &prologue {
6214            let mut names = Vec::new();
6215            pattern.bound_names(&mut names);
6216            for name in names {
6217                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
6218            }
6219        }
6220        // With parameter expressions, every parameter also gets a binding in the
6221        // parameter scope, which is what the defaults and any closure created among them
6222        // resolve against. A simple parameter needs both: the argument slot for the body
6223        // and the parameter binding for the list.
6224        let has_param_scope = self.cur().has_parameter_expressions;
6225        if has_param_scope {
6226            for param in &func.params {
6227                let mut names = Vec::new();
6228                param.bound_names(&mut names);
6229                for name in names {
6230                    self.declare_param_var(&name.name.clone());
6231                }
6232            }
6233        }
6234        self.hoist(body, body_key)?;
6235        // A generator starts suspended: `initial_yield` is its first instruction, so
6236        // creating one runs no body code until the first `next()`.
6237        //
6238        // An async function does **not** get one. Its body runs synchronously up to the
6239        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
6240        // before its caller's next statement — so emitting `initial_yield` here would
6241        // park the body before it started, which is not fixable at run time: the
6242        // suspension looks exactly like a real `await`. The reference's disassembly
6243        // confirms the difference (a generator's first opcode is `initial_yield`, an
6244        // async function's is its first statement).
6245        if self.cur().kind.is_generator() {
6246            self.emit(Opcode::InitialYield, &[]);
6247        }
6248        self.emit_scope_enter(body_key);
6249        // A constructor's prologue is not a parameter unpacking but the `this` binding:
6250        // a base constructor takes the receiver, a derived one starts in the dead zone
6251        // because only `super()` may produce it.
6252        match self.cur().ctor_kind {
6253            CtorKind::None => {}
6254            CtorKind::Base => {
6255                self.begin_this_local();
6256                self.emit(Opcode::CheckCtor, &[]);
6257            }
6258            CtorKind::Derived => {
6259                self.declare("this", VarDef::lexical("this"));
6260                let slot = self.cur().vars.len() as u32 - 1;
6261                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
6262                self.emit(Opcode::CheckCtor, &[]);
6263            }
6264        }
6265        // The whole parameter list is one scope, and nothing in the body exists yet, so
6266        // every name it mentions resolves against the parameter bindings and outward.
6267        self.state().in_params = has_param_scope;
6268        for (index, param) in func.params.iter().enumerate() {
6269            if let Some((_, pattern)) = prologue.iter().find(|(at, _)| *at == index) {
6270                match &pattern.kind {
6271                    // `...rest` collects what is left rather than reading one slot.
6272                    PatternKind::Rest(inner) => {
6273                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
6274                        self.destructure(inner, Some(VarDeclKind::Var))?;
6275                    }
6276                    _ => {
6277                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
6278                        self.destructure(pattern, Some(VarDeclKind::Var))?;
6279                    }
6280                }
6281            }
6282            if !has_param_scope {
6283                continue;
6284            }
6285            // Mirror the value into the parameter scope. For a plain parameter that is
6286            // a copy of its argument slot; for a pattern, one copy per name it bound.
6287            let mut names = Vec::new();
6288            param.bound_names(&mut names);
6289            for name in names {
6290                let Some(var) = self.cur().vars.iter().enumerate().position(|(index, var)| {
6291                    var.name == name.name
6292                        && self.cur().var_block.get(index).copied() == Some(FUNCTION_SCOPE)
6293                }) else {
6294                    continue;
6295                };
6296                let target = self.declare_param_var(&name.name);
6297                self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(var as u32))]);
6298                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(target))]);
6299            }
6300        }
6301        // The parameter list is over; from here on a direct `eval` belongs to the body.
6302        self.state().in_params = false;
6303        // Through `stmts`: the body is a block, and a `using` declaration in it is a
6304        // disposal region.
6305        self.stmts(body)?;
6306        // The implicit return only exists if control can actually get here: an
6307        // infinite loop never falls off the end.
6308        if self.end_is_reachable() {
6309            if self.cur().is_suspending() {
6310                // Falling off the end finishes the generator with `undefined`, and the
6311                // value is what tells the resume machinery "completed" rather than
6312                // "suspended".
6313                self.emit(Opcode::Undefined, &[]);
6314                self.emit(Opcode::ReturnAsync, &[]);
6315            } else {
6316                self.emit_class_constructor_tail();
6317            }
6318        }
6319        // Resolution runs while this function is still on the stack: capturing a
6320        // variable from an enclosing function means reaching into that
6321        // function's state, which requires the whole chain to be present.
6322        Ok(self.finish_current())
6323    }
6324
6325    /// Put every binding of a function that contains a direct `eval` into a cell.
6326    ///
6327    /// A direct eval can name any binding in scope, and any closure it creates has to
6328    /// keep sharing that binding after the function returns — `for (let i …)
6329    /// eval("push(() => i)")` collects one closure per iteration and each must read its
6330    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
6331    /// a cell. Doing this unconditionally for such functions is the cheap, honest
6332    /// answer: the alternative is knowing at compile time which names a string will
6333    /// mention.
6334    fn capture_everything_for_eval(&mut self) {
6335        let current = self.stack.len() - 1;
6336        if !self.stack[current].has_direct_eval {
6337            return;
6338        }
6339        for arg in &mut self.stack[current].args {
6340            arg.is_captured = true;
6341        }
6342        for var in &mut self.stack[current].vars {
6343            var.is_captured = true;
6344        }
6345    }
6346
6347    /// Whether the current position in the instruction stream can be reached.
6348    ///
6349    /// A walk over the control-flow graph, using labels as instruction indices.
6350    /// The reference does the same thing to decide whether an implicit
6351    /// `return_undef` is needed.
6352    fn end_is_reachable(&self) -> bool {
6353        let state = self.cur();
6354        reachable_instructions(state, state.insns.len())[state.insns.len()]
6355    }
6356
6357    /// Resolve and assemble the function on top of the compiler stack, then pop
6358    /// it.
6359    fn finish_current(&mut self) -> CompiledFunction {
6360        self.provide_param_arguments();
6361        self.provide_arguments();
6362        self.provide_this_local();
6363        self.provide_new_target_local();
6364        self.provide_home_object_local();
6365        self.provide_self_name();
6366        self.materialize_eval_sites();
6367        self.capture_everything_for_eval();
6368        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
6369        // Captured bindings need a reference cell; the count goes in the header so
6370        // the runtime knows how many cells to allocate on entry.
6371        let current = self.stack.len() - 1;
6372        let captured = self.stack[current]
6373            .args
6374            .iter()
6375            .filter(|a| a.is_captured)
6376            .count()
6377            + self.stack[current]
6378                .vars
6379                .iter()
6380                .filter(|v| v.is_captured)
6381                .count();
6382        self.stack[current].var_ref_count = captured as u32;
6383        // The scope chain is only final now that every binding is known.
6384        rebuild_scope_chain(&mut self.stack[current]);
6385        let (code, stack_size, positions) =
6386            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
6387        let _ = &mut resolved;
6388        let mut state = self.stack.pop().expect("a function is being compiled");
6389        CompiledFunction {
6390            name: state.name,
6391            kind: state.kind,
6392            strict: state.strict,
6393            is_arrow: state.is_arrow,
6394            has_parameter_expressions: state.has_parameter_expressions,
6395            body_start: state.body_start,
6396            args: state.args,
6397            defined_args: state.defined_args,
6398            vars: state.vars,
6399            closure_vars: state.closure_vars,
6400            cpool: state.cpool,
6401            atoms: state.atoms,
6402            code,
6403            stack_size,
6404            var_ref_count: state.var_ref_count,
6405            positions,
6406            source: None,
6407            line: state.line,
6408            column: state.column,
6409            filename: None,
6410            eval_sites: state.eval_sites,
6411            module: state.module.take().map(Box::new),
6412        }
6413    }
6414}
6415
6416/// Assign each binding a scope level and rebuild the scope chains.
6417///
6418/// Levels are numbered in the order the blocks appear, with 0 reserved for the
6419/// function scope where `var` and hoisted functions live. Every binding outside
6420/// level 0 gets a `scope_next` link to the next binding visible from the same
6421/// point, so walking a block's chain enumerates exactly the bindings live there.
6422///
6423/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
6424/// point at `b`, which is declared later in the source but earlier in the chain.
6425fn rebuild_scope_chain(state: &mut FnState) {
6426    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
6427    // real block that happens to start at offset zero keeps its own level instead of
6428    // being merged into the function scope.
6429    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
6430    for block in &state.blocks {
6431        if !levels.contains(&block.key) {
6432            levels.push(block.key);
6433        }
6434    }
6435    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
6436    let parent_level = |level: usize| -> usize {
6437        if level == 0 {
6438            return 0;
6439        }
6440        let key = levels[level];
6441        let parent = state
6442            .blocks
6443            .iter()
6444            .find(|b| b.key == key)
6445            .map(|b| b.parent)
6446            .unwrap_or(FUNCTION_SCOPE);
6447        level_of(parent)
6448    };
6449
6450    // Own bindings per level, in declaration order.
6451    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
6452    let keys: Vec<u64> = (0..state.vars.len())
6453        .map(|index| {
6454            state
6455                .var_block
6456                .get(index)
6457                .copied()
6458                .unwrap_or(FUNCTION_SCOPE)
6459        })
6460        .collect();
6461    for (index, key) in keys.into_iter().enumerate() {
6462        let level = level_of(key);
6463        state.vars[index].scope_level = level as u32;
6464        // A `catch` parameter is part of the runtime scope chain even though it is
6465        // not lexical: the handler's own bindings chain on to it, which is why the
6466        // reference prints `let y [next:1]` with `e` at 1.
6467        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
6468        {
6469            own[level].push(index);
6470        }
6471    }
6472
6473    // A scope's chain is its own bindings in reverse declaration order followed
6474    // by the enclosing scope's chain.
6475    let mut head = vec![-1i32; levels.len()];
6476    for level in 0..levels.len() {
6477        let inherited = if level == 0 {
6478            -1
6479        } else {
6480            head[parent_level(level)]
6481        };
6482        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
6483        head[level] = chain.first().map_or(inherited, |first| *first as i32);
6484        for (position, &index) in chain.iter().enumerate() {
6485            let next = chain
6486                .get(position + 1)
6487                .map_or(inherited, |next| *next as i32);
6488            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
6489        }
6490    }
6491    state.block_heads = head;
6492}
6493
6494/// This is where names become slots and where the temporal dead zone shows up in
6495/// the instruction stream: a read of a `let`/`const` binding compiles to
6496/// `get_loc_check`, which throws if the binding is still uninitialised.
6497///
6498/// The peephole pass from the reference implementation is applied at the end,
6499/// for the same reason it is applied to resolved bytecode there: the patterns are
6500/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
6501/// resolution. Deleted instructions stay in the list as `None` so that label
6502/// indices remain valid; [`Assembler`] maps them to byte offsets.
6503/// A resolved instruction and the source position it came from.
6504type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
6505
6506/// A resolved instruction paired with its position, which is what `assemble` consumes.
6507type PositionedInsn = (Opcode, Vec<Op>);
6508
6509fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
6510    let current = stack.len() - 1;
6511    // Dead-code elimination, on the symbolic form where labels are still
6512    // instruction indices. A `break` inside a loop leaves the trailing `goto`
6513    // unreachable, and a `return` leaves everything after it unreachable; the
6514    // reference drops both. Doing it here means the emitter never has to think
6515    // about reachability.
6516    strip_empty_gosubs(stack, current);
6517    eliminate_dead_code(stack, current);
6518    let insns = std::mem::take(&mut stack[current].insns);
6519    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
6520    // `insns`, and every arm below pushes exactly one instruction, so the positions
6521    // stay aligned with `out`.
6522    let positions = std::mem::take(&mut stack[current].insn_pos);
6523    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
6524    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
6525    for (index, insn) in insns.iter().enumerate() {
6526        let pos = positions.get(index).copied().flatten();
6527        out_pos.push(pos);
6528        match insn {
6529            Insn::Fixed { op, operands } => {
6530                let operands = operands
6531                    .iter()
6532                    .map(|operand| match operand {
6533                        Op::Atom(atom) => {
6534                            Op::AtomId(intern_atom(&mut stack[current], &atom.to_string()))
6535                        }
6536                        other => other.clone(),
6537                    })
6538                    .collect();
6539                out.push(Some((*op, operands)));
6540            }
6541            Insn::Var {
6542                action,
6543                name,
6544                block,
6545                in_params,
6546            } => {
6547                // Only a *read* prefers the parameter scope. A store in the parameter
6548                // list is binding its parameter or assigning inside a default; either
6549                // way it has to reach the slot the body reads, and the mirror into the
6550                // parameter scope is emitted separately (see `compile_function_body`).
6551                let reads = matches!(action, VarAction::Get | VarAction::GetUndef);
6552                let slot = resolve_slot(stack, current, name, *block, *in_params && reads);
6553                // A store to the name of a named function expression is special: the
6554                // reference drops it in sloppy mode and throws in strict mode, because
6555                // the binding is immutable but only *checked* when the body is strict.
6556                // The same rule applies when the name is reached through a closure:
6557                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
6558                // the store in the arrow too, not just in the function that owns the
6559                // binding. Reaching the owner means walking the chain of closure
6560                // entries, which is what `self_name_binding` does.
6561                let self_name = matches!(action, VarAction::Put | VarAction::Set)
6562                    .then(|| {
6563                        // A local of this function is the common case and needs no
6564                        // chain walk; only an access that resolves elsewhere can be
6565                        // pointing at an enclosing function's name binding.
6566                        if let Slot::Loc(index) = slot {
6567                            stack[current]
6568                                .vars
6569                                .get(index as usize)
6570                                .filter(|var| var.kind == VarKind::FunctionName)
6571                                .map(|var| var.is_const)
6572                        } else {
6573                            self_name_binding(stack, current, name, *block)
6574                        }
6575                    })
6576                    .flatten();
6577                if let Some(is_const) = self_name {
6578                    out.push(Some(if is_const {
6579                        (
6580                            Opcode::ThrowError,
6581                            vec![
6582                                Op::AtomId(intern_atom(&mut stack[current], name)),
6583                                Op::Int(0),
6584                            ],
6585                        )
6586                    } else {
6587                        (Opcode::Drop, Vec::new())
6588                    }));
6589                    continue;
6590                }
6591                out.push(Some(variable_instruction(stack, current, *action, slot)));
6592            }
6593            Insn::CloseCaptured { name, block } => {
6594                // The block matters: a loop variable is scoped to the `for` head's own
6595                // block, so resolving it against block 0 would miss it entirely and
6596                // silently emit nothing.
6597                let slot = resolve_slot(stack, current, name, *block, false);
6598                // Only a local with a reference cell has anything to close. A global
6599                // or a never-captured local resolves to no instruction at all, which
6600                // keeps the bytecode identical to the reference's.
6601                if let Slot::Loc(index) = slot
6602                    && stack[current]
6603                        .vars
6604                        .get(index as usize)
6605                        .is_some_and(|v| v.is_captured)
6606                {
6607                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
6608                } else {
6609                    out.push(None);
6610                }
6611            }
6612            Insn::DeleteVar { name } => {
6613                // A binding — a local, an argument, or a declared global — cannot be
6614                // deleted, and the reference encodes that as a constant `push_false`.
6615                // Only an implicit global needs the runtime lookup.
6616                if matches!(
6617                    resolve_slot(stack, current, name, 0, false),
6618                    Slot::Global(_)
6619                ) {
6620                    let atom = intern_atom(&mut stack[current], name);
6621                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
6622                } else {
6623                    out.push(Some((Opcode::PushFalse, Vec::new())));
6624                }
6625            }
6626            Insn::Dead => out.push(None),
6627        }
6628    }
6629    // Which label (if any) sits on each instruction, so the jump patterns can
6630    // tell whether they would cross a jump target.
6631    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
6632    for (id, placed) in stack[current].labels.iter().enumerate() {
6633        if let Some(index) = *placed
6634            && index < label_at.len()
6635            && label_at[index].is_none()
6636        {
6637            label_at[index] = Some(id as u32);
6638        }
6639    }
6640    if std::env::var_os("QJS_DEBUG").is_some() {
6641        eprintln!("--- peephole entry ---");
6642        for (i, e) in out.iter().enumerate() {
6643            eprintln!("{i}: {e:?}");
6644        }
6645        eprintln!("label_at: {label_at:?}");
6646    }
6647    peephole(&mut out, &label_at, &stack[current].labels);
6648    (out, out_pos)
6649}
6650
6651/// Find where `name` lives, capturing it in an enclosing function when needed.
6652///
6653/// The search runs outward through the enclosing functions' states, which are
6654/// still on the compiler stack while a nested function is resolved. Finding the
6655/// name in an enclosing function is what creates a closure reference, and every
6656/// function in between has to forward it — a function can only reach its own
6657/// parent's frame.
6658///
6659/// A name declared nowhere is a global. The reference does *not* look it up by
6660/// name from the inner function: the top-level function gets one `[global]`
6661/// entry and every nested function gets a `[global_ref<n>]` pointing at its
6662/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
6663/// rather than `[global]`.
6664/// The lexical blocks enclosing `block`, innermost first.
6665fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
6666    let mut chain = Vec::new();
6667    let mut current = Some(block);
6668    while let Some(key) = current {
6669        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
6670        // explicitly (rather than on "no block with this key") is what keeps a block
6671        // that happens to sit at offset zero from being mistaken for the terminator.
6672        if key == NO_PARENT || chain.contains(&key) {
6673            break;
6674        }
6675        chain.push(key);
6676        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
6677    }
6678    chain
6679}
6680
6681/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
6682///
6683/// The binding may be several functions away: an arrow nested in `function myfunc`
6684/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
6685/// means following `Ref` entries down and then reading the owning function's var table.
6686fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
6687    let state = stack.get(current)?;
6688    // A parameter shadows everything and is never a function-expression name.
6689    if state.args.iter().any(|arg| arg.name == name) {
6690        return None;
6691    }
6692    // A local of this very function: the answer is in its var table.
6693    if let Some(index) = local_slot_index(state, name, block) {
6694        let var = state.vars.get(index)?;
6695        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
6696    }
6697    // Otherwise the name lives further out, and the closure entry says how to get
6698    // there. `Local` names the owner's slot directly; `Ref` names the next level's
6699    // closure entry, so the walk continues downwards.
6700    let mut level = current;
6701    let mut index = state
6702        .closure_vars
6703        .iter()
6704        .position(|closure| closure.name == name)?;
6705    loop {
6706        let state = stack.get(level)?;
6707        let closure = state.closure_vars.get(index)?;
6708        match closure.closure_type {
6709            ClosureType::Local => {
6710                let owner = stack.get(level.checked_sub(1)?)?;
6711                let var = owner.vars.get(closure.var_idx as usize)?;
6712                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
6713            }
6714            ClosureType::Arg => return None,
6715            ClosureType::Ref => {
6716                level -= 1;
6717                index = closure.var_idx as usize;
6718            }
6719            // A global is never a function-expression name.
6720            ClosureType::Global
6721            | ClosureType::GlobalDecl
6722            | ClosureType::GlobalRef
6723            | ClosureType::ModuleDecl
6724            | ClosureType::ModuleImport => return None,
6725        }
6726    }
6727}
6728
6729/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
6730fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
6731    block_chain(state, block).into_iter().find_map(|scope| {
6732        state.vars.iter().enumerate().find_map(|(index, var)| {
6733            (var.name == name && state.var_block.get(index).copied() == Some(scope))
6734                .then_some(index)
6735        })
6736    })
6737}
6738
6739/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
6740fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
6741    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
6742        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
6743    }) {
6744        return index as u32;
6745    }
6746    state.var_block.push(PARAM_SCOPE);
6747    state.vars.push(VarDef::var(name));
6748    state.vars.len() as u32 - 1
6749}
6750
6751/// Whether a function-scope binding is visible to the parameter list.
6752///
6753/// The parameter list runs before the body, so the body's `var`s and function
6754/// declarations do not exist yet — a name that only the body declares has to resolve
6755/// outward instead. What *does* exist by then is the compiler's own prologue: the
6756/// self-name of a named function expression (bound by `special_object 2` before anything
6757/// else), `this` and `new.target`. Those stay visible, which is what makes
6758/// `function f(a = this)` and `var f = function f(a = f)` work.
6759///
6760/// `arguments` is handled separately, as a binding of the parameter scope itself: with
6761/// parameter expressions the reference creates two of them, and the one the parameter
6762/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
6763fn visible_in_params(var: &VarDef) -> bool {
6764    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
6765}
6766
6767fn resolve_slot(
6768    stack: &mut [FnState],
6769    current: usize,
6770    name: &str,
6771    block: u64,
6772    in_params: bool,
6773) -> Slot {
6774    // The parameter list's own bindings. They are consulted first because they shadow
6775    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
6776    // `a` in the parameter scope, so a closure made there reads the parameter even after
6777    // the body assigns to its own `a`.
6778    if in_params
6779        && let Some(index) = stack[current]
6780            .vars
6781            .iter()
6782            .enumerate()
6783            .position(|(index, var)| {
6784                var.name == name
6785                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
6786            })
6787    {
6788        return Slot::Loc(index as u32);
6789    }
6790    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
6791        return Slot::Arg(index as u32);
6792    }
6793    // A name can be bound more than once: two `catch` parameters in nested
6794    // handlers are two slots. The binding that wins is the one whose scope encloses
6795    // the access, and among those the innermost — so the blocks are walked outward
6796    // and the first binding found on the way is the one that counts. A binding in
6797    // no block (`var`) is reachable from anywhere, which is why the function scope
6798    // is the end of the walk.
6799    let chain = block_chain(&stack[current], block);
6800    for scope in &chain {
6801        let found = stack[current]
6802            .vars
6803            .iter()
6804            .enumerate()
6805            .find(|(index, var)| {
6806                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
6807            })
6808            .map(|(index, _)| index);
6809        if let Some(index) = found {
6810            return Slot::Loc(index as u32);
6811        }
6812    }
6813    // Function-scope bindings — `var` and function declarations — are recorded with
6814    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
6815    // them. They are reachable from anywhere in the function, which is exactly what
6816    // the sentinel means.
6817    //
6818    // This pass is *only* for those. A lexical binding has to be found through the
6819    // chain or not at all, and looking a name up without its block is precisely how
6820    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
6821    // block leaked out of it.
6822    let function_scoped = stack[current]
6823        .vars
6824        .iter()
6825        .enumerate()
6826        .find(|(index, var)| {
6827            var.name == name
6828                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
6829                && (!in_params || visible_in_params(var))
6830        })
6831        .map(|(index, _)| index);
6832    if let Some(index) = function_scoped {
6833        return Slot::Loc(index as u32);
6834    }
6835    if let Some(index) = stack[current]
6836        .closure_vars
6837        .iter()
6838        .position(|c| c.name == name)
6839    {
6840        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
6841    }
6842
6843    for owner in (0..current).rev() {
6844        // The nested function was created inside one of this frame's blocks, and the
6845        // outermost visible binding is the innermost block on that chain — not whatever
6846        // comes first in the variable table. `function f(){ class S{} }` has two `S`
6847        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
6848        // the class body is the one a method may see.
6849        let entry = stack
6850            .get(owner + 1)
6851            .map(|s| s.created_in_block)
6852            .unwrap_or(0);
6853        let lexical = block_chain(&stack[owner], entry)
6854            .into_iter()
6855            .find_map(|scope| {
6856                stack[owner]
6857                    .vars
6858                    .iter()
6859                    .enumerate()
6860                    .find(|(index, var)| {
6861                        var.name == name
6862                            && stack[owner].var_block.get(*index).copied() == Some(scope)
6863                    })
6864                    .map(|(index, _)| index)
6865            });
6866        // A function born in a parameter list sees that list's bindings, not the body's:
6867        // the parameter scope is the environment it was created in.
6868        let in_param_scope = stack
6869            .get(owner + 1)
6870            .is_some_and(|child| child.created_in_params)
6871            .then(|| {
6872                stack[owner]
6873                    .vars
6874                    .iter()
6875                    .enumerate()
6876                    .position(|(index, var)| {
6877                        var.name == name
6878                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
6879                    })
6880            })
6881            .flatten();
6882        let found = if let Some(index) = in_param_scope {
6883            let var = &stack[owner].vars[index];
6884            Some(Found::Local(
6885                ClosureType::Local,
6886                index as u32,
6887                var.is_const,
6888                var.is_lexical,
6889            ))
6890        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
6891            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
6892        } else if let Some(index) = lexical {
6893            let var = &stack[owner].vars[index];
6894            Some(Found::Local(
6895                ClosureType::Local,
6896                index as u32,
6897                var.is_const,
6898                var.is_lexical,
6899            ))
6900        } else if let Some(index) = stack[owner]
6901            .vars
6902            .iter()
6903            .enumerate()
6904            .find_map(|(index, var)| {
6905                // A function created inside a parameter list must not see the body of the
6906                // function it was born in; see [`FnState::created_in_params`].
6907                let hidden = stack
6908                    .get(owner + 1)
6909                    .is_some_and(|child| child.created_in_params);
6910                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
6911            })
6912        {
6913            let var = &stack[owner].vars[index];
6914            Some(Found::Local(
6915                ClosureType::Local,
6916                index as u32,
6917                var.is_const,
6918                var.is_lexical,
6919            ))
6920        } else if stack[owner].self_name.as_deref() == Some(name) {
6921            // A named function expression's own name. The reference declares it here,
6922            // on the first lookup that fails, rather than up front — and that is what
6923            // makes it reachable from a *nested* function: the nested lookup is what
6924            // walks out and creates the binding. A direct reference in the body is
6925            // caught the same way, which is why `provide_self_name` only has to add
6926            // the prologue.
6927            let strict = stack[owner].strict;
6928            stack[owner].var_block.push(FUNCTION_SCOPE);
6929            stack[owner].vars.push(VarDef {
6930                kind: VarKind::FunctionName,
6931                // In strict mode the name is immutable, so a store raises; sloppy
6932                // mode drops the store instead (see `variable_instruction`).
6933                is_const: strict,
6934                ..VarDef::var(name)
6935            });
6936            let index = stack[owner].vars.len() as u32 - 1;
6937            Some(Found::Local(ClosureType::Local, index, strict, false))
6938        } else if let Some(index) = stack[owner]
6939            .closure_vars
6940            .iter()
6941            .position(|c| c.name == name)
6942        {
6943            let closure = &stack[owner].closure_vars[index];
6944            Some(match closure.closure_type {
6945                // `GlobalRef` belongs here too: it is a *global* reached through this
6946                // frame's reference table, so treating it as a `Ref` to a local cell makes
6947                // the reader look for a cell no frame ever fills. That is how a second
6948                // function using `eval` in its parameter list read `undefined` after a
6949                // sibling had already made `eval` a closure entry.
6950                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
6951                    Found::Global(index as u32)
6952                }
6953                // A module variable is a cell in the *module's* environment, which is
6954                // the module body's parent as far as a nested function is concerned — so
6955                // it is captured as a plain reference, not looked up as a global.
6956                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
6957                    ClosureType::Ref,
6958                    index as u32,
6959                    closure.is_const,
6960                    closure.is_lexical,
6961                ),
6962                _ => Found::Local(
6963                    ClosureType::Ref,
6964                    index as u32,
6965                    closure.is_const,
6966                    closure.is_lexical,
6967                ),
6968            })
6969        } else {
6970            None
6971        };
6972        let Some(found) = found else { continue };
6973
6974        let (is_const, is_lexical) = match found {
6975            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
6976            Found::Global(_) => (false, false),
6977        };
6978        // Mark the owner's binding as captured so it moves into a reference cell.
6979        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
6980            let slot = match found {
6981                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
6982                _ => &mut stack[owner].vars[index as usize],
6983            };
6984            slot.is_captured = true;
6985        }
6986        // Forward the reference through every function in between.
6987        let mut previous = match found {
6988            Found::Local(kind, index, _, _) => (kind, index),
6989            Found::Global(index) => (ClosureType::Global, index),
6990        };
6991        for level in owner + 1..=current {
6992            let kind = match (previous.0, level) {
6993                // A global stays a global at *every* level. Without `GlobalRef` in
6994                // this arm the second nested function over the same global got a
6995                // `Ref` to a cell no frame ever held, so the innermost closure read
6996                // `undefined` — which is how a two-deep getter lost its outer
6997                // variable.
6998                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
6999                    ClosureType::GlobalRef
7000                }
7001                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
7002                _ => ClosureType::Ref,
7003            };
7004            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
7005            previous = (kind, index);
7006        }
7007        let index = previous.1;
7008        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
7009    }
7010
7011    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
7012    // creating a property. The top-level function holds the entry.
7013    let mut previous = (
7014        ClosureType::Global,
7015        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
7016    );
7017    for level in 1..=current {
7018        let index = ensure_closure(
7019            stack,
7020            level,
7021            name,
7022            false,
7023            false,
7024            ClosureType::GlobalRef,
7025            previous.1,
7026        );
7027        previous = (ClosureType::GlobalRef, index);
7028    }
7029    Slot::Global(previous.1)
7030}
7031
7032/// What an outward search turned up.
7033#[derive(Debug, Clone, Copy)]
7034enum Found {
7035    /// A binding in an enclosing function, reachable through a closure of this
7036    /// type, with its const/lexical flags.
7037    Local(ClosureType, u32, bool, bool),
7038    /// A global, reached through the enclosing function's closure entry.
7039    Global(u32),
7040}
7041
7042/// Add a closure entry to `level` if it is not there yet.
7043fn ensure_closure(
7044    stack: &mut [FnState],
7045    level: usize,
7046    name: &str,
7047    is_const: bool,
7048    is_lexical: bool,
7049    closure_type: ClosureType,
7050    var_idx: u32,
7051) -> u32 {
7052    if let Some(index) = stack[level]
7053        .closure_vars
7054        .iter()
7055        .position(|c| c.name == name)
7056    {
7057        return index as u32;
7058    }
7059    stack[level].closure_vars.push(ClosureVar {
7060        name: name.to_string(),
7061        is_const,
7062        is_lexical,
7063        closure_type,
7064        var_idx: var_idx as u16,
7065    });
7066    stack[level].closure_vars.len() as u32 - 1
7067}
7068
7069fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
7070    match closure.closure_type {
7071        // A `global_ref` only says *how* the binding is found (through the
7072        // parent's closure table); the access itself is an ordinary global one.
7073        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
7074        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
7075        // A module variable is a real cell in the module's environment, so it is reached
7076        // exactly like a captured local — the host, not the global object, is what fills
7077        // the slot.
7078        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
7079        _ => Slot::VarRef(index),
7080    }
7081}
7082
7083/// Pick the opcode for one variable access.
7084///
7085/// The `_check` variants are what enforce the temporal dead zone. They are used
7086/// for every access to a `let`/`const` binding except its own initialisation —
7087/// which is exactly the operation that takes the binding out of the dead zone.
7088fn variable_instruction(
7089    stack: &[FnState],
7090    current: usize,
7091    action: VarAction,
7092    slot: Slot,
7093) -> (Opcode, Vec<Op>) {
7094    let lexical = match slot {
7095        Slot::Loc(index) => stack[current]
7096            .vars
7097            .get(index as usize)
7098            .is_some_and(|v| v.needs_check()),
7099        Slot::VarRef(index) => stack[current]
7100            .closure_vars
7101            .get(index as usize)
7102            .is_some_and(|c| c.is_lexical),
7103        _ => false,
7104    };
7105    let operand = vec![Op::Slot(slot)];
7106    match (action, slot) {
7107        (VarAction::Get, Slot::Loc(index)) => (
7108            if lexical {
7109                Opcode::GetLocCheck
7110            } else {
7111                Opcode::GetLoc
7112            },
7113            vec![Op::Slot(Slot::Loc(index))],
7114        ),
7115        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
7116        (VarAction::Get, Slot::VarRef(index)) => (
7117            if lexical {
7118                Opcode::GetVarRefCheck
7119            } else {
7120                Opcode::GetVarRef
7121            },
7122            vec![Op::Slot(Slot::VarRef(index))],
7123        ),
7124        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
7125        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
7126        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
7127        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
7128        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
7129        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
7130            (Opcode::GetVarUndef, operand)
7131        }
7132
7133        (VarAction::Put, Slot::Loc(_)) => (
7134            if lexical {
7135                Opcode::PutLocCheck
7136            } else {
7137                Opcode::PutLoc
7138            },
7139            operand,
7140        ),
7141        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
7142        (VarAction::Put, Slot::VarRef(_)) => (
7143            if lexical {
7144                Opcode::PutVarRefCheck
7145            } else {
7146                Opcode::PutVarRef
7147            },
7148            operand,
7149        ),
7150        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
7151        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
7152        // Initialisation is what ends the dead zone, so it never checks.
7153        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
7154        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
7155        // `this` in a derived constructor is always a local, so these cannot happen;
7156        // routing them to the ordinary forms keeps the match total without inventing
7157        // opcodes the reference does not have.
7158        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
7159        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
7160        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
7161            (Opcode::PutVarInit, operand)
7162        }
7163        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
7164        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
7165        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
7166            (Opcode::PutVarInit, operand)
7167        }
7168        (VarAction::Set, Slot::Loc(_)) => (
7169            if lexical {
7170                Opcode::SetLocCheck
7171            } else {
7172                Opcode::SetLoc
7173            },
7174            operand,
7175        ),
7176        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
7177        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
7178        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
7179        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
7180        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
7181        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
7182        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
7183        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
7184        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
7185        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
7186        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
7187        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
7188    }
7189}
7190
7191/// The instruction-rewriting pass.
7192///
7193/// These are the reference implementation's patterns, restricted to the ones the
7194/// constructs this compiler supports can produce. Each entry is a comment on the
7195/// bytecode it removes, because the whole point is that the result is one
7196/// instruction shorter than the literal translation of the AST.
7197fn peephole(
7198    insns: &mut [Option<(Opcode, Vec<Op>)>],
7199    label_at: &[Option<u32>],
7200    placed: &[Option<usize>],
7201) {
7202    fold_dup_patterns(insns, label_at);
7203
7204    // `drop` before `return_undef` is dead: the return discards the whole frame
7205    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
7206    // consumes its own `drop`; removing the drop first would leave the `dup` and
7207    // produce a `set_` where the reference has a `put_`.
7208    for index in 0..insns.len() {
7209        if opcode_at(insns, index) != Some(Opcode::Drop) {
7210            continue;
7211        }
7212        // Skip over a run of drops, but stop at a jump target: removing code on
7213        // one side of a label would silently retarget the jump.
7214        let mut next = index + 1;
7215        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
7216            next += 1;
7217        }
7218        if is_label_at(label_at, next) {
7219            continue;
7220        }
7221        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
7222            for entry in &mut insns[index..next] {
7223                *entry = None;
7224            }
7225        }
7226    }
7227
7228    // The rewrites below all decide against one fixed snapshot, which is what the
7229    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
7230    // the pass, so a rule never observes what an earlier rule removed. Gathering
7231    // every deletion first and applying them together reproduces that.
7232    let snapshot: Vec<Option<Opcode>> = insns
7233        .iter()
7234        .map(|entry| entry.as_ref().map(|(op, _)| *op))
7235        .collect();
7236    // The next instruction that is still there. Holes left by dead-code
7237    // elimination are not instructions, so a rule looks past them.
7238    let next_op = |index: usize| -> Option<usize> {
7239        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
7240    };
7241
7242    let mut doomed = vec![false; insns.len()];
7243    for index in 0..insns.len() {
7244        // A constant pushed only to be dropped does nothing at all. This is what a
7245        // comma expression with a literal left operand compiles to — `(0, f)()` — and
7246        // the reference removes the pair rather than making the reader step over it.
7247        let constant = matches!(
7248            snapshot[index],
7249            Some(
7250                Opcode::Undefined
7251                    | Opcode::Null
7252                    | Opcode::PushMinus1
7253                    | Opcode::Push0
7254                    | Opcode::Push1
7255                    | Opcode::Push2
7256                    | Opcode::Push3
7257                    | Opcode::Push4
7258                    | Opcode::Push5
7259                    | Opcode::Push6
7260                    | Opcode::Push7
7261                    | Opcode::PushTrue
7262                    | Opcode::PushFalse
7263                    | Opcode::PushI32
7264            )
7265        );
7266        if constant
7267            && let Some(next) = next_op(index)
7268            && snapshot[next] == Some(Opcode::Drop)
7269        {
7270            doomed[index] = true;
7271            doomed[next] = true;
7272        }
7273    }
7274    for (index, entry) in insns.iter_mut().enumerate() {
7275        if doomed[index] {
7276            *entry = None;
7277        }
7278    }
7279
7280    // A conditional whose destination is the very next instruction just pops its
7281    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
7282    // compiles to.
7283    //
7284    // Order matters, and it is the reference's order: this runs *before* the
7285    // folding below, on the instruction the conditional originally had. Folding
7286    // moves a conditional's destination, and the reference never re-examines it
7287    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
7288    // a conditional even though folding leaves it pointing at the next
7289    // instruction.
7290    for (index, entry) in insns.iter_mut().enumerate() {
7291        let Some((op, operands)) = entry.clone() else {
7292            continue;
7293        };
7294        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
7295            continue;
7296        }
7297        let Some(id) = label_id(&operands) else {
7298            continue;
7299        };
7300        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
7301            *entry = Some((Opcode::Drop, Vec::new()));
7302        }
7303    }
7304
7305    // A constant condition is decided here rather than at run time.
7306    fold_constant_conditions(insns);
7307    // The conditional folding below is about pairs of *real* branches, so it runs
7308    // before a jump to the next instruction is dropped: `do { … if (c) continue }
7309    // while (t)` puts `continue` exactly on the condition, and the reference inverts
7310    // the branch first and only then notices the jump goes nowhere.
7311    fold_conditional_jumps(insns, label_at, placed);
7312
7313    // A jump whose destination is the very next instruction does nothing, which is
7314    // what constant folding leaves behind for `while (1) { … }`.
7315    remove_jump_to_next(insns, placed);
7316
7317    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
7318    // a use of the same variable boils down to.
7319    for index in 0..insns.len() {
7320        let Some((put_op, _)) = insns[index].clone() else {
7321            continue;
7322        };
7323        if !is_foldable_put(put_op) {
7324            continue;
7325        }
7326        if is_label_at(label_at, index + 1) {
7327            continue;
7328        }
7329        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
7330            continue;
7331        };
7332        if get_op != get_form_of(put_op) {
7333            continue;
7334        }
7335        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
7336        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
7337            continue;
7338        }
7339        insns[index] = Some((set_form_of(put_op), get_operands));
7340        insns[index + 1] = None;
7341    }
7342}
7343
7344/// Drop `gosub`s that call an empty subroutine.
7345///
7346/// A `gosub` whose target starts with `ret` returns immediately, so the reference
7347/// drops the call. This is how `try`/`catch` without a `finally` loses its
7348/// finalizer plumbing: the finalizer block is empty, its first instruction is
7349/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
7350/// [`eliminate_dead_code`] then removes.
7351fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
7352    let state = &stack[current];
7353    let mut targets = Vec::new();
7354    for insn in &state.insns {
7355        if let Insn::Fixed { op, operands } = insn
7356            && *op == Opcode::Gosub
7357            && let Some(id) = label_id(operands)
7358            && let Some(target) = state.labels.get(id as usize).copied().flatten()
7359        {
7360            targets.push(target);
7361        }
7362    }
7363    let empty: Vec<usize> = targets
7364        .into_iter()
7365        .filter(|target| {
7366            stack[current]
7367                .insns
7368                .get(*target)
7369                .map(|insn| {
7370                    matches!(
7371                        insn,
7372                        Insn::Fixed {
7373                            op: Opcode::Ret,
7374                            ..
7375                        }
7376                    )
7377                })
7378                .unwrap_or(false)
7379        })
7380        .collect();
7381    if empty.is_empty() {
7382        return;
7383    }
7384    for insn in stack[current].insns.iter_mut() {
7385        if let Insn::Fixed { op, operands } = insn
7386            && *op == Opcode::Gosub
7387            && let Some(id) = label_id(operands)
7388            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
7389            && empty.contains(&target)
7390        {
7391            *insn = Insn::Dead;
7392        }
7393    }
7394}
7395
7396/// Replace unreachable instructions with [`Insn::Dead`].
7397fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
7398    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
7399    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
7400        if !reachable[index] {
7401            *insn = Insn::Dead;
7402        }
7403    }
7404}
7405
7406/// Mark every instruction index reachable from the entry, plus the index one past
7407/// the last instruction.
7408///
7409/// `seen[len]` answers "can control reach the end of this function", and the
7410/// entries before it identify dead code. Both DCE and the implicit-return decision
7411/// read the same result, which keeps them from disagreeing.
7412fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
7413    let mut seen = vec![false; count + 1];
7414    let mut worklist = vec![0usize];
7415    while let Some(index) = worklist.pop() {
7416        if index > count || seen[index] {
7417            continue;
7418        }
7419        seen[index] = true;
7420        if index == count {
7421            continue;
7422        }
7423        let (op, operands) = match &state.insns[index] {
7424            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
7425            // A variable access never transfers control, and a removed
7426            // instruction is only reachable if it is already marked.
7427            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
7428                worklist.push(index + 1);
7429                continue;
7430            }
7431        };
7432        match op {
7433            // A return, a throw and a `ret` all leave this instruction stream: the
7434            // first two give control to the caller or the handler, and `ret`
7435            // returns to a `gosub` elsewhere.
7436            // A tail call leaves the function too: the callee's result becomes this
7437            // function's result, so nothing after it runs.
7438            Opcode::Return
7439            | Opcode::ReturnUndef
7440            | Opcode::TailCall
7441            | Opcode::TailCallMethod
7442            | Opcode::Throw
7443            | Opcode::ThrowError
7444            | Opcode::Ret => {}
7445            // A `catch` records where exceptions from the code that follows go.
7446            // That code is not reachable through normal control flow, but it is
7447            // reachable — through the exception edge — so the walk has to follow
7448            // it, or dead-code elimination would delete every handler.
7449            Opcode::Catch => {
7450                if let Some(target) = placed_label(state, operands) {
7451                    worklist.push(target);
7452                }
7453                worklist.push(index + 1);
7454            }
7455            // A `gosub` calls a subroutine and then continues, so both edges count.
7456            Opcode::Gosub => {
7457                if let Some(target) = placed_label(state, operands) {
7458                    worklist.push(target);
7459                }
7460                worklist.push(index + 1);
7461            }
7462            Opcode::Goto => {
7463                if let Some(target) = placed_label(state, operands) {
7464                    worklist.push(target);
7465                }
7466            }
7467            Opcode::IfTrue | Opcode::IfFalse => {
7468                if let Some(target) = placed_label(state, operands) {
7469                    worklist.push(target);
7470                }
7471                worklist.push(index + 1);
7472            }
7473            _ => worklist.push(index + 1),
7474        }
7475    }
7476    seen
7477}
7478
7479/// The instruction index a jump operand points at, resolved through the label
7480/// placement table.
7481fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
7482    let id = label_id(operands)?;
7483    state.labels.get(id as usize).copied().flatten()
7484}
7485
7486/// The label an instruction refers to.
7487fn label_id(operands: &[Op]) -> Option<u32> {
7488    operands.iter().find_map(|operand| match operand {
7489        Op::Label(label) => Some(label.0),
7490        _ => None,
7491    })
7492}
7493
7494/// Turn `if_false L; goto M; L:` into `if_true M`.
7495///
7496/// A conditional whose alternate branch is an unconditional jump needs one jump,
7497/// not two. This is the shape `if (c) break;` produces, so folding it removes an
7498/// instruction and a label from every conditional `break`.
7499/// The boolean a constant-push instruction produces, or `None` if it is not one.
7500///
7501/// Only the operators whose truthiness is decided by the opcode are covered; a
7502/// constant that needs the constant pool (a string) is left alone, because reading it
7503/// would mean threading the pool through the peephole for a case the reference also
7504/// skips.
7505fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
7506    match op {
7507        // `push_0` returns -1 for zero, `push_1` 1, and so on.
7508        Opcode::PushMinus1 => Some(true),
7509        Opcode::Push0 => Some(false),
7510        Opcode::Push1
7511        | Opcode::Push2
7512        | Opcode::Push3
7513        | Opcode::Push4
7514        | Opcode::Push5
7515        | Opcode::Push6
7516        | Opcode::Push7 => Some(true),
7517        Opcode::PushTrue => Some(true),
7518        Opcode::PushFalse => Some(false),
7519        Opcode::Undefined | Opcode::Null => Some(false),
7520        Opcode::PushI32 => match operands.first() {
7521            Some(Op::Int(value)) => Some(*value != 0),
7522            _ => None,
7523        },
7524        _ => None,
7525    }
7526}
7527
7528/// Fold a branch on a constant condition.
7529///
7530/// `if (0) a() else b()` must not test anything at run time, and the reference
7531/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
7532/// which is why the bytecode for a `while (1)` loop has no condition at all.
7533///
7534/// Two instructions become one, so the slot the test occupied is left empty rather
7535/// than shifting everything after it: labels have already been resolved to indices.
7536fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
7537    for index in 0..insns.len() {
7538        let Some((push_op, push_operands)) = insns[index].clone() else {
7539            continue;
7540        };
7541        let Some(truth) = constant_truth(push_op, &push_operands) else {
7542            continue;
7543        };
7544        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
7545            continue;
7546        };
7547        let (destination, taken) = match branch_op {
7548            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
7549            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
7550            _ => continue,
7551        };
7552        let Some(destination) = destination else {
7553            continue;
7554        };
7555        insns[index] = if taken {
7556            // The branch is always taken, so it becomes an unconditional jump.
7557            Some((Opcode::Goto, vec![destination]))
7558        } else {
7559            // The branch never runs: both instructions disappear and control falls
7560            // through to what came after.
7561            None
7562        };
7563        insns[index + 1] = None;
7564    }
7565}
7566
7567/// Remove a jump whose destination is the instruction right after it.
7568///
7569/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
7570/// its test into nothing, and the loop-end jump then points at the following
7571/// instruction. The reference drops them, so `stack_size` and the listing agree.
7572fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
7573    for index in 0..insns.len() {
7574        let Some((op, operands)) = insns[index].clone() else {
7575            continue;
7576        };
7577        if !is_goto(op) {
7578            continue;
7579        }
7580        let Some(id) = label_id(&operands) else {
7581            continue;
7582        };
7583        // The next instruction that still exists, which is what "the instruction
7584        // after this jump" means once earlier folds have punched holes.
7585        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
7586        if placed.get(id as usize).copied().flatten() == next {
7587            insns[index] = None;
7588        }
7589    }
7590}
7591
7592fn fold_conditional_jumps(
7593    insns: &mut [Option<(Opcode, Vec<Op>)>],
7594    label_at: &[Option<u32>],
7595    placed: &[Option<usize>],
7596) {
7597    for index in 0..insns.len() {
7598        let Some((op, operands)) = insns[index].clone() else {
7599            continue;
7600        };
7601        let inverted = match op {
7602            Opcode::IfFalse => Opcode::IfTrue,
7603            Opcode::IfTrue => Opcode::IfFalse,
7604            _ => continue,
7605        };
7606        // Next must be an unconditional jump that is not itself a target, and the
7607        // instruction after it must be exactly where the conditional goes.
7608        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
7609            continue;
7610        };
7611        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
7612            continue;
7613        }
7614        // The conditional must land on the instruction *after* the jump. Several
7615        // labels can share a position, so this asks where *this* label was put
7616        // rather than what label happens to sit there.
7617        let Some(taken) = label_id(&operands) else {
7618            continue;
7619        };
7620        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
7621            continue;
7622        }
7623        let Some(destination) = next_operands.first().cloned() else {
7624            continue;
7625        };
7626        insns[index] = Some((inverted, vec![destination]));
7627        insns[index + 1] = None;
7628    }
7629}
7630
7631/// Whether a jump target is placed at this instruction index.
7632fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
7633    label_at.get(index).copied().flatten().is_some()
7634}
7635
7636fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
7637    // `dup put_x(n)` -> `set_x(n)`
7638    // `dup put_x(n) drop` -> `put_x(n)`
7639    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
7640    for index in 0..insns.len() {
7641        if opcode_at(insns, index) != Some(Opcode::Dup) {
7642            continue;
7643        }
7644        if is_label_at(label_at, index + 1) {
7645            continue;
7646        }
7647        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
7648            continue;
7649        };
7650        if !is_foldable_put(put_op) {
7651            continue;
7652        }
7653        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
7654            continue;
7655        };
7656        let mut new_op = set_form_of(put_op);
7657        let mut end = index + 2;
7658        if is_label_at(label_at, end) {
7659            // The `put` has to stay as it is; only the `dup` can be folded.
7660            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
7661            insns[index + 1] = None;
7662            continue;
7663        }
7664        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
7665        // Deleting it moves the label's target onto whatever follows, and the code that
7666        // jumps there arrives with a different stack than the fall-through path: that is
7667        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
7668        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
7669        // an empty stack. The store had already consumed the value it was supposed to
7670        // leave behind.
7671        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
7672            new_op = put_op;
7673            end += 1;
7674            if opcode_at(insns, end) == Some(get_form_of(put_op))
7675                && !is_label_at(label_at, end)
7676                && insns[end]
7677                    .as_ref()
7678                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
7679            {
7680                new_op = set_form_of(put_op);
7681                end += 1;
7682            }
7683        }
7684        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
7685        for entry in &mut insns[index + 1..end] {
7686            *entry = None;
7687        }
7688    }
7689}
7690
7691fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
7692    insns
7693        .get(index)
7694        .and_then(|entry| entry.as_ref())
7695        .map(|(op, _)| *op)
7696}
7697
7698/// The four `put_` families that have a `set_` twin. Deliberately not including
7699/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
7700/// these, and folding the others would produce instructions that do not exist.
7701fn is_foldable_put(op: Opcode) -> bool {
7702    matches!(
7703        op,
7704        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
7705    )
7706}
7707
7708fn set_form_of(op: Opcode) -> Opcode {
7709    match op {
7710        Opcode::PutLoc => Opcode::SetLoc,
7711        Opcode::PutLocCheck => Opcode::SetLocCheck,
7712        Opcode::PutArg => Opcode::SetArg,
7713        Opcode::PutVarRef => Opcode::SetVarRef,
7714        other => other,
7715    }
7716}
7717
7718fn get_form_of(op: Opcode) -> Opcode {
7719    match op {
7720        Opcode::PutLoc => Opcode::GetLoc,
7721        Opcode::PutLocCheck => Opcode::GetLocCheck,
7722        Opcode::PutArg => Opcode::GetArg,
7723        Opcode::PutVarRef => Opcode::GetVarRef,
7724        other => other,
7725    }
7726}
7727
7728/// Atom interning, per function.
7729///
7730/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
7731/// identifiers, so the array-index rule applies here rather than at the handful of
7732/// call sites that build property keys.
7733fn intern_atom(state: &mut FnState, name: &str) -> u32 {
7734    let atom = Atom::from_text(name);
7735    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
7736        return index as u32;
7737    }
7738    state.atoms.push(atom);
7739    state.atoms.len() as u32 - 1
7740}
7741
7742fn binary_opcode(op: BinaryOp) -> Opcode {
7743    match op {
7744        BinaryOp::Add => Opcode::Add,
7745        BinaryOp::Sub => Opcode::Sub,
7746        BinaryOp::Mul => Opcode::Mul,
7747        BinaryOp::Div => Opcode::Div,
7748        BinaryOp::Mod => Opcode::Mod,
7749        BinaryOp::Pow => Opcode::Pow,
7750        BinaryOp::BitOr => Opcode::Or,
7751        BinaryOp::BitXor => Opcode::Xor,
7752        BinaryOp::BitAnd => Opcode::And,
7753        BinaryOp::Shl => Opcode::Shl,
7754        BinaryOp::Shr => Opcode::Sar,
7755        BinaryOp::UShr => Opcode::Shr,
7756        BinaryOp::Lt => Opcode::Lt,
7757        BinaryOp::LtEq => Opcode::Lte,
7758        BinaryOp::Gt => Opcode::Gt,
7759        BinaryOp::GtEq => Opcode::Gte,
7760        BinaryOp::Eq => Opcode::Eq,
7761        BinaryOp::NotEq => Opcode::Neq,
7762        BinaryOp::StrictEq => Opcode::StrictEq,
7763        BinaryOp::StrictNotEq => Opcode::StrictNeq,
7764        BinaryOp::In => Opcode::In,
7765        BinaryOp::Instanceof => Opcode::Instanceof,
7766    }
7767}
7768
7769fn compound_opcode(op: AssignOp) -> Opcode {
7770    match op {
7771        AssignOp::Add => Opcode::Add,
7772        AssignOp::Sub => Opcode::Sub,
7773        AssignOp::Mul => Opcode::Mul,
7774        AssignOp::Div => Opcode::Div,
7775        AssignOp::Mod => Opcode::Mod,
7776        AssignOp::Pow => Opcode::Pow,
7777        AssignOp::Shl => Opcode::Shl,
7778        AssignOp::Shr => Opcode::Sar,
7779        AssignOp::UShr => Opcode::Shr,
7780        AssignOp::BitOr => Opcode::Or,
7781        AssignOp::BitXor => Opcode::Xor,
7782        AssignOp::BitAnd => Opcode::And,
7783        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
7784    }
7785}
7786
7787/// Encode the resolved instruction stream, choosing short forms where possible.
7788///
7789/// The peephole pass leaves holes in the instruction list so that label indices
7790/// stay valid. A label names an *instruction index*, and an index that was
7791/// deleted has to resolve to the next surviving instruction, which is what
7792/// [`resolve_label`] does before the byte offsets are known.
7793fn assemble(
7794    insns: &mut [Option<(Opcode, Vec<Op>)>],
7795    insn_pos: &[Option<Position>],
7796    state: &mut FnState,
7797) -> (Vec<u8>, u32, Vec<LineCol>) {
7798    // Compaction: surviving instructions in order, plus the index mapping.
7799    //
7800    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
7801    // point below where instructions are removed — otherwise a stack trace would point
7802    // at the wrong source line as soon as dead-code elimination kicked in.
7803    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
7804    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7805    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
7806    for (original, entry) in insns.iter_mut().enumerate() {
7807        if let Some((op, operands)) = entry.take() {
7808            original_to_kept[original] = Some(kept.len());
7809            kept.push((op, operands));
7810            spans.push(insn_pos.get(original).copied().flatten());
7811        }
7812    }
7813
7814    if std::env::var_os("QJS_DEBUG").is_some() {
7815        eprintln!("--- assemble entry --- {kept:?}");
7816    }
7817    // How many labels are real, as opposed to the per-instruction ones allocated
7818    // just below. Only a real label marks a spot in the source program.
7819    let real_labels = state.labels.len();
7820
7821    // Give every surviving instruction a label of its own. Jump cleanup below
7822    // redirects jumps to arbitrary instructions, and a jump target has to be a
7823    // label; pre-allocating one per index means a redirect never has to invent
7824    // anything.
7825    let existing = state.labels.len();
7826    let base = kept.len();
7827    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
7828    for offset in 0..=kept.len() {
7829        state.labels.push(Some(0));
7830        index_label.push(Label((existing + offset) as u32));
7831    }
7832    // Point each pre-allocated label at its instruction, reusing the count from
7833    // `original_to_kept` so the mapping survives compaction.
7834    let place_index_labels = |state: &mut FnState,
7835                              original_to_kept: &[Option<usize>],
7836                              kept_len: usize,
7837                              index_label: &[Label]| {
7838        for (original, mapped) in original_to_kept.iter().enumerate() {
7839            if let Some(kept_index) = mapped {
7840                let label = index_label[*kept_index].0 as usize;
7841                state.labels[label] = Some(original);
7842            }
7843        }
7844        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
7845    };
7846    place_index_labels(state, &original_to_kept, base, &index_label);
7847
7848    // Resolve every label to a kept index once; the placement table maps labels
7849    // to original indices, so a second hop lands in kept space.
7850    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
7851    for (id, placed) in state.labels.iter().enumerate() {
7852        let Some(original) = placed else { continue };
7853        label_kept[id] = if *original == usize::MAX {
7854            Some(base)
7855        } else {
7856            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
7857        };
7858    }
7859
7860    // Code after an unconditional transfer is unreachable, and the reference drops it
7861    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
7862    // scans forward until it finds a label something still jumps to, so a run of
7863    // dead instructions between a `throw` and the next live target disappears.
7864    //
7865    // The scan repeats because dropping a jump lowers the reference count of the
7866    // label it pointed at, which can strand what follows. Only a real label keeps an
7867    // instruction alive here; the per-instruction labels allocated above belong to
7868    // this pass, not to the program.
7869    loop {
7870        let mut references = vec![false; kept.len() + 1];
7871        for (_, operands) in &kept {
7872            if let Some(target) = target_kept_index(operands, &label_kept)
7873                && target < references.len()
7874            {
7875                references[target] = true;
7876            }
7877        }
7878        let mut doomed = vec![false; kept.len()];
7879        let mut any = false;
7880        for (index, (op, _)) in kept.iter().enumerate() {
7881            if !is_transfer(*op) {
7882                continue;
7883            }
7884            for next in index + 1..kept.len() {
7885                if references[next] {
7886                    break;
7887                }
7888                doomed[next] = true;
7889                any = true;
7890            }
7891        }
7892        if !any {
7893            break;
7894        }
7895        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
7896    }
7897
7898    // A label that lands on an unconditional jump stands for wherever that jump
7899    // goes, so retarget it once and every jump to the label follows for free.
7900    // This is what makes `continue` in a `for` head reach the loop top instead of
7901    // stopping at the update's trailing jump.
7902    let folded: Vec<Option<usize>> = label_kept
7903        .iter()
7904        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
7905        .collect();
7906    label_kept = folded;
7907
7908    // Jump cleanup, in compacted index space. Two rewrites the reference also
7909    // applies while it resolves labels:
7910    //   * a jump whose destination is the very next instruction does nothing;
7911    //   * a jump to a jump is redirected to its final destination.
7912    // The second can expose the first, so this repeats until it settles.
7913    loop {
7914        let mut delete = vec![false; kept.len()];
7915        let mut changed = false;
7916        for index in 0..kept.len() {
7917            let (op, operands) = &kept[index];
7918            if !is_goto(*op) {
7919                continue;
7920            }
7921            let Some(immediate) = target_kept_index(operands, &label_kept) else {
7922                continue;
7923            };
7924            let target = follow_jump_chain(&kept, &label_kept, immediate);
7925            if target == index + 1 {
7926                delete[index] = true;
7927                changed = true;
7928            } else if matches!(
7929                kept.get(target).map(|(op, _)| *op),
7930                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
7931            ) {
7932                // Jumping straight to a return or throw is the same as doing it
7933                // here, so the jump becomes that instruction.
7934                kept[index] = (kept[target].0, Vec::new());
7935                changed = true;
7936            } else if target != immediate {
7937                // Redirect to the end of the chain.
7938                let label = index_label[target];
7939                kept[index].1 = vec![Op::Label(label)];
7940                changed = true;
7941            }
7942        }
7943        if !changed {
7944            break;
7945        }
7946        if !delete.iter().any(|deleted| *deleted) {
7947            break;
7948        }
7949        // Drop the deleted instructions and renumber everything.
7950        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
7951        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
7952        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
7953        for (old, entry) in kept.into_iter().enumerate() {
7954            if delete[old] {
7955                continue;
7956            }
7957            moved[old] = Some(next.len());
7958            next.push(entry);
7959            next_spans.push(spans[old]);
7960        }
7961        for (id, slot) in label_kept.iter_mut().enumerate() {
7962            let Some(old) = *slot else { continue };
7963            *slot = match moved.get(old).copied().flatten() {
7964                Some(new) => Some(new),
7965                // The target was deleted: the jump now lands on whatever follows.
7966                None => (old..moved.len())
7967                    .find_map(|i| moved[i])
7968                    .or(Some(next.len())),
7969            };
7970            let _ = id;
7971        }
7972        kept = next;
7973        spans = next_spans;
7974    }
7975
7976    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
7977    // jump to the next instruction and is deleted, leaving the label at the end with
7978    // nothing pointing at it. If that also strands the last instruction, it goes
7979    // too — which is how a `try` whose body always returns ends on its `ret` rather
7980    // than an implicit `return_undef`.
7981    // Which instructions something still jumps to. Reading the surviving jumps is
7982    // what the reference's reference counts amount to: once a jump has been folded
7983    // away the label it named is unreferenced, even though the program still has a
7984    // label there.
7985    let mut references = vec![false; kept.len() + 1];
7986    let _ = real_labels;
7987    for (_, operands) in &kept {
7988        if let Some(target) = target_kept_index(operands, &label_kept)
7989            && target < references.len()
7990        {
7991            references[target] = true;
7992        }
7993    }
7994    let mut end = kept.len();
7995    while end > 0 {
7996        let last = end - 1;
7997        let reachable = references[last] || end < kept.len();
7998        if reachable {
7999            break;
8000        }
8001        let after_transfer = last
8002            .checked_sub(1)
8003            .map(|previous| {
8004                matches!(
8005                    kept[previous].0,
8006                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
8007                )
8008            })
8009            .unwrap_or(false);
8010        if !after_transfer {
8011            break;
8012        }
8013        end = last;
8014    }
8015    kept.truncate(end);
8016    spans.truncate(end);
8017
8018    // Choose an opcode for each instruction and its size, so label offsets can be
8019    // computed.
8020    let chosen = choose_opcodes(&kept, &label_kept);
8021    let offsets = instruction_offsets(&chosen);
8022    let offset = *offsets.last().unwrap_or(&0);
8023
8024    let mut code = Vec::with_capacity(offset);
8025    for (position, (_, operands)) in kept.iter().enumerate() {
8026        let op = chosen[position];
8027        code.push(op as u8);
8028        let operands = retarget_labels(operands, &label_kept, kept.len());
8029        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
8030    }
8031    let stack_size = compute_stack_size(&code);
8032    // Keep only the offsets where the position actually changes: a run of
8033    // instructions on one line is one table entry, and the runtime binary searches
8034    // the table for the frame's pc.
8035    //
8036    // The table always starts at pc 0 with the *function's own* position, because the
8037    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
8038    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
8039    // (`function`, `async`, a method's property name). An instruction before the first
8040    // recorded operator therefore reports the function's own start, which is what makes a
8041    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
8042    let mut positions: Vec<LineCol> = vec![LineCol {
8043        pc: 0,
8044        line: state.line,
8045        column: state.column,
8046    }];
8047    let mut last: Option<Position> = None;
8048    for (index, span) in spans.iter().enumerate() {
8049        let Some(pos) = *span else { continue };
8050        if last == Some(pos) {
8051            continue;
8052        }
8053        last = Some(pos);
8054        if pos.line == state.line && pos.column == state.column {
8055            // Already the seed entry above.
8056            continue;
8057        }
8058        positions.push(LineCol {
8059            pc: offsets[index] as u32,
8060            line: pos.line,
8061            column: pos.column,
8062        });
8063    }
8064    (code, stack_size, positions)
8065}
8066
8067/// Whether an instruction always transfers control away, so anything after it in the
8068/// same stream is unreachable.
8069fn is_transfer(op: Opcode) -> bool {
8070    matches!(
8071        op,
8072        Opcode::Goto
8073            | Opcode::Goto8
8074            | Opcode::Goto16
8075            | Opcode::Return
8076            | Opcode::ReturnUndef
8077            | Opcode::Throw
8078            | Opcode::ThrowError
8079            | Opcode::Ret
8080    )
8081}
8082
8083/// Remove the marked instructions and renumber the label table so it keeps pointing
8084/// at the same instructions. A label whose instruction went away moves to whatever
8085/// follows it, since a jump is never left with nowhere to land.
8086fn drop_instructions(
8087    kept: Vec<(Opcode, Vec<Op>)>,
8088    spans: Vec<Option<Position>>,
8089    label_kept: &mut [Option<usize>],
8090    doomed: &[bool],
8091) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
8092    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
8093    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
8094    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
8095    for (old, entry) in kept.into_iter().enumerate() {
8096        if doomed.get(old).copied().unwrap_or(false) {
8097            continue;
8098        }
8099        moved[old] = Some(result.len());
8100        result.push(entry);
8101        result_spans.push(spans[old]);
8102    }
8103    for slot in label_kept.iter_mut() {
8104        let Some(old) = *slot else { continue };
8105        *slot = match moved.get(old).copied().flatten() {
8106            Some(new) => Some(new),
8107            None => (old..moved.len())
8108                .find_map(|i| moved[i])
8109                .or(Some(result.len())),
8110        };
8111    }
8112    (result, result_spans)
8113}
8114
8115fn is_goto(op: Opcode) -> bool {
8116    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
8117}
8118
8119/// The kept index a jump operand points at.
8120fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
8121    let id = label_id(operands)?;
8122    label_kept.get(id as usize).copied().flatten()
8123}
8124
8125/// Follow a chain of unconditional jumps to its first real destination.
8126fn follow_jump_chain(
8127    kept: &[(Opcode, Vec<Op>)],
8128    label_kept: &[Option<usize>],
8129    start: usize,
8130) -> usize {
8131    let mut current = start;
8132    // `for(;;)` jumps to itself, so the walk has to be bounded.
8133    for _ in 0..kept.len() {
8134        let Some((op, operands)) = kept.get(current) else {
8135            return current;
8136        };
8137        if !is_goto(*op) {
8138            return current;
8139        }
8140        let Some(next) = target_kept_index(operands, label_kept) else {
8141            return current;
8142        };
8143        if next == current {
8144            return current;
8145        }
8146        current = next;
8147    }
8148    current
8149}
8150
8151/// Rewrite label operands from label ids to kept instruction indices.
8152fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
8153    operands
8154        .iter()
8155        .map(|operand| match operand {
8156            Op::Label(label) => {
8157                let target = label_kept
8158                    .get(label.0 as usize)
8159                    .copied()
8160                    .flatten()
8161                    .unwrap_or(kept_len);
8162                Op::Label(Label(target as u32))
8163            }
8164            other => other.clone(),
8165        })
8166        .collect()
8167}
8168
8169/// Encode the resolved instruction stream, choosing short forms where possible.
8170///
8171/// Compute the maximum value-stack depth by exploring the control-flow graph.
8172///
8173/// This is a breadth-first walk from the first instruction, tracking the stack
8174/// depth on entry to each instruction. Every instruction has at most two
8175/// successors (fall through, and a jump target), so a worklist over byte offsets
8176/// is enough. The reference does the same thing in `compute_stack_size`, which is
8177/// why the resulting numbers match exactly.
8178///
8179/// Instructions that pop a variable number of values (`call`, `array_from`, …)
8180/// encode that count in their operand, which is added to the static `n_pop`.
8181fn compute_stack_size(code: &[u8]) -> u32 {
8182    let mut depth_at = vec![u16::MAX; code.len()];
8183    // Each entry carries the enclosing `catch` levels, innermost last, because
8184    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
8185    // offset and forgets that level.
8186    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
8187    let mut max_depth = 0u32;
8188
8189    while let Some((pc, depth, catch_levels)) = worklist.pop() {
8190        if pc >= code.len() {
8191            continue;
8192        }
8193        if depth_at[pc] != u16::MAX {
8194            continue;
8195        }
8196        force_depth(&mut depth_at, pc, depth);
8197
8198        let Some(op) = Opcode::from_u8(code[pc]) else {
8199            break;
8200        };
8201        let info = op.info();
8202        let next = pc + info.size as usize;
8203        if next > code.len() {
8204            break;
8205        }
8206        let mut n_pop = info.n_pop as u32;
8207        let mut n_push = info.n_push as u32;
8208        // Variable-length forms carry their count in the operand.
8209        match info.format {
8210            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
8211                n_pop += read_u16(code, pc + 1) as u32;
8212            }
8213            crate::opcode::OpFormat::Npopx => {
8214                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
8215            }
8216            _ => {}
8217        }
8218        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
8219        // are the `set_` variant; the table already records that, so nothing to
8220        // adjust here.
8221        let _ = &mut n_push;
8222
8223        // The depth before this instruction's own push, which is what a `catch`
8224        // records as its level.
8225        let depth_before = depth;
8226        let mut depth = depth.saturating_sub(n_pop) + n_push;
8227        let mut catch_levels = catch_levels;
8228        if op == Opcode::NipCatch {
8229            // Discard everything above the innermost catch offset, keeping the value
8230            // on top: the frame the code after this sees is the same shape it would
8231            // have had if the `try` were not there.
8232            if let Some(base) = catch_levels.pop() {
8233                depth = base + 1;
8234            }
8235        }
8236        max_depth = max_depth.max(depth);
8237
8238        // Successors.
8239        let target = jump_target_of(code, pc, op);
8240        match op {
8241            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8242                if let Some(target) = target {
8243                    worklist.push((target, depth, catch_levels));
8244                }
8245            }
8246            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
8247                if let Some(target) = target {
8248                    worklist.push((target, depth, catch_levels.clone()));
8249                }
8250                worklist.push((next, depth, catch_levels));
8251            }
8252            // A `catch` records an exception edge to the handler. The handler is
8253            // entered with the thrown value on top of the stack, in the slot the
8254            // catch offset occupies on the normal path — which is why the handler's
8255            // first instruction can `put_loc` the exception away, and why the depth
8256            // is the same on both paths.
8257            Opcode::Catch => {
8258                if let Some(target) = target {
8259                    // The handler is protected by the *enclosing* catch, not by this
8260                    // one: an error raised inside it is what the handler's own
8261                    // `catch` catches.
8262                    worklist.push((target, depth, catch_levels.clone()));
8263                }
8264                catch_levels.push(depth_before);
8265                worklist.push((next, depth, catch_levels));
8266            }
8267            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
8268            // rewind past it too. Its level sits one slot higher than a `catch`'s:
8269            // the iterator and next-method slots occupy the offset's place.
8270            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
8271                if let Some(target) = target {
8272                    worklist.push((target, depth, catch_levels.clone()));
8273                }
8274                catch_levels.push(depth_before + 1);
8275                worklist.push((next, depth, catch_levels));
8276            }
8277            // `gosub` calls a subroutine with the return address on top. The opcode
8278            // table records no push for it — `ret` is what pops the slot — so the
8279            // extra one is added here, where the depth of the subroutine's first
8280            // instruction is being computed.
8281            Opcode::Gosub => {
8282                if let Some(target) = target {
8283                    worklist.push((target, depth + 1, catch_levels.clone()));
8284                }
8285                worklist.push((next, depth, catch_levels));
8286            }
8287            // `ret` goes back to a `gosub`; nothing here follows it.
8288            Opcode::Ret
8289            | Opcode::Return
8290            | Opcode::ReturnUndef
8291            | Opcode::Throw
8292            | Opcode::ThrowError => {}
8293            _ => worklist.push((next, depth, catch_levels)),
8294        }
8295    }
8296    max_depth
8297}
8298
8299/// Record the stack depth on entry to `pc`, keeping the deeper value if the
8300/// instruction is reachable more than once.
8301fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
8302    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
8303    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
8304        depth_at[pc] = clamped;
8305    }
8306}
8307
8308fn read_u16(code: &[u8], at: usize) -> u16 {
8309    let mut value = 0u16;
8310    for i in 0..2 {
8311        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
8312    }
8313    value
8314}
8315
8316/// The absolute target of a jump instruction, if it has one.
8317fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
8318    let info = op.info();
8319    let position = pc + 1;
8320    match info.format {
8321        crate::opcode::OpFormat::Label8 => {
8322            let offset = *code.get(position)? as i8 as i64;
8323            Some((position as i64 + offset) as usize)
8324        }
8325        crate::opcode::OpFormat::Label16 => {
8326            let offset = read_u16(code, position) as i16 as i64;
8327            Some((position as i64 + offset) as usize)
8328        }
8329        crate::opcode::OpFormat::Label => {
8330            let mut offset = 0i32;
8331            for i in 0..4 {
8332                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
8333            }
8334            Some((position as i64 + offset as i64) as usize)
8335        }
8336        _ => None,
8337    }
8338}
8339
8340fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
8341    use Opcode::*;
8342    match (op, operands.first()) {
8343        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
8344            op.short_form(*value as u32).unwrap_or(op)
8345        }
8346        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
8347        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
8348        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
8349        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
8350        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
8351        // A declared global is reached through its reference cell, so it shares
8352        // the `var_ref` encodings, short forms included.
8353        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
8354            op.short_form(*index).unwrap_or(op)
8355        }
8356        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
8357            op.short_form(*count as u32).unwrap_or(op)
8358        }
8359        _ => op,
8360    }
8361}
8362
8363/// The byte offset each instruction will start at, plus the total code size.
8364fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
8365    let mut offsets = Vec::with_capacity(chosen.len() + 1);
8366    let mut offset = 0usize;
8367    for op in chosen {
8368        offsets.push(offset);
8369        offset += op.size() as usize;
8370    }
8371    offsets.push(offset);
8372    offsets
8373}
8374
8375/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
8376/// the offset actually fits.
8377///
8378/// The choice is circular: an instruction's size decides the offsets of everything after
8379/// it, and the offsets decide whether a jump may be short. So this starts with every jump
8380/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
8381/// Shrinking only ever *shortens* distances, so the loop converges.
8382///
8383/// Doing it in one pass instead — which is what this used to do — silently truncated any
8384/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
8385/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
8386/// with four closures in its body simply stopped, with no error and no output past the
8387/// first iteration.
8388fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
8389    let mut chosen: Vec<Opcode> = kept
8390        .iter()
8391        .map(|(op, operands)| choose_short_form(*op, operands))
8392        .collect();
8393    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
8394    let candidates = |op: Opcode| match op {
8395        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
8396        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
8397        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
8398        _ => None,
8399    };
8400    loop {
8401        let offsets = instruction_offsets(&chosen);
8402        let mut changed = false;
8403        for index in 0..kept.len() {
8404            let (op, operands) = &kept[index];
8405            let Some((short, medium, has_medium)) = candidates(*op) else {
8406                continue;
8407            };
8408            if chosen[index] == short {
8409                continue;
8410            }
8411            let Some(target) = target_kept_index(operands, label_kept) else {
8412                continue;
8413            };
8414            let Some(&target_offset) = offsets.get(target) else {
8415                continue;
8416            };
8417            // A jump is relative to the byte after its opcode, which is the convention
8418            // `jump_target_of` decodes with.
8419            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
8420            if (-128..=127).contains(&relative) {
8421                chosen[index] = short;
8422                changed = true;
8423            } else if has_medium
8424                && chosen[index] == Opcode::Goto
8425                && (-32_768..=32_767).contains(&relative)
8426            {
8427                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
8428                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
8429                // the reference encodes them.
8430                chosen[index] = medium;
8431                changed = true;
8432            }
8433        }
8434        if !changed {
8435            return chosen;
8436        }
8437    }
8438}
8439
8440fn encode_operands(
8441    code: &mut Vec<u8>,
8442    op: Opcode,
8443    operands: &[Op],
8444    position: usize,
8445    offsets: &[usize],
8446) {
8447    use crate::opcode::OpFormat::*;
8448    let info = op.info();
8449    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
8450        let index = match slot {
8451            Slot::Arg(i)
8452            | Slot::Loc(i)
8453            | Slot::VarRef(i)
8454            | Slot::Global(i)
8455            | Slot::GlobalDecl(i) => i,
8456        };
8457        code.extend_from_slice(&(index as u16).to_be_bytes());
8458    };
8459    match info.format {
8460        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
8461        U8 | Const8 => {
8462            if let Some(value) = operands.first().and_then(operand_uint) {
8463                code.push(value as u8);
8464            }
8465        }
8466        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
8467        // like their wide counterparts, only one byte wide.
8468        Loc8 => {
8469            if let Some(Op::Slot(slot)) = operands.first() {
8470                let index = match slot {
8471                    Slot::Arg(i)
8472                    | Slot::Loc(i)
8473                    | Slot::VarRef(i)
8474                    | Slot::Global(i)
8475                    | Slot::GlobalDecl(i) => *i,
8476                };
8477                code.push(index as u8);
8478            }
8479        }
8480        I8 => {
8481            if let Some(value) = operands.first().and_then(operand_int) {
8482                code.push(value as i8 as u8);
8483            }
8484        }
8485        U16 | Npop => {
8486            if let Some(value) = operands.first().and_then(operand_int) {
8487                code.extend_from_slice(&(value as u16).to_be_bytes());
8488            }
8489        }
8490        I16 => {
8491            if let Some(value) = operands.first().and_then(operand_int) {
8492                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
8493            }
8494        }
8495        I32 => {
8496            if let Some(value) = operands.first().and_then(operand_int) {
8497                code.extend_from_slice(&value.to_be_bytes());
8498            }
8499        }
8500        U32 | Const => {
8501            if let Some(value) = operands.first().and_then(operand_uint) {
8502                code.extend_from_slice(&value.to_be_bytes());
8503            }
8504        }
8505        Loc | Arg | VarRef => {
8506            if let Some(Op::Slot(slot)) = operands.first() {
8507                write_slot(code, *slot);
8508            }
8509        }
8510        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
8511            if let Some(Op::AtomId(index)) = operands.first() {
8512                code.extend_from_slice(&index.to_be_bytes());
8513            }
8514            // The trailing immediate means different things per format, and the
8515            // atom forms that carry a *label* have to resolve it like any other
8516            // jump, so they cannot share the `U8`/`U16` arms above.
8517            match info.format {
8518                AtomU8 | AtomLabelU8 => {
8519                    if let Some(value) = operands.get(1).and_then(operand_uint) {
8520                        code.push(value as u8);
8521                    }
8522                }
8523                AtomU16 | AtomLabelU16 => {
8524                    if let Some(value) = operands.get(1).and_then(operand_uint) {
8525                        code.extend_from_slice(&(value as u16).to_be_bytes());
8526                    }
8527                }
8528                _ => {}
8529            }
8530        }
8531        NpopU16 => {
8532            for operand in operands.iter().take(2) {
8533                if let Some(value) = operand_uint(operand) {
8534                    code.extend_from_slice(&(value as u16).to_be_bytes());
8535                }
8536            }
8537        }
8538        Label | Label8 | Label16 | LabelU16 => {
8539            if let Some(Op::Label(label)) = operands.first() {
8540                // Labels were already remapped to kept-instruction indices.
8541                let Some(&target) = offsets.get(label.0 as usize) else {
8542                    debug_assert!(false, "label {} is past the end", label.0);
8543                    return;
8544                };
8545                let relative = target as i64 - (position as i64 + 1);
8546                match info.format {
8547                    Label8 => code.push(relative as i8 as u8),
8548                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
8549                    // `label_u16` stores the target followed by an unrelated u16.
8550                    LabelU16 => {
8551                        code.extend_from_slice(&(relative as i32).to_be_bytes());
8552                        if let Some(value) = operands.get(1).and_then(operand_uint) {
8553                            code.extend_from_slice(&(value as u16).to_be_bytes());
8554                        }
8555                    }
8556                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
8557                }
8558            }
8559        }
8560    }
8561}
8562
8563fn operand_int(op: &Op) -> Option<i32> {
8564    match op {
8565        Op::Int(value) => Some(*value),
8566        _ => None,
8567    }
8568}
8569
8570fn operand_uint(op: &Op) -> Option<u32> {
8571    match op {
8572        Op::Const(value) | Op::AtomId(value) => Some(*value),
8573        Op::Int(value) => Some(*value as u32),
8574        _ => None,
8575    }
8576}
8577
8578/// Disassemble a compiled function.
8579pub fn disassemble(function: &CompiledFunction) -> String {
8580    disasm::disassemble_program(function)
8581}