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