Skip to main content

nodejs/
compiler.rs

1//! Lower the JavaScript AST to `fusevm::Chunk`.
2//!
3//! Native fusevm ops carry arithmetic (`+ - * / % **`), the relational
4//! comparisons (`< <= > >=`) and boolean short-circuit so the JIT can trace
5//! them; the strict numeric hook (host) supplies JS semantics for non-numeric
6//! operands (string concat, coercion). Everything JS-specific — name access,
7//! member/index access, calls, object/array construction, iteration — lowers to
8//! a `CallBuiltin` that lands in `builtins.rs`.
9//!
10//! Conditions are normalized through the `TRUTHY` builtin before a native
11//! `JumpIfFalse`, because JS truthiness differs from fusevm's default numeric
12//! truthiness. Compiler-internal name strings travel as native `Value::Str`
13//! constants; JS-level strings are always heap objects built by `MKSTR`.
14
15use crate::ast::*;
16use crate::host::{binop as bop, member, ops, unop, unwind, FuncDef, ParamSlot, TryDef};
17use fusevm::{Chunk, ChunkBuilder, Op, Value};
18
19/// A compiled program: the top-level chunk plus the function template table and
20/// the try-block table.
21#[derive(Default)]
22pub struct Program {
23    pub main: Chunk,
24    pub functions: Vec<(String, FuncDef)>,
25    pub tries: Vec<TryDef>,
26    /// Whether the program's own top level is strict (`'use strict'` as its
27    /// first statement). A FUNCTION carries its strictness in its `FuncDef`;
28    /// the top level had nowhere to put it, so the module frame stayed sloppy
29    /// and a refused write never threw there even though the compiler had
30    /// already emitted the strict ASSIGNMENT opcodes.
31    pub strict: bool,
32    /// The text the program was parsed from, which every function's `span`
33    /// indexes. Installed on the host by `load_merged`.
34    pub source: Option<std::sync::Arc<str>>,
35}
36
37/// Rebase every func-id and try-id reference so its ids sit above those already
38/// loaded on the host (needed only for incremental loading; a no-op for a single
39/// run).
40pub fn rebase_program(prog: &mut Program, func_off: usize, try_off: usize) {
41    if func_off == 0 && try_off == 0 {
42        return;
43    }
44    rebase_chunk(&mut prog.main, func_off, try_off);
45    for (_, f) in &mut prog.functions {
46        rebase_chunk(&mut f.chunk, func_off, try_off);
47    }
48    for t in &mut prog.tries {
49        rebase_chunk(&mut t.block, func_off, try_off);
50        if let Some((_, hb)) = &mut t.handler {
51            rebase_chunk(hb, func_off, try_off);
52        }
53        if let Some(f) = &mut t.finalizer {
54            rebase_chunk(f, func_off, try_off);
55        }
56    }
57}
58
59fn rebase_chunk(chunk: &mut Chunk, func_off: usize, try_off: usize) {
60    for i in 1..chunk.ops.len() {
61        let off = match chunk.ops[i] {
62            Op::CallBuiltin(id, _) if id == ops::MKFUNC => func_off,
63            Op::CallBuiltin(id, 4) if id == ops::MKCLASS => func_off,
64            Op::CallBuiltin(id, 1) if id == ops::TRY => try_off,
65            _ => continue,
66        };
67        if off == 0 {
68            continue;
69        }
70        if let Op::LoadInt(v) = &mut chunk.ops[i - 1] {
71            *v += off as i64;
72        }
73    }
74    for sub in &mut chunk.sub_chunks {
75        rebase_chunk(sub, func_off, try_off);
76    }
77}
78
79/// A node's source position over the ops `start..end` it compiled to.
80struct PosMark {
81    start: usize,
82    end: usize,
83    pos: Pos,
84    scope: PosScope,
85}
86
87/// Which of a node's ops its position is given to.
88#[derive(Clone, Copy)]
89enum PosScope {
90    /// A statement: every op no nested node placed — V8's statement position,
91    /// which is where an error in an unplaced sub-expression is reported.
92    Statement,
93    /// A call, `new`, or property access: only the op that performs it (its
94    /// last builtin call), the one that raises or calls out. Its operands keep
95    /// their own places, as V8's expression positions do: an unbound `o` in
96    /// `o.p` is not reported at `p`.
97    Operation,
98}
99
100/// Move a chunk's source positions (script-relative [`Pos`] values in its
101/// `lines`) into the script's range of the host's source address space, which
102/// starts at `base`; with no range (`None`) the positions are dropped.
103pub fn rebase_positions(chunk: &mut Chunk, base: Option<u32>) {
104    for p in chunk.lines.iter_mut().filter(|p| **p != 0) {
105        *p = base.map_or(0, |b| b + *p - 1);
106    }
107    for sub in &mut chunk.sub_chunks {
108        rebase_positions(sub, base);
109    }
110}
111
112/// The binding scope a declaration keyword introduces.
113fn bind_mode(kind: DeclKind) -> BindMode {
114    match kind {
115        DeclKind::Var => BindMode::Var,
116        DeclKind::Let => BindMode::Lexical,
117        DeclKind::Const => BindMode::Const,
118    }
119}
120
121/// How a binding site introduces its name.
122#[derive(Clone, Copy, PartialEq, Eq)]
123enum BindMode {
124    /// Plain assignment to an existing binding (`x = 1`, a for-of head without
125    /// `let`/`const`/`var`).
126    Assign,
127    /// `let`/`class`: bound in the innermost BLOCK scope.
128    Lexical,
129    /// `const`: block-scoped like `Lexical`, but IMMUTABLE — a later assignment
130    /// to the name throws `TypeError: Assignment to constant variable.`
131    Const,
132    /// `var` / a hoisted function declaration: bound at FUNCTION scope.
133    Var,
134}
135
136/// Break/continue jump fixups for a loop or switch.
137struct LoopCtx {
138    breaks: Vec<usize>,
139    continues: Vec<usize>,
140    /// Block-scope depth the `break` target expects; a `break` from inside nested
141    /// blocks pops back down to it first.
142    break_depth: usize,
143    /// Block-scope depth the `continue` target expects.
144    continue_depth: usize,
145    /// Number of iterators on the VM stack inside this loop's body.
146    iter_depth: usize,
147    /// Whether `continue` binds here (true for loops, false for `switch`).
148    catches_continue: bool,
149    /// The source label attached to this loop/block, if any (`outer: for …`),
150    /// so labeled `break outer` / `continue outer` can target it directly.
151    label: Option<String>,
152}
153
154#[derive(Default)]
155pub struct Compiler {
156    /// Pending short-circuit jumps for the optional chain being lowered, one
157    /// frame per chain.
158    ///
159    /// `?.` short-circuits the WHOLE chain to its right, not just its own link:
160    /// `o.a?.b.c` is `undefined` when `o.a` is nullish, and never reads `.c`
161    /// off it. Each `?.` therefore parks its jump here and the chain's ROOT
162    /// patches every one of them to the end. An empty stack means no chain is
163    /// open, so a `?.` outside one patches itself as before.
164    opt_chain: Vec<Vec<usize>>,
165    /// Compiling a Script whose COMPLETION VALUE is observable — what `eval`
166    /// returns. Every expression statement then stores into `.completion`
167    /// instead of discarding its value, which is how the "last non-empty
168    /// completion" rule (14.x, `UpdateEmpty`) falls out without threading a
169    /// value through each statement form. Cleared inside a nested function
170    /// body, whose statements are not the script's.
171    completion: bool,
172    functions: Vec<(String, FuncDef)>,
173    tries: Vec<TryDef>,
174    loops: Vec<LoopCtx>,
175    tmp: usize,
176    /// A label seen immediately before a loop, consumed by that loop's `LoopCtx`
177    /// (`outer: for (…)`); `None` once claimed.
178    pending_label: Option<String>,
179    /// Source text of the expression an object pattern is being destructured
180    /// FROM, set by the declaration or assignment site. Node names it in the
181    /// error a nullish source raises — `Cannot destructure property 'w' of 'v'
182    /// as it is null` — and the pattern compiler only has the VALUE.
183    destructure_src: Option<String>,
184    /// Whether `destructure_src` came from a DECLARATION's initializer rather
185    /// than from an assignment target. Node names the source in a
186    /// not-iterable error only for a declaration: `const [x] = o` is `o is not
187    /// iterable`, while `[y] = o` reports the TYPE.
188    destructure_is_decl: bool,
189    /// Emit per-statement `DBG_LINE` markers for the DAP debugger (`node --dap`).
190    debug: bool,
191    /// Index into `loops` of the first loop opened by the chunk being emitted.
192    /// A `break`/`continue` targeting a loop BELOW this index leaves the current
193    /// chunk (a `try` body is compiled as its own chunk), so it cannot be a plain
194    /// jump and is raised as a signal instead.
195    chunk_loop_base: usize,
196    /// Whether this chunk contains a signal-raising `break`/`continue`, so loops
197    /// in it must re-dispatch a still-pending signal when they exit.
198    chunk_signals: bool,
199    /// Number of block scopes open at the current emission point, so a jump out of
200    /// them can pop exactly the right number.
201    scope_depth: usize,
202    /// True while compiling an `async function*` body, where `yield*` must drive
203    /// the delegate through the ASYNC iteration protocol.
204    in_async_generator: bool,
205    /// Number of for-of/for-in iterators parked on the VM stack at this point. A
206    /// `break`/`continue` that leaves such a loop must close and drop its iterator,
207    /// otherwise the enclosing loop's `FORITER` would peek at the wrong one.
208    iter_depth: usize,
209    /// Whether the code being emitted is in STRICT mode — a `'use strict'`
210    /// directive prologue on the program or an enclosing function body, or a
211    /// class body (which is strict unconditionally). The only difference it
212    /// makes here is `PutValue` on an unresolvable reference: strict code throws
213    /// `ReferenceError` where sloppy code creates a global.
214    strict: bool,
215    /// Callee SOURCE TEXT per call op of the chunk being emitted, handed to the
216    /// host when the chunk is built so a failed call can name the callee the way
217    /// the source wrote it. Saved and restored around every nested chunk.
218    call_sites: Vec<(usize, String)>,
219    /// Source positions for the chunk being emitted, innermost node first;
220    /// `finish_chunk` writes them into the chunk's `lines`.
221    pos_marks: Vec<PosMark>,
222    /// Parked-iterator depth per `yield` op of the chunk being emitted, so an
223    /// injected `.return()`/`.throw()` can close the `for…of` / `yield*`
224    /// iterators the halt would otherwise abandon.
225    yield_sites: Vec<(usize, usize)>,
226    /// Locals of the chunk being emitted that live in fusevm frame slots rather
227    /// than the host's scope chain — see [`crate::slots`]. Empty for a chunk the
228    /// analysis refused, so `slot_of` answering `None` is the old path.
229    slots: crate::slots::Plan,
230    /// Number of tagged-template sites emitted so far in this compilation, so
231    /// each site carries an ordinal the runtime can cache its template object
232    /// under. Monotonic across the whole compilation rather than per chunk: two
233    /// textually identical arrow bodies are separate chunks, and this operand is
234    /// what makes their bytecode — and therefore their chunk hashes — differ.
235    tmpl_sites: u64,
236    /// Set by `build_arrow` for the one `build_function` call it makes: an arrow
237    /// has no `arguments` object of its own to alias.
238    arrow_next: bool,
239    /// Counter for the hidden slots static-field initializers are called
240    /// through (see `emit_static_initializer`).
241    static_init_n: usize,
242    /// While a `finally` block is compiled inside a completion-valued program:
243    /// `(its own register, the enclosing register)`. A `finally` that completes
244    /// normally discards its value (14.15.3), so its statements write a
245    /// register of their own; a `break`/`continue` that LEAVES it completes the
246    /// whole `try` statement with the value the block had produced so far
247    /// (`undefined` if none), so that register is copied outward just before
248    /// the jump.
249    finalizer_completion: Option<(String, String)>,
250    /// The register expression statements write while `completion` is on;
251    /// empty means the program-level [`COMPLETION_SLOT`].
252    completion_slot: String,
253    /// `(op index, parked-iterator depth)` at every point of the chunk being
254    /// emitted where that depth changes, so `finish_chunk` can record the depth
255    /// for every builtin call — the error path needs it to close the iterators a
256    /// throw abandons.
257    iter_events: Vec<(usize, usize)>,
258    /// How many `with` bodies enclose the code being emitted, nested functions
259    /// included. Inside one, an identifier may resolve to a property of the
260    /// `with` object, so every name access goes through the `WITH_*` ops and no
261    /// local lives in a frame slot.
262    with_depth: usize,
263}
264
265// ── early errors: duplicate lexical declarations ─────────────────────────────
266
267/// The names strict code may not BIND or ASSIGN to (13.1.1, 14.3.1.1).
268const RESERVED_IN_STRICT: [&str; 2] = ["eval", "arguments"];
269
270/// `SyntaxError: Unexpected eval or arguments in strict mode` — raised for a
271/// binding, a parameter, an assignment target and an update target alike.
272fn strict_reserved_error() -> String {
273    "SyntaxError: Unexpected eval or arguments in strict mode".to_string()
274}
275
276/// Reject a duplicate lexical declaration before anything runs, as node does.
277///
278/// `let a = 1; let a = 2;` is a SyntaxError at PARSE time in node, and this
279/// engine ran it — the second declaration simply won. That is the gap that lets
280/// a genuine double-declaration bug through silently, and it bit three test
281/// files in this repo whose collisions node rejected and this accepted.
282///
283/// Deliberately narrow, since a false positive REJECTS a program that works:
284/// only the three collisions the spec is unambiguous about are reported —
285/// two lexical declarations of one name in the same statement list, a lexical
286/// name that a `var` in the same subtree hoists onto, and a lexical name
287/// colliding with a function declaration beside it. Repeated `var`s, and the
288/// same name in nested scopes, stay legal.
289///
290/// V8 finds a collision while parsing, when the second of the two
291/// declarations is reached, so the one reported is the collision whose later
292/// declaration comes first in the source, and the report's arrow underlines
293/// that declaration's name (`parser::note_error_span`).
294pub fn check_early_errors(stmts: &[Stmt]) -> Result<(), String> {
295    let mut found = None;
296    redeclarations(stmts, &mut found);
297    check_redeclared(found)
298}
299
300/// Report the collision [`redeclarations`] found, if any.
301fn check_redeclared(found: Option<Binding>) -> Result<(), String> {
302    match found {
303        Some(b) => {
304            crate::parser::note_error_span(b.pos, b.end);
305            Err(already_declared(&b.name))
306        }
307        None => Ok(()),
308    }
309}
310
311/// A declared name and the span V8 reports a collision with it at: the first
312/// character of the name for a variable, the first of the declaration for a
313/// function, the whole declaration for a class. `end` 0 is that one
314/// character; `pos` 0 is a declaration with no source position.
315#[derive(Clone)]
316struct Binding {
317    name: String,
318    pos: Pos,
319    end: Pos,
320}
321
322/// The bindings a declaration target introduces, each placed where `bound`
323/// (the parser's record of the target) says its name is written.
324fn bindings_at(target: &Expr, bound: &[(String, Pos)]) -> Vec<Binding> {
325    let mut names = Vec::new();
326    pattern_names(target, &mut names);
327    names
328        .into_iter()
329        .map(|name| {
330            let pos = bound.iter().find(|(n, _)| *n == name).map_or(0, |b| b.1);
331            Binding { name, pos, end: 0 }
332        })
333        .collect()
334}
335
336/// Where a declaration spanning `span` starts, as a [`Pos`] (0: unplaced).
337fn span_pos(span: Span) -> Pos {
338    if span == (0, 0) {
339        0
340    } else {
341        span.0 + 1
342    }
343}
344
345/// Keep the collision whose reported declaration comes first in the source;
346/// one with no position is reported only when no placed one is found.
347fn note_redeclared(found: &mut Option<Binding>, b: &Binding) {
348    let key = |b: &Binding| if b.pos == 0 { Pos::MAX } else { b.pos };
349    if !found.as_ref().is_some_and(|f| key(b) >= key(f)) {
350        *found = Some(b.clone());
351    }
352}
353
354/// The later of two colliding declarations — the one V8 reports.
355fn later<'a>(a: &'a Binding, b: &'a Binding) -> &'a Binding {
356    if a.pos > b.pos {
357        a
358    } else {
359        b
360    }
361}
362
363/// Note every collision in the statement list `stmts` and the lists nested in
364/// it, and hand back the list's own lexical declarations.
365fn redeclarations(stmts: &[Stmt], found: &mut Option<Binding>) -> Vec<Binding> {
366    let mut lexical: Vec<Binding> = Vec::new();
367    let mut functions: Vec<Binding> = Vec::new();
368    let mut declare_lexical = |b: Binding, found: &mut Option<Binding>| {
369        if let Some(prev) = lexical.iter().find(|l| l.name == b.name) {
370            note_redeclared(found, later(prev, &b));
371        }
372        lexical.push(b);
373    };
374    for st in stmts {
375        match &st.kind {
376            StmtKind::Decl { kind, decls } if !matches!(kind, DeclKind::Var) => {
377                for d in decls {
378                    for b in bindings_at(&d.target, &d.bound) {
379                        declare_lexical(b, found);
380                    }
381                }
382            }
383            StmtKind::ClassDecl(c) => {
384                if let Some(n) = &c.name {
385                    let pos = span_pos(c.span);
386                    let end = if pos == 0 { 0 } else { c.span.1 + 1 };
387                    declare_lexical(
388                        Binding {
389                            name: n.clone(),
390                            pos,
391                            end,
392                        },
393                        found,
394                    );
395                }
396            }
397            StmtKind::FuncDecl { name, span, .. } => functions.push(Binding {
398                name: name.clone(),
399                pos: span_pos(*span),
400                end: 0,
401            }),
402            _ => {}
403        }
404    }
405    // A function declaration and a lexical binding of the same name cannot
406    // share a scope, whichever order they appear in.
407    for f in &functions {
408        for l in lexical.iter().filter(|l| l.name == f.name) {
409            note_redeclared(found, later(f, l));
410        }
411    }
412    // A `var` anywhere below hoists PAST any block between it and its function
413    // scope, so it collides with a lexical name declared here.
414    let mut vars: Vec<Binding> = Vec::new();
415    for st in stmts {
416        collect_var_bindings(st, &mut vars);
417    }
418    for l in &lexical {
419        for v in vars.iter().filter(|v| v.name == l.name) {
420            note_redeclared(found, later(v, l));
421        }
422    }
423    // Each nested statement list is its own scope.
424    for st in stmts {
425        nested_redeclarations(&st.kind, found);
426    }
427    lexical
428}
429
430/// [`check_early_errors`] for a function body, which also may not redeclare a
431/// parameter lexically (`function f(a) { let a }`, 15.2.1).
432fn check_function_body(params: &[Param], body: &[Stmt]) -> Result<(), String> {
433    let mut found = None;
434    let lexical = redeclarations(body, &mut found);
435    let mut names = Vec::new();
436    for p in params {
437        pattern_names(&p.pattern, &mut names);
438    }
439    for l in lexical.iter().filter(|l| names.contains(&l.name)) {
440        note_redeclared(&mut found, l);
441    }
442    check_redeclared(found)
443}
444
445fn already_declared(name: &str) -> String {
446    format!("SyntaxError: Identifier '{name}' has already been declared")
447}
448
449/// Recurse into the statement lists that form their own scopes. A function
450/// BODY is checked when that function is compiled (`build_function`), so the
451/// walk does not descend into one here.
452fn nested_redeclarations(k: &StmtKind, found: &mut Option<Binding>) {
453    match k {
454        StmtKind::Block(b) => {
455            redeclarations(b, found);
456        }
457        StmtKind::If { cons, alt, .. } => {
458            nested_redeclarations(&cons.kind, found);
459            if let Some(a) = alt {
460                nested_redeclarations(&a.kind, found);
461            }
462        }
463        StmtKind::While { body, .. }
464        | StmtKind::DoWhile { body, .. }
465        | StmtKind::With { body, .. }
466        | StmtKind::Labeled { body, .. } => nested_redeclarations(&body.kind, found),
467        // A `for (let …)` head is its own scope, and a `var` in the body hoists
468        // THROUGH it onto the same name — a collision no block-level check sees.
469        StmtKind::ForOf {
470            decl_kind: Some(kind),
471            target,
472            body,
473            ..
474        }
475        | StmtKind::ForIn {
476            decl_kind: Some(kind),
477            target,
478            body,
479            ..
480        } if !matches!(kind, DeclKind::Var) => {
481            let mut head = Vec::new();
482            pattern_names(target, &mut head);
483            let mut vars = Vec::new();
484            collect_var_bindings(body, &mut vars);
485            for v in vars.iter().filter(|v| head.contains(&v.name)) {
486                note_redeclared(found, v);
487            }
488            nested_redeclarations(&body.kind, found);
489        }
490        StmtKind::ForOf { body, .. } | StmtKind::ForIn { body, .. } => {
491            nested_redeclarations(&body.kind, found)
492        }
493        StmtKind::For { body, .. } => nested_redeclarations(&body.kind, found),
494        StmtKind::Try {
495            block,
496            handler,
497            finalizer,
498        } => {
499            redeclarations(block, found);
500            if let Some((param, h)) = handler {
501                // The catch parameter and the handler body's lexical
502                // declarations share a scope (14.15.1).
503                let lexical = redeclarations(h, found);
504                let mut names = Vec::new();
505                if let Some(p) = param {
506                    pattern_names(p, &mut names);
507                }
508                for l in lexical.iter().filter(|l| names.contains(&l.name)) {
509                    note_redeclared(found, l);
510                }
511            }
512            if let Some(f) = finalizer {
513                redeclarations(f, found);
514            }
515        }
516        StmtKind::Switch { cases, .. } => {
517            // Every case shares ONE block scope, so their statements are
518            // checked together rather than case by case.
519            let all: Vec<Stmt> = cases.iter().flat_map(|c| c.body.clone()).collect();
520            redeclarations(&all, found);
521        }
522        _ => {}
523    }
524}
525
526/// Compile a parsed program. `debug` enables per-statement DAP line markers.
527pub fn compile(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
528    let mut c = Compiler {
529        opt_chain: Vec::new(),
530        debug,
531        // Under `--dap` the debugger reads scopes by name out of the host, and a
532        // slot has no name, so a debug run keeps every local a binding.
533        slots: if debug {
534            Default::default()
535        } else {
536            crate::slots::plan(&[], stmts, true)
537        },
538        strict: has_use_strict(stmts),
539        ..Default::default()
540    };
541    check_early_errors(stmts)?;
542    let mut b = ChunkBuilder::new();
543    // Hoist function declarations to the top (JS function hoisting).
544    c.hoist_vars(&mut b, stmts)?;
545    c.hoist_lexical(&mut b, stmts);
546    c.hoist_funcs(&mut b, stmts)?;
547    c.compile_stmts(&mut b, stmts)?;
548    Ok(Program {
549        main: c.finish_chunk(b),
550        functions: c.functions,
551        tries: c.tries,
552        strict: c.strict,
553        source: None,
554    })
555}
556
557/// Compile leaving the value of the final top-level expression statement on the
558/// stack (the program's completion value), for `eval`/`vm.runInThisContext`. A
559/// non-expression final statement leaves nothing (→ `undefined`).
560pub fn compile_completion(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
561    compile_completion_strict(stmts, debug, false, false)
562}
563
564/// As [`compile_completion`], but with the CALLER's strictness folded in.
565///
566/// A direct `eval` inherits it (19.2.1.1 step 10), which decides every strict
567/// early error inside the evaluated source: `eval('delete x')` in strict code
568/// is a SyntaxError, and compiling the source on its own could not see that.
569pub fn compile_completion_strict(
570    stmts: &[Stmt],
571    debug: bool,
572    caller_strict: bool,
573    in_with: bool,
574) -> Result<Program, String> {
575    let mut c = Compiler {
576        opt_chain: Vec::new(),
577        debug,
578        strict: caller_strict || has_use_strict(stmts),
579        // A direct `eval` inside a `with` body names things through the `with`
580        // object too.
581        with_depth: usize::from(in_with),
582        ..Default::default()
583    };
584    check_early_errors(stmts)?;
585    let mut b = ChunkBuilder::new();
586    // The completion register, declared before anything can write it. A name no
587    // source text can spell, like the `.param<n>` slots a destructured
588    // parameter uses.
589    c.name_const(&mut b, COMPLETION_SLOT);
590    b.emit(Op::LoadUndef, 0);
591    b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
592    b.emit(Op::Pop, 0);
593    c.completion = true;
594    c.hoist_vars(&mut b, stmts)?;
595    // The eval's own `let`/`const`/`class` exist from its start, in their dead
596    // zone (19.2.1.3 EvalDeclarationInstantiation step 15), as a script's do.
597    c.hoist_lexical(&mut b, stmts);
598    c.hoist_funcs(&mut b, stmts)?;
599    c.compile_stmts(&mut b, stmts)?;
600    c.completion = false;
601    c.name_const(&mut b, COMPLETION_SLOT);
602    b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
603    Ok(Program {
604        main: c.finish_chunk(b),
605        functions: c.functions,
606        tries: c.tries,
607        strict: c.strict,
608        source: None,
609    })
610}
611
612impl Compiler {
613    /// `UpdateEmpty(result, undefined)` — the step `if`, every loop, `try` and
614    /// `switch` apply to their own completion (14.6.7, 14.7.x, 14.11.x,
615    /// 14.15.3). Each therefore always produces a VALUE: `1; if(0){2}` is
616    /// `undefined`, not 1, and a `break` out of a loop body discards what
617    /// earlier iterations accumulated. A block, a labelled statement, `;` and
618    /// every declaration propagate empty instead and are not reset here.
619    fn reset_completion_for_finalizer_exit(&mut self, b: &mut ChunkBuilder) {
620        let Some((own, outer)) = self.finalizer_completion.clone() else {
621            return;
622        };
623        self.name_const(b, &outer);
624        self.name_const(b, &own);
625        b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
626        b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
627        b.emit(Op::Pop, 0);
628    }
629
630    /// The register the running statement list accumulates its value in.
631    fn cslot(&self) -> String {
632        if self.completion_slot.is_empty() {
633            COMPLETION_SLOT.to_string()
634        } else {
635            self.completion_slot.clone()
636        }
637    }
638
639    fn reset_completion(&mut self, b: &mut ChunkBuilder) {
640        if !self.completion {
641            return;
642        }
643        let slot = self.cslot();
644        self.name_const(b, &slot);
645        b.emit(Op::LoadUndef, 0);
646        b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
647        b.emit(Op::Pop, 0);
648    }
649}
650
651/// The hidden binding a completion-valued Script accumulates into. Leading dot:
652/// no source text can name it, so nothing a script declares can collide.
653const COMPLETION_SLOT: &str = ".completion";
654
655/// Does this statement list open with a `"use strict"` directive prologue?
656///
657/// A directive prologue is the run of leading statements that are nothing but a
658/// string literal, so `"use strict"` counts only while every statement before it
659/// is also one.
660fn has_use_strict(stmts: &[Stmt]) -> bool {
661    for s in stmts {
662        match &s.kind {
663            StmtKind::Expr(e) => match e {
664                Expr::Str(v) if v == "use strict" => return true,
665                Expr::Str(_) => continue,
666                _ => return false,
667            },
668            _ => return false,
669        }
670    }
671    false
672}
673
674/// The callee's source text, re-printed from its AST the way V8's `CallPrinter`
675/// does for the `TypeError` a failed call raises: `o.a.b`, `o[k]`, `"s".x`,
676/// `3.x`, `o?.a?.zz`. A string-literal computed access normalizes to dot form
677/// (`o['a']` prints `o.a`), which is what node reports.
678///
679/// `None` for any shape this does not print faithfully — the caller then keeps
680/// the bare method name it already used, so an unprinted shape is never given
681/// invented text.
682fn callee_text(e: &Expr) -> Option<String> {
683    Some(match e {
684        Expr::Ident(n) => n.clone(),
685        Expr::This => "this".into(),
686        Expr::Number(n) => crate::host::fmt_number(*n),
687        Expr::Str(s) => format!("\"{s}\""),
688        Expr::True => "true".into(),
689        Expr::False => "false".into(),
690        Expr::Null => "null".into(),
691        Expr::Undefined => "undefined".into(),
692        // V8's parser folds `-<number>` into one literal, so it prints bare.
693        Expr::Unary(UnOp::Neg, inner) if matches!(**inner, Expr::Number(_)) => match **inner {
694            Expr::Number(n) => crate::host::fmt_number(-n),
695            _ => return None,
696        },
697        Expr::Regex(body, flags) => format!("/{body}/{flags}"),
698        // `CallPrinter::VisitArrayLiteral`: the elements comma-joined with no
699        // space, a hole empty, a spread parenthesized.
700        Expr::Array(items) => {
701            let parts: Option<Vec<String>> = items
702                .iter()
703                .map(|item| match item {
704                    Expr::Hole => Some(String::new()),
705                    Expr::Spread(inner) => Some(format!("(...{})", callee_text(inner)?)),
706                    other => callee_text(other),
707                })
708                .collect();
709            format!("[{}]", parts?.join(","))
710        }
711        // A template with no substitutions is a string literal to V8. One with
712        // a single substitution prints just that substitution (`` `a${n}b` ``
713        // is reported as `n`).
714        Expr::Template { quasis, exprs } if exprs.is_empty() => {
715            format!("\"{}\"", quasis.concat())
716        }
717        Expr::Template { exprs, .. } if exprs.len() == 1 => callee_text(&exprs[0])?,
718        // Values V8 does not print from source: a function, arrow or class
719        // literal, a `new` expression, a BigInt literal.
720        Expr::Function { .. } | Expr::Class(_) | Expr::New { .. } | Expr::BigInt(_) => {
721            "(intermediate value)".into()
722        }
723        // A conditional is three unprinted values in a row.
724        Expr::Conditional { .. } => {
725            "(intermediate value)(intermediate value)(intermediate value)".into()
726        }
727        // An assignment is reported by its TARGET: `(o.a = 1)()` is `o.a`.
728        Expr::Assign { target, .. } => callee_text(target)?,
729        Expr::Unary(op, inner) => {
730            let op = match op {
731                UnOp::Neg => "-",
732                UnOp::Pos => "+",
733                UnOp::Not => "!",
734                UnOp::BitNot => "~",
735                UnOp::TypeOf => "typeof ",
736                UnOp::Void => "void ",
737                UnOp::Delete => "delete ",
738            };
739            format!("({op}{})", callee_text(inner)?)
740        }
741        Expr::Update { op, prefix, target } => {
742            let op = match op {
743                UpdateOp::Inc => "++",
744                UpdateOp::Dec => "--",
745            };
746            let t = callee_text(target)?;
747            if *prefix {
748                format!("({op}{t})")
749            } else {
750                format!("({t}{op})")
751            }
752        }
753        Expr::Binary(op, l, r) => {
754            let op = match op {
755                BinOp::Add => "+",
756                BinOp::Sub => "-",
757                BinOp::Mul => "*",
758                BinOp::Div => "/",
759                BinOp::Mod => "%",
760                BinOp::Pow => "**",
761                BinOp::Lt => "<",
762                BinOp::Le => "<=",
763                BinOp::Gt => ">",
764                BinOp::Ge => ">=",
765                BinOp::EqEqEq => "===",
766                BinOp::NeEqEq => "!==",
767                BinOp::EqEq => "==",
768                BinOp::NeEq => "!=",
769                BinOp::BitAnd => "&",
770                BinOp::BitOr => "|",
771                BinOp::BitXor => "^",
772                BinOp::Shl => "<<",
773                BinOp::Shr => ">>",
774                BinOp::UShr => ">>>",
775                BinOp::In => "in",
776                BinOp::InstanceOf => "instanceof",
777            };
778            format!("({} {op} {})", callee_text(l)?, callee_text(r)?)
779        }
780        Expr::Logical(op, l, r) => {
781            let op = match op {
782                LogicalOp::And => "&&",
783                LogicalOp::Or => "||",
784                LogicalOp::Nullish => "??",
785            };
786            format!("({} {op} {})", callee_text(l)?, callee_text(r)?)
787        }
788        Expr::Object(props) if props.is_empty() => "{}".into(),
789        // A non-empty OBJECT literal is the one shape V8 will not render from
790        // source: `({a: 1})()` is `{(intermediate value)} is not a function`,
791        // where an array literal or a template is printed as written. Without
792        // this the message fell back to the VALUE, which renders
793        // `[object Object]` — a spelling node never produces here.
794        Expr::Object(_) => "{(intermediate value)}".into(),
795        Expr::Member {
796            object,
797            property,
798            optional,
799            ..
800        } => {
801            let dot = if *optional { "?." } else { "." };
802            format!("{}{dot}{property}", callee_text(object)?)
803        }
804        Expr::Index {
805            object,
806            index,
807            optional,
808            ..
809        } => {
810            let obj = callee_text(object)?;
811            // A string-literal key prints as a dot access whatever it spells —
812            // V8 reports `o["has space"]` as `o.has space` and `o["5"]` as `o.5`.
813            // A substitution-free template is a string literal too.
814            let literal = match &**index {
815                Expr::Str(k) => Some(k.clone()),
816                Expr::Template { quasis, exprs } if exprs.is_empty() => Some(quasis.concat()),
817                _ => None,
818            };
819            if let Some(k) = literal {
820                let dot = if *optional { "?." } else { "." };
821                return Some(format!("{obj}{dot}{k}"));
822            }
823            let idx = callee_text(index)?;
824            let open = if *optional { "?.[" } else { "[" };
825            format!("{obj}{open}{idx}]")
826        }
827        // V8 prints a call in a callee position as `f(...)`, whatever its
828        // arguments were: `require('fs').nope()` reports `require(...).nope`.
829        Expr::Call { func, .. } => format!("{}(...)", callee_text(func)?),
830        // A one-element sequence is the parser's marker for a PARENTHESIZED
831        // optional chain, which V8 does not print: `(o?.a).b()` reports
832        // `(intermediate value).b`.
833        Expr::Sequence(items) if items.len() == 1 => "(intermediate value)".into(),
834        Expr::Sequence(items) => {
835            let parts: Option<Vec<String>> = items.iter().map(callee_text).collect();
836            format!("({})", parts?.join(" , "))
837        }
838        _ => return None,
839    })
840}
841
842fn argc(n: usize) -> Result<u8, String> {
843    u8::try_from(n).map_err(|_| "too many arguments (>255) for one call".to_string())
844}
845
846/// Does this expression already leave a `Value::Bool` on the stack? A condition
847/// that does needs no `TRUTHY` call: `JumpIfFalse` reads the boolean directly.
848///
849/// The gain is one host round-trip per condition evaluation — `for (let i = 0;
850/// i < n; i++)` paid it on every iteration — and it also puts the comparison
851/// immediately before the jump that consumes it, which is what fusevm's block
852/// JIT requires of a bool-producing op (`bool_is_consumed_in_place`).
853///
854/// Every arm listed here is a lowering that ends in a `Bool`: the relational
855/// ops go to `Op::Num{Lt,Le,Gt,Ge}` (the numeric hook's `relational` returns a
856/// Rust `bool`), the equality ops to `STRICT_EQ`/`LOOSE_EQ`, `in` to
857/// `CONTAINS`, `instanceof` to `INSTANCEOF`, and `!`/`!=`/`!==` end in
858/// `Op::LogNot`. Anything else — including `&&`/`||`/`??`, which evaluate to an
859/// OPERAND and not to a boolean — keeps the call.
860fn yields_bool(e: &Expr) -> bool {
861    match e {
862        Expr::True | Expr::False => true,
863        Expr::Unary(UnOp::Not, _) | Expr::Unary(UnOp::Delete, _) => true,
864        Expr::Binary(op, _, _) => matches!(
865            op,
866            BinOp::Lt
867                | BinOp::Le
868                | BinOp::Gt
869                | BinOp::Ge
870                | BinOp::EqEq
871                | BinOp::NeEq
872                | BinOp::EqEqEq
873                | BinOp::NeEqEq
874                | BinOp::In
875                | BinOp::InstanceOf
876        ),
877        _ => false,
878    }
879}
880
881impl Compiler {
882    // ── emit helpers ─────────────────────────────────────────────────────
883    fn name_const(&self, b: &mut ChunkBuilder, s: &str) {
884        let k = b.add_constant(Value::str(s));
885        b.emit(Op::LoadConst(k), 0);
886    }
887    fn strlit(&self, b: &mut ChunkBuilder, s: &str) {
888        let k = b.add_constant(Value::str(s));
889        b.emit(Op::LoadConst(k), 0);
890        b.emit(Op::CallBuiltin(ops::MKSTR, 1), 0);
891    }
892    fn tmp_name(&mut self, tag: &str) -> String {
893        let n = format!(".{tag}{}", self.tmp);
894        self.tmp += 1;
895        n
896    }
897
898    /// Emit MKFUNC for a compiled function template and leave the closure on the
899    /// stack.
900    fn emit_mkfunc(&self, b: &mut ChunkBuilder, def_id: usize) {
901        b.emit(Op::LoadInt(def_id as i64), 0);
902        b.emit(Op::CallBuiltin(ops::MKFUNC, 1), 0);
903    }
904
905    /// Emit the `var` hoisting for one function (or program) scope.
906    ///
907    /// A `var` binding exists from the moment its scope is entered, so
908    /// `f(){ x; var x = 1 }` reads `undefined` where a `let` would throw. The
909    /// walk therefore descends through every block, loop, `switch`, `try` and
910    /// label — `var` ignores block scope — but stops at a nested function, which
911    /// begins a scope of its own. Only the binding is created here; the
912    /// initialiser still runs where it is written.
913    ///
914    /// Emitted BEFORE [`Self::hoist_funcs`] so a function declaration overwrites
915    /// the `undefined` rather than the other way round, which is the order the
916    /// spec instantiates them in.
917    fn hoist_vars(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
918        let mut names = Vec::new();
919        for s in stmts {
920            collect_var_names(s, &mut names);
921        }
922        for n in names {
923            // A slotted local is its slot, which already reads `undefined`
924            // before its first write, so there is no binding to create.
925            if self.slot_of(&n).is_some() {
926                continue;
927            }
928            self.name_const(b, &n);
929            b.emit(Op::CallBuiltin(ops::HOIST_VAR, 1), 0);
930            b.emit(Op::Pop, 0);
931        }
932        Ok(())
933    }
934
935    /// Declare every `let`/`const`/`class` named DIRECTLY in `stmts` as
936    /// uninitialized, at the top of the scope those statements form.
937    ///
938    /// Without it a lexical binding simply did not exist until its declaration
939    /// ran, so a read above it either found an OUTER binding of the same name —
940    /// `let x = 1; { x; let x = 2 }` read `1` where node throws — or reported
941    /// the name as undefined, which is the message for a typo rather than for
942    /// the temporal dead zone. Nested blocks are NOT walked: each opens its own
943    /// scope and hoists its own.
944    fn hoist_lexical(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) {
945        for s in stmts {
946            match &s.kind {
947                StmtKind::Decl {
948                    kind: DeclKind::Let | DeclKind::Const,
949                    decls,
950                } => {
951                    for d in decls {
952                        for name in binding_names(&d.target) {
953                            self.name_const(b, &name);
954                            b.emit(Op::CallBuiltin(ops::HOIST_TDZ, 1), 0);
955                            b.emit(Op::Pop, 0);
956                        }
957                    }
958                }
959                StmtKind::ClassDecl(c) => {
960                    if let Some(name) = &c.name {
961                        self.name_const(b, name);
962                        b.emit(Op::CallBuiltin(ops::HOIST_TDZ, 1), 0);
963                        b.emit(Op::Pop, 0);
964                    }
965                }
966                _ => {}
967            }
968        }
969    }
970
971    fn hoist_funcs(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
972        self.hoist_funcs_in(b, stmts, false)
973    }
974
975    /// `in_block` marks a declaration that is nested in a BLOCK rather than at
976    /// the top of a function body or script. Only that case is affected by
977    /// strictness.
978    fn hoist_funcs_in(
979        &mut self,
980        b: &mut ChunkBuilder,
981        stmts: &[Stmt],
982        in_block: bool,
983    ) -> Result<(), String> {
984        for s in stmts {
985            if let StmtKind::FuncDecl {
986                name,
987                params,
988                body,
989                is_generator,
990                is_async,
991                span,
992                ..
993            } = &s.kind
994            {
995                let def_id = self.build_function(name, params, body, *is_generator, *is_async)?;
996                self.functions[def_id].1.span = *span;
997                self.emit_mkfunc(b, def_id);
998                // A function declaration in a BLOCK is block-scoped (14.2.x);
999                // only Annex B.3.3's sloppy-mode legacy hoists it to the
1000                // enclosing FUNCTION scope as well. Hoisting unconditionally
1001                // made `function o() { { function g() {} } return typeof g }`
1002                // answer `"function"` under `'use strict'`, where node says
1003                // `"undefined"`.
1004                let mode = if in_block && self.strict {
1005                    BindMode::Lexical
1006                } else {
1007                    BindMode::Var
1008                };
1009                self.declare_as(b, &Expr::Ident(name.clone()), mode);
1010            }
1011        }
1012        Ok(())
1013    }
1014
1015    fn compile_stmts(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
1016        for s in stmts {
1017            self.compile_stmt(b, s)?;
1018        }
1019        Ok(())
1020    }
1021
1022    fn compile_stmt(&mut self, b: &mut ChunkBuilder, s: &Stmt) -> Result<(), String> {
1023        let start = b.current_pos();
1024        let r = self.compile_stmt_kind(b, s);
1025        self.mark_pos(b, start, s.pos, PosScope::Statement);
1026        r
1027    }
1028
1029    fn compile_stmt_kind(&mut self, b: &mut ChunkBuilder, s: &Stmt) -> Result<(), String> {
1030        if self.debug && s.line != 0 {
1031            b.emit(Op::LoadInt(s.line as i64), 0);
1032            b.emit(Op::CallBuiltin(ops::DBG_LINE, 1), 0);
1033            b.emit(Op::Pop, 0);
1034        }
1035        match &s.kind {
1036            StmtKind::Expr(e) => {
1037                self.compile_expr(b, e)?;
1038                if self.completion {
1039                    let slot = self.cslot();
1040                    self.name_const(b, &slot);
1041                    b.emit(Op::Swap, 0);
1042                    b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
1043                }
1044                b.emit(Op::Pop, 0);
1045            }
1046            StmtKind::Empty => {}
1047            StmtKind::FuncDecl { .. } => {} // hoisted at block entry
1048            // `esm::lower` replaces module declarations before compilation; one
1049            // reaching here is an `import`/`export` outside module code.
1050            StmtKind::Import(_) => {
1051                return Err("SyntaxError: Cannot use import statement outside a module".to_string())
1052            }
1053            StmtKind::Export(_) => return Err("SyntaxError: Unexpected token 'export'".to_string()),
1054            StmtKind::ClassDecl(node) => {
1055                self.compile_class(b, node)?;
1056                // Bind the class to its name in the current scope.
1057                if let Some(name) = &node.name {
1058                    self.declare(b, &Expr::Ident(name.clone()));
1059                } else {
1060                    b.emit(Op::Pop, 0);
1061                }
1062            }
1063            StmtKind::Decl { kind, decls } => {
1064                let mode = bind_mode(*kind);
1065                for d in decls {
1066                    // `var x;` with no initialiser names a binding that scope
1067                    // entry already created, and must NOT reset it — in
1068                    // `function f(a) { var a; }` the parameter stands.
1069                    if d.init.is_none() && *kind == DeclKind::Var {
1070                        continue;
1071                    }
1072                    match &d.init {
1073                        Some(v) => {
1074                            self.compile_expr(b, v)?;
1075                            // Name inference: `const f = () => {}` / `= function(){}`
1076                            // / `= class {}` gives the function/class the name `f`.
1077                            if let Expr::Ident(name) = &d.target {
1078                                self.infer_name(b, v, name);
1079                            }
1080                        }
1081                        None => {
1082                            b.emit(Op::LoadUndef, 0);
1083                        }
1084                    }
1085                    // 13.3.1.1: a `var`/`let`/`const` may not BIND `eval` or
1086                    // `arguments` in strict code.
1087                    if self.strict {
1088                        for n in binding_names(&d.target) {
1089                            if RESERVED_IN_STRICT.contains(&n.as_str()) {
1090                                return Err(strict_reserved_error());
1091                            }
1092                        }
1093                    }
1094                    self.destructure_src = d.init.as_ref().and_then(destructure_source_text);
1095                    self.destructure_is_decl = true;
1096                    let r = self.compile_bind(b, &d.target, mode);
1097                    self.destructure_src = None;
1098                    self.destructure_is_decl = false;
1099                    r?;
1100                }
1101            }
1102            StmtKind::Block(body) => {
1103                // A block that declares nothing lexical has nothing to put in a
1104                // scope, and opening one costs an `EnvData` allocation and free
1105                // every time control enters the block — once per iteration when
1106                // the block is a loop body, which is where most of them are.
1107                let scoped = crate::capture::block_needs_scope(body);
1108                if scoped {
1109                    self.emit_push_scope(b);
1110                }
1111                self.hoist_lexical(b, body);
1112                self.hoist_funcs_in(b, body, true)?;
1113                self.compile_stmts(b, body)?;
1114                if scoped {
1115                    self.emit_pop_scope(b);
1116                }
1117            }
1118            StmtKind::If { test, cons, alt } => {
1119                self.reset_completion(b);
1120                self.compile_if(b, test, cons, alt)?
1121            }
1122            StmtKind::While { test, body } => {
1123                self.reset_completion(b);
1124                self.compile_while(b, test, body)?
1125            }
1126            StmtKind::With { object, body } => {
1127                self.reset_completion(b);
1128                self.compile_expr(b, object)?;
1129                b.emit(Op::CallBuiltin(ops::WITH_PUSH, 1), 0);
1130                b.emit(Op::Pop, 0);
1131                self.scope_depth += 1;
1132                self.with_depth += 1;
1133                let r = self.compile_stmt(b, body);
1134                self.with_depth -= 1;
1135                r?;
1136                self.emit_pop_scope(b);
1137            }
1138            StmtKind::DoWhile { body, test } => {
1139                self.reset_completion(b);
1140                self.compile_do_while(b, body, test)?
1141            }
1142            StmtKind::For {
1143                init,
1144                test,
1145                update,
1146                body,
1147            } => {
1148                self.reset_completion(b);
1149                self.compile_for(b, init, test, update, body)?
1150            }
1151            StmtKind::ForOf {
1152                decl_kind,
1153                target,
1154                iter,
1155                body,
1156                is_await,
1157            } => {
1158                self.reset_completion(b);
1159                let mode = decl_kind.map(bind_mode).unwrap_or(BindMode::Assign);
1160                if *is_await {
1161                    self.compile_for_await(b, mode, target, iter, body)?
1162                } else {
1163                    self.compile_for_of(b, mode, target, iter, body)?
1164                }
1165            }
1166            StmtKind::ForIn {
1167                decl_kind,
1168                target,
1169                object,
1170                body,
1171            } => {
1172                self.reset_completion(b);
1173                let mode = decl_kind.map(bind_mode).unwrap_or(BindMode::Assign);
1174                self.compile_for_in(b, mode, target, object, body)?
1175            }
1176            StmtKind::Switch { disc, cases } => {
1177                self.reset_completion(b);
1178                self.compile_switch(b, disc, cases)?
1179            }
1180            StmtKind::Return(e) => {
1181                match e {
1182                    Some(e) => self.compile_expr(b, e)?,
1183                    None => {
1184                        b.emit(Op::LoadUndef, 0);
1185                    }
1186                }
1187                // A `return` out of a `for…of` is an abrupt completion, and
1188                // 7.4.9 `IteratorClose` runs the iterator's `return` for it —
1189                // which is what makes a generator's `finally` run. `break` and
1190                // `continue` already closed theirs; a `return` walked away and
1191                // left the iterator suspended forever.
1192                self.emit_close_iters_under_value(b);
1193                b.emit(Op::CallBuiltin(ops::SIG_RETURN, 1), 0);
1194            }
1195            StmtKind::Labeled { label, body } => self.compile_labeled(b, label, body)?,
1196            StmtKind::Break(label) => {
1197                let idx = match label {
1198                    // `break outer`: the nearest enclosing context carrying that label.
1199                    Some(name) => self
1200                        .loops
1201                        .iter()
1202                        .rposition(|c| c.label.as_deref() == Some(name.as_str()))
1203                        .ok_or_else(|| format!("SyntaxError: Undefined label '{name}'"))?,
1204                    None => self
1205                        .loops
1206                        .len()
1207                        .checked_sub(1)
1208                        .ok_or("SyntaxError: Illegal break statement")?,
1209                };
1210                if idx >= self.chunk_loop_base {
1211                    self.emit_unwind_scopes(b, self.loops[idx].break_depth);
1212                    self.emit_close_iters(b, self.loops[idx].iter_depth);
1213                    let j = b.emit(Op::Jump(0), 0);
1214                    self.loops[idx].breaks.push(j);
1215                } else {
1216                    self.reset_completion_for_finalizer_exit(b);
1217                    self.emit_signal_jump(b, ops::SIG_BREAK, label.as_deref());
1218                }
1219            }
1220            StmtKind::Continue(label) => {
1221                let idx = match label {
1222                    // `continue outer`: the labeled loop (a label on a non-loop
1223                    // cannot catch `continue`).
1224                    Some(name) => self
1225                        .loops
1226                        .iter()
1227                        .rposition(|c| {
1228                            c.catches_continue && c.label.as_deref() == Some(name.as_str())
1229                        })
1230                        .ok_or_else(|| {
1231                            // A label that exists but names a non-loop is a different
1232                            // error from one that does not exist.
1233                            if self.loops.iter().any(|c| c.label.as_deref() == Some(name.as_str())) {
1234                                format!(
1235                                    "SyntaxError: Illegal continue statement: '{name}' does not denote an iteration statement"
1236                                )
1237                            } else {
1238                                format!("SyntaxError: Undefined label '{name}'")
1239                            }
1240                        })?,
1241                    None => self
1242                        .loops
1243                        .iter()
1244                        .rposition(|c| c.catches_continue)
1245                        .ok_or("SyntaxError: Illegal continue statement: no surrounding iteration statement")?,
1246                };
1247                if idx >= self.chunk_loop_base {
1248                    self.emit_unwind_scopes(b, self.loops[idx].continue_depth);
1249                    self.emit_close_iters(b, self.loops[idx].iter_depth);
1250                    let j = b.emit(Op::Jump(0), 0);
1251                    self.loops[idx].continues.push(j);
1252                } else {
1253                    self.reset_completion_for_finalizer_exit(b);
1254                    self.emit_signal_jump(b, ops::SIG_CONTINUE, label.as_deref());
1255                }
1256            }
1257            StmtKind::Throw(e) => {
1258                self.compile_expr(b, e)?;
1259                b.emit(Op::CallBuiltin(ops::THROW, 1), 0);
1260            }
1261            StmtKind::Try {
1262                block,
1263                handler,
1264                finalizer,
1265            } => {
1266                self.reset_completion(b);
1267                self.compile_try(b, block, handler, finalizer)?
1268            }
1269        }
1270        Ok(())
1271    }
1272
1273    // ── binding / assignment ─────────────────────────────────────────────
1274    /// Store the value on top of the stack into `target`. `declare` chooses
1275    /// `DECLARE` (new binding) vs `SETLOCAL` (existing binding / global).
1276    fn compile_bind(
1277        &mut self,
1278        b: &mut ChunkBuilder,
1279        target: &Expr,
1280        declare: BindMode,
1281    ) -> Result<(), String> {
1282        // A DESTRUCTURING target named `eval` or `arguments` is refused in
1283        // strict code too, with its own wording — `({ a: eval } = {})` slipped
1284        // past the assignment check because it never builds an `Expr::Assign`.
1285        if self.strict {
1286            if let Expr::Ident(n) = target {
1287                if declare == BindMode::Assign && RESERVED_IN_STRICT.contains(&n.as_str()) {
1288                    return Err("SyntaxError: Invalid destructuring assignment target".to_string());
1289                }
1290            }
1291        }
1292        match target {
1293            Expr::Ident(_) => {
1294                if declare == BindMode::Assign {
1295                    self.store_simple(b, target)?;
1296                } else {
1297                    self.declare_as(b, target, declare);
1298                }
1299            }
1300            Expr::Member { .. } | Expr::Index { .. } => {
1301                self.store_simple(b, target)?;
1302            }
1303            Expr::Array(items) => self.destructure_array(b, items, declare)?,
1304            Expr::Object(props) => self.destructure_object(b, props, declare)?,
1305            Expr::Assign { target, value, .. } => {
1306                // Pattern element with a default: use it when TOS is undefined.
1307                b.emit(Op::Dup, 0);
1308                b.emit(Op::LoadUndef, 0);
1309                b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
1310                let jf = b.emit(Op::JumpIfFalse(0), 0);
1311                b.emit(Op::Pop, 0); // drop the undefined
1312                self.compile_expr(b, value)?;
1313                // 8.6.3 / 14.3.3: a destructuring default whose target is a
1314                // single binding identifier names an anonymous function after
1315                // it — `const {a = function(){}} = {}` gives `a.name === "a"`.
1316                if let Expr::Ident(n) = &**target {
1317                    self.infer_name(b, value, n);
1318                }
1319                let end = b.current_pos();
1320                b.patch_jump(jf, end);
1321                self.compile_bind(b, target, declare)?;
1322            }
1323            _ => return Err("SyntaxError: Invalid destructuring assignment target".into()),
1324        }
1325        Ok(())
1326    }
1327
1328    /// Emit a `DECLARE` of a simple name binding, consuming TOS value.
1329    fn declare(&self, b: &mut ChunkBuilder, target: &Expr) {
1330        self.declare_as(b, target, BindMode::Lexical);
1331    }
1332
1333    /// Emit the declaration op matching `mode`: block-scoped for `let`/`const`,
1334    /// function-scoped for `var` and hoisted function declarations.
1335    fn declare_as(&self, b: &mut ChunkBuilder, target: &Expr, mode: BindMode) {
1336        if let Expr::Ident(n) = target {
1337            // A slotted local has no scope entry to declare into: the binding IS
1338            // the store.
1339            if let Some(slot) = self.slot_of(n) {
1340                b.emit(Op::SetSlot(slot), 0);
1341                return;
1342            }
1343            // `var x = v` inside `with` is a PutValue on the resolved reference
1344            // (14.3.2.1): the object may supply `x`. The binding itself was
1345            // created when the function was entered.
1346            let op = match mode {
1347                BindMode::Var if self.with_depth > 0 => ops::WITH_SET,
1348                BindMode::Var => ops::DECLARE_VAR,
1349                BindMode::Const => ops::DECLARE_CONST,
1350                _ => ops::DECLARE,
1351            };
1352            self.name_const(b, n);
1353            b.emit(Op::Swap, 0);
1354            b.emit(Op::CallBuiltin(op, 2), 0);
1355            b.emit(Op::Pop, 0);
1356        }
1357    }
1358
1359    /// Emit `throw new TypeError("Assignment to constant variable.")`.
1360    ///
1361    /// A store to a `const` is a RUNTIME error, not a parse error — the spec
1362    /// puts it in SetMutableBinding (8.5.2), so `try { const c=1; c=2 } catch {}`
1363    /// has to catch it. Emitting the throw in place of the store gives exactly
1364    /// that, and costs nothing for every store that is not to a const.
1365    fn throw_const_assignment(&mut self, b: &mut ChunkBuilder) {
1366        self.throw_error(b, "TypeError", "Assignment to constant variable.");
1367    }
1368
1369    /// Bind the value on TOS to a `for-in`/`for-of` head target. Only the
1370    /// assignment form (`for (x of …)`) has a target that can be wrong: a
1371    /// non-reference is an early SyntaxError, and a CALL is evaluated and then
1372    /// refused at run time (B.3.6), once the loop has produced a value.
1373    fn bind_loop_target(
1374        &mut self,
1375        b: &mut ChunkBuilder,
1376        target: &Expr,
1377        declare: BindMode,
1378    ) -> Result<(), String> {
1379        const MSG: &str = "Invalid left-hand side in for-loop";
1380        if matches!(declare, BindMode::Assign) {
1381            match target {
1382                Expr::Ident(_)
1383                | Expr::Member { .. }
1384                | Expr::Index { .. }
1385                | Expr::Array(_)
1386                | Expr::Object(_)
1387                    if !Self::spine_has_optional(target) => {}
1388                Expr::Call { .. } if !Self::spine_has_optional(target) => {
1389                    b.emit(Op::Pop, 0); // the iteration value
1390                    self.compile_expr(b, target)?;
1391                    b.emit(Op::Pop, 0);
1392                    self.throw_error(b, "ReferenceError", MSG);
1393                    return Ok(());
1394                }
1395                _ => return Err(format!("SyntaxError: {MSG}")),
1396            }
1397        }
1398        self.compile_bind(b, target, declare)
1399    }
1400
1401    /// Emit `throw new <ctor>(<message>)` in place.
1402    fn throw_error(&mut self, b: &mut ChunkBuilder, ctor: &str, message: &str) {
1403        let e = Expr::New {
1404            callee: Box::new(Expr::Ident(ctor.into())),
1405            args: vec![Expr::Str(message.into())],
1406            pos: 0,
1407        };
1408        // `New` of a known builtin with a literal argument cannot fail to
1409        // compile, so the error path is unreachable rather than swallowed.
1410        if self.compile_expr(b, &e).is_ok() {
1411            b.emit(Op::CallBuiltin(ops::THROW, 1), 0);
1412        }
1413    }
1414
1415    /// 13.15.1 / 13.4.1: whether `target` may be assigned or updated.
1416    ///
1417    /// A non-reference target (`1 = 2`, `a + b = 1`, `x?.y = 1`) is an early
1418    /// SyntaxError. A CALL is the one web-compat exception (B.3.6): it parses,
1419    /// is evaluated, and only then throws a ReferenceError, so it is lowered
1420    /// here as call, pop, throw. `Ok(true)` means the throw was emitted and the
1421    /// caller must not store; `patterns` admits `[a] = …` / `{a} = …`.
1422    fn reject_bad_target(
1423        &mut self,
1424        b: &mut ChunkBuilder,
1425        target: &Expr,
1426        patterns: bool,
1427        message: &str,
1428    ) -> Result<bool, String> {
1429        let syntax_error = || Err(format!("SyntaxError: {message}"));
1430        match target {
1431            Expr::Ident(_) | Expr::Member { .. } | Expr::Index { .. }
1432                if Self::spine_has_optional(target) =>
1433            {
1434                syntax_error()
1435            }
1436            Expr::Ident(_) | Expr::Member { .. } | Expr::Index { .. } => Ok(false),
1437            Expr::Array(_) | Expr::Object(_) if patterns => Ok(false),
1438            Expr::Call { .. } if !Self::spine_has_optional(target) => {
1439                self.compile_expr(b, target)?;
1440                b.emit(Op::Pop, 0);
1441                self.throw_error(b, "ReferenceError", message);
1442                Ok(true)
1443            }
1444            _ => syntax_error(),
1445        }
1446    }
1447
1448    /// Store TOS into an lvalue (Ident/Member/Index), leaving nothing.
1449    fn store_simple(&mut self, b: &mut ChunkBuilder, target: &Expr) -> Result<(), String> {
1450        match target {
1451            Expr::Ident(n) => {
1452                // A slotted binding never reaches the host's scope chain, so the
1453                // host's immutable-binding check cannot see it. The slot plan is
1454                // exact about which names are const (one declaration per name,
1455                // unreachable from another chunk, simple identifiers only), so
1456                // the store is rejected here instead — at run time, as the spec
1457                // requires, since `try { const c=1; c=2 } catch {}` must CATCH
1458                // this rather than fail to parse.
1459                if self.slots.consts.contains(n) {
1460                    b.emit(Op::Pop, 0); // drop the value that will never be stored
1461                    self.throw_const_assignment(b);
1462                    return Ok(());
1463                }
1464                if let Some(slot) = self.slot_of(n) {
1465                    b.emit(Op::SetSlot(slot), 0);
1466                    return Ok(());
1467                }
1468                self.name_const(b, n);
1469                b.emit(Op::Swap, 0);
1470                // `PutValue` (6.2.5.6) on an unresolvable reference: strict code
1471                // throws `ReferenceError`, sloppy code creates a global.
1472                let op = match (self.with_depth > 0, self.strict) {
1473                    (true, true) => ops::WITH_SET_STRICT,
1474                    (true, false) => ops::WITH_SET,
1475                    (false, true) => ops::SETLOCAL_STRICT,
1476                    (false, false) => ops::SETLOCAL,
1477                };
1478                b.emit(Op::CallBuiltin(op, 2), 0);
1479                b.emit(Op::Pop, 0);
1480            }
1481            // `super.x = v` / `super[k] = v`: the parent chain's setter, else a
1482            // data write on `this` — never a write to the `super` object.
1483            Expr::Member {
1484                object, property, ..
1485            } if matches!(**object, Expr::Super) => {
1486                self.name_const(b, property); // [value, name]
1487                b.emit(Op::Swap, 0); // [name, value]
1488                b.emit(Op::CallBuiltin(ops::SUPER_SET, 2), 0);
1489                b.emit(Op::Pop, 0);
1490            }
1491            Expr::Index { object, index, .. } if matches!(**object, Expr::Super) => {
1492                self.compile_expr(b, index)?; // [value, key]
1493                b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
1494                b.emit(Op::Swap, 0); // [key, value]
1495                b.emit(Op::CallBuiltin(ops::SUPER_SET, 2), 0);
1496                b.emit(Op::Pop, 0);
1497            }
1498            Expr::Member {
1499                object, property, ..
1500            } => {
1501                self.compile_expr(b, object)?; // [value, recv]
1502                self.name_const(b, property); // [value, recv, name]
1503                b.emit(Op::Rot, 0); // [recv, name, value]
1504                b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0);
1505                b.emit(Op::Pop, 0);
1506            }
1507            Expr::Index { object, index, .. } => {
1508                self.compile_expr(b, object)?; // [value, recv]
1509                self.compile_expr(b, index)?; // [value, recv, idx]
1510                b.emit(Op::Rot, 0); // [recv, idx, value]
1511                b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0);
1512                b.emit(Op::Pop, 0);
1513            }
1514            _ => return Err("SyntaxError: Invalid destructuring assignment target".into()),
1515        }
1516        Ok(())
1517    }
1518
1519    fn destructure_array(
1520        &mut self,
1521        b: &mut ChunkBuilder,
1522        items: &[Expr],
1523        declare: BindMode,
1524    ) -> Result<(), String> {
1525        let star_idx = items
1526            .iter()
1527            .position(|e| matches!(e, Expr::Spread(_)))
1528            .map(|i| i as i64)
1529            .unwrap_or(-1);
1530        // 13.15.5.2 / 14.3.3: a rest element is the LAST element of a pattern.
1531        if star_idx >= 0 && star_idx as usize + 1 != items.len() {
1532            return Err("SyntaxError: Rest element must be last element".to_string());
1533        }
1534        b.emit(Op::LoadInt(items.len() as i64), 0);
1535        b.emit(Op::LoadInt(star_idx), 0);
1536        let at = b.current_pos();
1537        b.emit(Op::CallBuiltin(ops::UNPACK, 3), 0); // pushes items[0]..items[n-1], items[0] on top
1538                                                    // Destructuring a non-iterable names the SOURCE the same way `for-of`
1539                                                    // does: `const [x] = a` reports `a is not iterable`. The text is the one
1540                                                    // the object-pattern error already carries; a synthesized `.param<n>`
1541                                                    // slot has no source spelling and is skipped.
1542                                                    // …and only for a plain IDENTIFIER source. Node reports the TYPE for
1543                                                    // every other shape — a member, an index, a call, a nested pattern —
1544                                                    // even though the text exists, so recording one there would name an
1545                                                    // expression node never names.
1546        if let Some(src) = self
1547            .destructure_src
1548            .clone()
1549            .filter(|_| self.destructure_is_decl)
1550            .filter(|t| !t.starts_with('.'))
1551            .filter(|t| {
1552                t.starts_with('{')
1553                    || t.chars()
1554                        .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
1555            })
1556        {
1557            self.call_sites.push((at, src));
1558        }
1559        for it in items {
1560            match it {
1561                // An elided target position (`const [a, , b] = xs`) still
1562                // consumes its unpacked value; nothing is bound to it.
1563                Expr::Hole | Expr::Undefined => {
1564                    b.emit(Op::Pop, 0);
1565                }
1566                Expr::Spread(inner) => self.compile_bind(b, inner, declare)?,
1567                _ => self.compile_bind(b, it, declare)?,
1568            }
1569        }
1570        Ok(())
1571    }
1572
1573    fn destructure_object(
1574        &mut self,
1575        b: &mut ChunkBuilder,
1576        props: &[Prop],
1577        declare: BindMode,
1578    ) -> Result<(), String> {
1579        if props
1580            .iter()
1581            .rposition(|p| matches!(p, Prop::Spread(_)))
1582            .is_some_and(|i| i + 1 != props.len())
1583        {
1584            return Err("SyntaxError: Rest element must be last element".to_string());
1585        }
1586        // A NULLISH source: node names the pattern's first property and the
1587        // source expression rather than reporting the property read that failed.
1588        // Which of the two wordings it uses is decided by that first element —
1589        // a plain property names itself, a rest / computed key / empty pattern
1590        // does not, and one carrying a DEFAULT falls through to the ordinary
1591        // read error because the default is what reads it.
1592        // A leading `.` marks a compiler-generated name (a parameter slot), which
1593        // is not something the user wrote and must not be quoted back at them.
1594        if let Some(src) = self.destructure_src.take().filter(|s| !s.starts_with('.')) {
1595            let first = match props.first() {
1596                Some(Prop::KeyValue {
1597                    key: Expr::Str(k),
1598                    value,
1599                    computed: false,
1600                }) if !matches!(value, Expr::Assign { .. }) => Some(k.clone()),
1601                // A COMPUTED first key names nothing — evaluating it is what
1602                // would fail — and neither does a rest or an empty pattern.
1603                None | Some(Prop::Spread(_)) | Some(Prop::KeyValue { computed: true, .. }) => None,
1604                // A first property carrying a DEFAULT falls through: the default
1605                // is what performs the read, so node reports the read.
1606                _ => return self.destructure_object_body(b, props, declare),
1607            };
1608            self.emit_destructure_guard(b, &src, first.as_deref());
1609        }
1610        self.destructure_object_body(b, props, declare)
1611    }
1612
1613    /// `throw new TypeError(…)` when TOS is nullish, leaving TOS untouched
1614    /// otherwise.
1615    fn emit_destructure_guard(&mut self, b: &mut ChunkBuilder, src: &str, first: Option<&str>) {
1616        for (is_null, word) in [(true, "null"), (false, "undefined")] {
1617            b.emit(Op::Dup, 0);
1618            if is_null {
1619                b.emit(Op::CallBuiltin(ops::LOAD_NULL, 0), 0);
1620            } else {
1621                b.emit(Op::LoadUndef, 0);
1622            }
1623            b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
1624            let ok = b.emit(Op::JumpIfFalse(0), 0);
1625            let msg = match first {
1626                Some(k) => {
1627                    format!("Cannot destructure property '{k}' of '{src}' as it is {word}.")
1628                }
1629                None => format!("Cannot destructure '{src}' as it is {word}."),
1630            };
1631            // A real `TypeError` instance, not a bare string — the handler
1632            // reads `e.constructor.name` and `e.stack`.
1633            let e = Expr::New {
1634                callee: Box::new(Expr::Ident("TypeError".into())),
1635                args: vec![Expr::Str(msg)],
1636                pos: 0,
1637            };
1638            if self.compile_expr(b, &e).is_ok() {
1639                b.emit(Op::CallBuiltin(ops::THROW, 1), 0);
1640            }
1641            let end = b.current_pos();
1642            b.patch_jump(ok, end);
1643        }
1644    }
1645
1646    fn destructure_object_body(
1647        &mut self,
1648        b: &mut ChunkBuilder,
1649        props: &[Prop],
1650        declare: BindMode,
1651    ) -> Result<(), String> {
1652        // Object value on TOS; keep it, read each key, bind, then drop.
1653        let obj_tmp = self.tmp_name("destr");
1654        self.name_const(b, &obj_tmp);
1655        b.emit(Op::Swap, 0);
1656        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
1657        b.emit(Op::Pop, 0);
1658        // The keys a `...rest` must EXCLUDE. A statically-spelled key is known
1659        // here; a computed one (`{ [k]: v, ...rest }`) is only a value at run
1660        // time, and only collecting the static ones left every computed key in
1661        // the rest object — `const { [k]: y, ...r } = { a: 1, b: 2 }` with
1662        // `k === 'b'` put `b` in BOTH `y` and `r`.
1663        //
1664        // A computed key must still be evaluated exactly once, so its value is
1665        // stashed in a temporary as it is computed and the rest reads that
1666        // temporary rather than re-running the expression.
1667        enum Excl {
1668            Static(String),
1669            Computed(String),
1670        }
1671        let has_rest = props.iter().any(|p| matches!(p, Prop::Spread(_)));
1672        let mut named: Vec<Excl> = Vec::new();
1673        for p in props {
1674            match p {
1675                Prop::KeyValue { key, value, .. } => {
1676                    // Load obj, read key.
1677                    self.load_local(b, &obj_tmp);
1678                    self.compile_expr(b, key)?; // [obj, key]
1679                    match key {
1680                        Expr::Str(s) => named.push(Excl::Static(s.clone())),
1681                        // Only worth a temporary when a rest will read it.
1682                        _ if has_rest => {
1683                            let t = self.tmp_name("destrkey");
1684                            b.emit(Op::Dup, 0); // [obj, key, key]
1685                            self.name_const(b, &t); // [obj, key, key, name]
1686                            b.emit(Op::Swap, 0); // [obj, key, name, key]
1687                            b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0); // [obj, key, _]
1688                            b.emit(Op::Pop, 0); // [obj, key]
1689                            named.push(Excl::Computed(t));
1690                        }
1691                        _ => {}
1692                    }
1693                    b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0); // [value]
1694                    self.compile_bind(b, value, declare)?;
1695                }
1696                Prop::Spread(target) => {
1697                    self.load_local(b, &obj_tmp);
1698                    for k in &named {
1699                        match k {
1700                            Excl::Static(s) => self.strlit(b, s),
1701                            Excl::Computed(t) => self.load_local(b, t),
1702                        }
1703                    }
1704                    b.emit(Op::CallBuiltin(ops::MKARR, argc(named.len())?), 0);
1705                    b.emit(Op::CallBuiltin(ops::OBJ_REST, 2), 0); // [rest_object]
1706                    self.compile_bind(b, target, declare)?;
1707                }
1708                // Accessors never appear in a destructuring pattern.
1709                Prop::Accessor { .. } => {}
1710            }
1711        }
1712        Ok(())
1713    }
1714
1715    fn load_local(&self, b: &mut ChunkBuilder, name: &str) {
1716        if let Some(slot) = self.slot_of(name) {
1717            b.emit(Op::GetSlot(slot), 0);
1718            return;
1719        }
1720        self.name_const(b, name);
1721        let op = if self.with_depth > 0 {
1722            ops::WITH_GET
1723        } else {
1724            ops::GETLOCAL
1725        };
1726        b.emit(Op::CallBuiltin(op, 1), 0);
1727    }
1728
1729    /// The frame slot holding `name` in the chunk being emitted, if it has one.
1730    fn slot_of(&self, name: &str) -> Option<u16> {
1731        self.slots.table.get(name).copied()
1732    }
1733
1734    /// The slot for `name` if it also provably holds a Number, so `++`/`--` can
1735    /// be a native add rather than a `NUM_STEP` round-trip through the host.
1736    fn numeric_slot_of(&self, name: &str) -> Option<u16> {
1737        self.slots
1738            .numeric
1739            .contains(name)
1740            .then(|| self.slot_of(name))
1741            .flatten()
1742    }
1743
1744    // ── control flow ─────────────────────────────────────────────────────
1745    fn compile_condition(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
1746        self.compile_expr(b, e)?;
1747        if !yields_bool(e) {
1748            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
1749        }
1750        Ok(())
1751    }
1752
1753    fn compile_if(
1754        &mut self,
1755        b: &mut ChunkBuilder,
1756        test: &Expr,
1757        cons: &Stmt,
1758        alt: &Option<Box<Stmt>>,
1759    ) -> Result<(), String> {
1760        self.compile_condition(b, test)?;
1761        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
1762        self.compile_stmt(b, cons)?;
1763        if let Some(alt) = alt {
1764            let jend = b.emit(Op::Jump(0), 0);
1765            let else_start = b.current_pos();
1766            b.patch_jump(jfalse, else_start);
1767            self.compile_stmt(b, alt)?;
1768            let end = b.current_pos();
1769            b.patch_jump(jend, end);
1770        } else {
1771            let end = b.current_pos();
1772            b.patch_jump(jfalse, end);
1773        }
1774        Ok(())
1775    }
1776
1777    /// `label: stmt`. If the body is a loop, the label rides into that loop's
1778    /// `LoopCtx` (so labeled `break`/`continue` target it); otherwise a break-only
1779    /// context spans the body so `break label` can jump past it.
1780    fn compile_labeled(
1781        &mut self,
1782        b: &mut ChunkBuilder,
1783        label: &str,
1784        body: &Stmt,
1785    ) -> Result<(), String> {
1786        if matches!(
1787            body.kind,
1788            StmtKind::While { .. }
1789                | StmtKind::DoWhile { .. }
1790                | StmtKind::For { .. }
1791                | StmtKind::ForOf { .. }
1792                | StmtKind::ForIn { .. }
1793        ) {
1794            self.pending_label = Some(label.to_string());
1795            self.compile_stmt(b, body)?;
1796            // The loop claimed it; clear any residue defensively.
1797            self.pending_label = None;
1798        } else {
1799            self.loops.push(LoopCtx {
1800                breaks: Vec::new(),
1801                continues: Vec::new(),
1802                break_depth: self.scope_depth,
1803                continue_depth: self.scope_depth,
1804                iter_depth: self.iter_depth,
1805                catches_continue: false,
1806                label: Some(label.to_string()),
1807            });
1808            self.compile_stmt(b, body)?;
1809            let ctx = self.loops.pop().unwrap();
1810            let end = b.current_pos();
1811            for br in ctx.breaks {
1812                b.patch_jump(br, end);
1813            }
1814            self.redispatch_after_loop(b);
1815        }
1816        Ok(())
1817    }
1818
1819    /// After a loop/switch exits, a signal raised deeper in this chunk may still be
1820    /// pending (a LABELED `break`/`continue` for an OUTER loop). Re-dispatch it one
1821    /// level out. Emitted only when this chunk actually raises signals.
1822    fn redispatch_after_loop(&mut self, b: &mut ChunkBuilder) {
1823        if self.chunk_signals {
1824            self.emit_signal_dispatch(b);
1825        }
1826    }
1827
1828    /// `while (test) body`, lowered ROTATED: the test is emitted once as an entry
1829    /// guard and once at the bottom, so the loop closes with a CONDITIONAL
1830    /// backward branch rather than an unconditional `Jump` back to a test at the
1831    /// top.
1832    ///
1833    /// That shape is what fusevm's tracing JIT needs — it only closes a trace on
1834    /// a conditional backward branch. Emitted the other way, `--tiers` reported
1835    /// `trace-eligible=true traced=false` and `reaches native code false` for
1836    /// every `for` and `while` this frontend produced, while the same arithmetic
1837    /// written as `do { … } while (…)` — the one loop form that already ended in
1838    /// a conditional branch — reported `traced=true`. Measured on a debug build:
1839    /// `for (let i = 0; i < 3000000; i++) s += i` took 5.76s of user CPU
1840    /// unrotated and 0.02s rotated.
1841    ///
1842    /// Evaluation order and count are unchanged: a top-test loop runs the test
1843    /// `n + 1` times for `n` iterations, and so does this — one entry test, then
1844    /// one after each pass. Rotation costs one copy of the condition's code and
1845    /// saves one jump per iteration.
1846    fn compile_while(
1847        &mut self,
1848        b: &mut ChunkBuilder,
1849        test: &Expr,
1850        body: &Stmt,
1851    ) -> Result<(), String> {
1852        self.compile_condition(b, test)?;
1853        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
1854        let top = b.current_pos();
1855        self.loops.push(LoopCtx {
1856            breaks: Vec::new(),
1857            continues: Vec::new(),
1858            break_depth: self.scope_depth,
1859            continue_depth: self.scope_depth,
1860            iter_depth: self.iter_depth,
1861            catches_continue: true,
1862            label: self.pending_label.take(),
1863        });
1864        self.compile_stmt(b, body)?;
1865        // `continue` re-tests the condition, which is now the BOTTOM copy of it.
1866        let cont_target = b.current_pos();
1867        self.compile_condition(b, test)?;
1868        b.emit(Op::JumpIfTrue(top), 0);
1869        let ctx = self.loops.pop().unwrap();
1870        for c in ctx.continues {
1871            b.patch_jump(c, cont_target);
1872        }
1873        let end = b.current_pos();
1874        b.patch_jump(jfalse, end);
1875        for br in ctx.breaks {
1876            b.patch_jump(br, end);
1877        }
1878        self.redispatch_after_loop(b);
1879        Ok(())
1880    }
1881
1882    fn compile_do_while(
1883        &mut self,
1884        b: &mut ChunkBuilder,
1885        body: &Stmt,
1886        test: &Expr,
1887    ) -> Result<(), String> {
1888        let start = b.current_pos();
1889        self.loops.push(LoopCtx {
1890            breaks: Vec::new(),
1891            continues: Vec::new(),
1892            break_depth: self.scope_depth,
1893            continue_depth: self.scope_depth,
1894            iter_depth: self.iter_depth,
1895            catches_continue: true,
1896            label: self.pending_label.take(),
1897        });
1898        self.compile_stmt(b, body)?;
1899        let cont_target = b.current_pos();
1900        self.compile_condition(b, test)?;
1901        b.emit(Op::JumpIfTrue(start), 0);
1902        let ctx = self.loops.pop().unwrap();
1903        for c in ctx.continues {
1904            b.patch_jump(c, cont_target);
1905        }
1906        let end = b.current_pos();
1907        for br in ctx.breaks {
1908            b.patch_jump(br, end);
1909        }
1910        self.redispatch_after_loop(b);
1911        Ok(())
1912    }
1913
1914    fn compile_for(
1915        &mut self,
1916        b: &mut ChunkBuilder,
1917        init: &Option<Box<Stmt>>,
1918        test: &Option<Expr>,
1919        update: &Option<Expr>,
1920        body: &Stmt,
1921    ) -> Result<(), String> {
1922        // A `let`/`const` head is scoped to the loop AND re-bound per iteration, so
1923        // a closure made in one pass keeps that pass's value (ForBodyEvaluation's
1924        // CreatePerIterationEnvironment). A `var` head belongs to the function.
1925        let lexical_head = matches!(
1926            init.as_deref(),
1927            Some(Stmt {
1928                kind: StmtKind::Decl {
1929                    kind: DeclKind::Let | DeclKind::Const,
1930                    ..
1931                },
1932                ..
1933            })
1934        );
1935        // The loop's own scope is not optional — it is what keeps `let i` from
1936        // leaking past the loop or clobbering an outer `i`. The per-iteration
1937        // COPY of that scope is: only code that can CAPTURE a binding can tell
1938        // one copy per pass from one binding mutated in place, and the copy is a
1939        // whole-scope clone every iteration. A 5M-iteration counting loop spent
1940        // 17% of its samples cloning scopes that nothing could observe.
1941        let per_iteration = lexical_head;
1942        let copy_per_iteration = lexical_head
1943            && (crate::capture::stmt_captures(body)
1944                || init.as_deref().is_some_and(crate::capture::stmt_captures)
1945                || test.as_ref().is_some_and(crate::capture::expr_captures)
1946                || update.as_ref().is_some_and(crate::capture::expr_captures));
1947        if per_iteration {
1948            self.emit_push_scope(b);
1949            // The head's own bindings are in scope — and in their dead zone —
1950            // for the head itself: `for (let i = i; …)` is a ReferenceError.
1951            if let Some(init) = init.as_deref() {
1952                self.hoist_lexical(b, std::slice::from_ref(init));
1953            }
1954        }
1955        if let Some(init) = init {
1956            self.compile_stmt(b, init)?;
1957        }
1958        if copy_per_iteration {
1959            self.emit_copy_scope(b);
1960        }
1961        // Rotated, for the reason `compile_while` documents: the test as an entry
1962        // guard plus a conditional backward branch at the bottom.
1963        let jfalse = match test {
1964            Some(t) => {
1965                self.compile_condition(b, t)?;
1966                Some(b.emit(Op::JumpIfFalse(0), 0))
1967            }
1968            None => None,
1969        };
1970        let top = b.current_pos();
1971        self.loops.push(LoopCtx {
1972            breaks: Vec::new(),
1973            continues: Vec::new(),
1974            break_depth: self.scope_depth,
1975            continue_depth: self.scope_depth,
1976            iter_depth: self.iter_depth,
1977            catches_continue: true,
1978            label: self.pending_label.take(),
1979        });
1980        self.compile_stmt(b, body)?;
1981        let cont_target = b.current_pos();
1982        if copy_per_iteration {
1983            // Fresh copy BEFORE the update, so the update advances the NEXT pass's
1984            // binding and the one just captured keeps this pass's value.
1985            self.emit_copy_scope(b);
1986        }
1987        if let Some(u) = update {
1988            self.compile_expr(b, u)?;
1989            b.emit(Op::Pop, 0);
1990        }
1991        match test {
1992            Some(t) => {
1993                self.compile_condition(b, t)?;
1994                b.emit(Op::JumpIfTrue(top), 0);
1995            }
1996            // `for (;;)` has no test to branch on, so the back edge is a
1997            // constant-true CONDITIONAL branch rather than an unconditional
1998            // `Jump`. The distinction is not cosmetic: fusevm's trace compiler
1999            // only ever installs a trace closed by `JumpIfTrue`/`JumpIfFalse`
2000            // and silently declines an `Op::Jump` close, so `for (;;)` stayed
2001            // interpreted while the identical `while (true)` — which already
2002            // emitted `LoadTrue; JumpIfTrue` — reached native code. Measured on
2003            // a debug build, 3M iterations of `s += i`: 4.26s against 0.02s.
2004            None => {
2005                b.emit(Op::LoadTrue, 0);
2006                b.emit(Op::JumpIfTrue(top), 0);
2007            }
2008        }
2009        let ctx = self.loops.pop().unwrap();
2010        for c in ctx.continues {
2011            b.patch_jump(c, cont_target);
2012        }
2013        let end = b.current_pos();
2014        if let Some(jf) = jfalse {
2015            b.patch_jump(jf, end);
2016        }
2017        for br in ctx.breaks {
2018            b.patch_jump(br, end);
2019        }
2020        if per_iteration {
2021            self.emit_pop_scope(b);
2022        }
2023        self.redispatch_after_loop(b);
2024        Ok(())
2025    }
2026
2027    fn compile_for_of(
2028        &mut self,
2029        b: &mut ChunkBuilder,
2030        declare: BindMode,
2031        target: &Expr,
2032        iter: &Expr,
2033        body: &Stmt,
2034    ) -> Result<(), String> {
2035        self.compile_expr(b, iter)?;
2036        let at = b.current_pos();
2037        b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
2038                                                     // A `for-of` over a non-iterable names the SOURCE expression:
2039                                                     // `for (const x of a)` reports `a is not iterable`, not the rendering
2040                                                     // of whatever `a` held. Same table the callee-naming uses.
2041                                                     //
2042                                                     // A CALL source gets V8's combined wording, since either half could be
2043                                                     // at fault: `for (const x of f())` is `f is not a function or its
2044                                                     // return value is not iterable`. Recording the whole subject rather
2045                                                     // than a marker keeps the runtime side one string substitution.
2046        match iter {
2047            Expr::Call { func, .. } => {
2048                let name = callee_text(func).unwrap_or_else(|| "(intermediate value)".into());
2049                self.call_sites
2050                    .push((at, format!("{name} is not a function or its return value")));
2051            }
2052            _ => self.note_call_site(at, iter),
2053        }
2054        self.iter_depth += 1;
2055        self.note_iter_depth(b);
2056        let r = self.loop_over(b, declare, target, body);
2057        self.iter_depth -= 1;
2058        self.note_iter_depth(b);
2059        r
2060    }
2061
2062    fn compile_for_in(
2063        &mut self,
2064        b: &mut ChunkBuilder,
2065        declare: BindMode,
2066        target: &Expr,
2067        object: &Expr,
2068        body: &Stmt,
2069    ) -> Result<(), String> {
2070        // The object is kept in a temp for the whole loop: each key is re-checked
2071        // against it just before it is visited, because the body can delete one
2072        // (14.7.5.10 enumerates lazily, so a key deleted before its turn is never
2073        // visited). Without that, `for (const k in d) delete d.z` still visited
2074        // `z`.
2075        let obj_tmp = self.tmp_name("forin");
2076        self.compile_expr(b, object)?;
2077        self.name_const(b, &obj_tmp);
2078        b.emit(Op::Swap, 0);
2079        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0); // [obj]
2080        b.emit(Op::CallBuiltin(ops::FORIN_KEYS, 1), 0); // [keys_array]
2081        b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
2082        self.iter_depth += 1;
2083        self.note_iter_depth(b);
2084        let r = self.loop_over_inner(b, declare, target, body, Some(obj_tmp));
2085        self.iter_depth -= 1;
2086        self.note_iter_depth(b);
2087        r
2088    }
2089
2090    /// `for await (target of iterable) body`. Obtains an async iterator, then each
2091    /// pass `await`s a `{value, done}` step (a native async iterator's promise, or
2092    /// the sync fallback's per-value await). The iterator lives in a temp local.
2093    fn compile_for_await(
2094        &mut self,
2095        b: &mut ChunkBuilder,
2096        declare: BindMode,
2097        target: &Expr,
2098        iter: &Expr,
2099        body: &Stmt,
2100    ) -> Result<(), String> {
2101        let iter_tmp = self.tmp_name("aiter");
2102        self.compile_expr(b, iter)?;
2103        let at = b.current_pos();
2104        b.emit(Op::CallBuiltin(ops::GET_ASYNC_ITER, 1), 0); // [iterator]
2105                                                            // `for await` over a non-iterable names the source AND says ASYNC:
2106                                                            // `for await (const x of o)` is `o is not async iterable`. Recording
2107                                                            // the whole subject keeps the runtime side one substitution, as the
2108                                                            // call-source wording above does.
2109        self.note_call_site(at, iter);
2110        self.name_const(b, &iter_tmp);
2111        b.emit(Op::Swap, 0);
2112        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
2113        b.emit(Op::Pop, 0);
2114        let start = b.current_pos();
2115        // step = await ASYNC_STEP(iterator)  -> {value, done}
2116        self.load_local(b, &iter_tmp);
2117        b.emit(Op::CallBuiltin(ops::ASYNC_STEP, 1), 0); // [stepPromise]
2118        b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0); // [step]
2119        b.emit(Op::CallBuiltin(ops::ITER_RESULT, 1), 0); // [step]
2120        let step_tmp = self.tmp_name("astep");
2121        self.name_const(b, &step_tmp);
2122        b.emit(Op::Swap, 0);
2123        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
2124        b.emit(Op::Pop, 0);
2125        // if (step.done) break
2126        self.load_local(b, &step_tmp);
2127        self.name_const(b, "done");
2128        b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
2129        b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
2130        let jdone = b.emit(Op::JumpIfTrue(0), 0);
2131        // target = step.value
2132        self.load_local(b, &step_tmp);
2133        self.name_const(b, "value");
2134        b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [value]
2135        let per_iteration = matches!(declare, BindMode::Lexical | BindMode::Const);
2136        if per_iteration {
2137            self.emit_push_scope(b);
2138        }
2139        self.bind_loop_target(b, target, declare)?;
2140        self.loops.push(LoopCtx {
2141            breaks: Vec::new(),
2142            continues: Vec::new(),
2143            break_depth: self.scope_depth,
2144            continue_depth: self.scope_depth,
2145            iter_depth: self.iter_depth,
2146            catches_continue: true,
2147            label: self.pending_label.take(),
2148        });
2149        self.compile_stmt(b, body)?;
2150        let cont_target = b.current_pos();
2151        if per_iteration {
2152            self.emit_pop_scope(b);
2153        }
2154        b.emit(Op::Jump(start), 0);
2155        let ctx = self.loops.pop().unwrap();
2156        for c in ctx.continues {
2157            b.patch_jump(c, cont_target);
2158        }
2159        // `done` arrives before the iteration scope is open; `break` from inside it
2160        // still has one to close.
2161        let break_target = b.current_pos();
2162        if per_iteration {
2163            b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
2164            b.emit(Op::Pop, 0);
2165        }
2166        // Leaving early closes the async iterator, running an async generator's
2167        // pending `finally` / calling a user iterator's `.return()`.
2168        self.load_local(b, &iter_tmp);
2169        b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0);
2170        b.emit(Op::Pop, 0);
2171        let end = b.current_pos();
2172        b.patch_jump(jdone, end);
2173        for br in ctx.breaks {
2174            b.patch_jump(br, break_target);
2175        }
2176        self.redispatch_after_loop(b);
2177        Ok(())
2178    }
2179
2180    /// Shared loop tail for for-of / for-in: iterator on TOS.
2181    fn loop_over(
2182        &mut self,
2183        b: &mut ChunkBuilder,
2184        declare: BindMode,
2185        target: &Expr,
2186        body: &Stmt,
2187    ) -> Result<(), String> {
2188        self.loop_over_inner(b, declare, target, body, None)
2189    }
2190
2191    /// `alive_in` names the local holding a `for-in`'s object. When it is set,
2192    /// each key is re-checked against that object before it is bound, and a key
2193    /// the body already deleted is skipped rather than visited.
2194    fn loop_over_inner(
2195        &mut self,
2196        b: &mut ChunkBuilder,
2197        declare: BindMode,
2198        target: &Expr,
2199        body: &Stmt,
2200        alive_in: Option<String>,
2201    ) -> Result<(), String> {
2202        // `for (const v of …)` binds a FRESH `v` each pass, so a closure made in one
2203        // pass keeps that pass's element.
2204        let per_iteration = matches!(declare, BindMode::Lexical | BindMode::Const);
2205        let start = b.current_pos();
2206        b.emit(Op::CallBuiltin(ops::FORITER, 0), 0); // [iterator, value, has_next]
2207        let jdone = b.emit(Op::JumpIfFalse(0), 0); // pops has_next
2208        if let Some(obj_tmp) = &alive_in {
2209            b.emit(Op::Dup, 0); // [iterator, key, key]
2210            self.load_local(b, obj_tmp); // [iterator, key, key, obj]
2211            b.emit(Op::Swap, 0); // [iterator, key, obj, key]
2212            b.emit(Op::CallBuiltin(ops::FORIN_ALIVE, 2), 0); // [iterator, key, alive]
2213            let jalive = b.emit(Op::JumpIfTrue(0), 0);
2214            b.emit(Op::Pop, 0); // drop the dead key -> [iterator]
2215            b.emit(Op::Jump(start), 0);
2216            b.patch_jump(jalive, b.current_pos());
2217        }
2218        if per_iteration {
2219            self.emit_push_scope(b);
2220        }
2221        self.bind_loop_target(b, target, declare)?; // consumes value -> [iterator]
2222        self.loops.push(LoopCtx {
2223            breaks: Vec::new(),
2224            continues: Vec::new(),
2225            break_depth: self.scope_depth,
2226            continue_depth: self.scope_depth,
2227            iter_depth: self.iter_depth,
2228            catches_continue: true,
2229            label: self.pending_label.take(),
2230        });
2231        self.compile_stmt(b, body)?;
2232        let cont_target = b.current_pos();
2233        if per_iteration {
2234            self.emit_pop_scope(b);
2235        }
2236        b.emit(Op::Jump(start), 0);
2237        let ctx = self.loops.pop().unwrap();
2238        for c in ctx.continues {
2239            b.patch_jump(c, cont_target);
2240        }
2241        let done = b.current_pos();
2242        b.patch_jump(jdone, done);
2243        b.emit(Op::Pop, 0); // drop iterator
2244        let jafter = b.emit(Op::Jump(0), 0);
2245        let break_target = b.current_pos();
2246        // `break` out of a for-of closes the iterator (runs a generator's pending
2247        // `finally` / calls a user iterator's `.return()`), then drops it.
2248        if per_iteration {
2249            b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
2250            b.emit(Op::Pop, 0);
2251        }
2252        b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0);
2253        b.emit(Op::Pop, 0); // ITER_CLOSE leaves its result; the `done` path popped
2254        let end = b.current_pos();
2255        b.patch_jump(jafter, end);
2256        for br in ctx.breaks {
2257            b.patch_jump(br, break_target);
2258        }
2259        // Every exit path above has already closed and dropped THIS loop's
2260        // iterator, so a signal re-dispatched here must not count it as live.
2261        self.iter_depth -= 1;
2262        self.redispatch_after_loop(b);
2263        self.iter_depth += 1;
2264        Ok(())
2265    }
2266
2267    fn compile_switch(
2268        &mut self,
2269        b: &mut ChunkBuilder,
2270        disc: &Expr,
2271        cases: &[SwitchCase],
2272    ) -> Result<(), String> {
2273        let disc_tmp = self.tmp_name("switch");
2274        self.compile_expr(b, disc)?;
2275        self.name_const(b, &disc_tmp);
2276        b.emit(Op::Swap, 0);
2277        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
2278        b.emit(Op::Pop, 0);
2279        // All cases share ONE block scope, so `case 1: let x = …` is visible to the
2280        // later cases but dies with the switch. It opens BEFORE the test chain
2281        // because each case test jumps straight into its body.
2282        self.emit_push_scope(b);
2283        // …and every case's lexical names are hoisted into that one scope, so a
2284        // read from an EARLIER case is a dead-zone error rather than a lookup
2285        // that escapes to an outer binding.
2286        let all: Vec<Stmt> = cases.iter().flat_map(|c| c.body.iter().cloned()).collect();
2287        self.hoist_lexical(b, &all);
2288        // Emit the test chain: `if (disc === caseTest) goto bodyN`.
2289        let mut body_jumps: Vec<Option<usize>> = Vec::new();
2290        let mut default_idx: Option<usize> = None;
2291        for (i, case) in cases.iter().enumerate() {
2292            match &case.test {
2293                Some(t) => {
2294                    self.load_local(b, &disc_tmp);
2295                    self.compile_expr(b, t)?;
2296                    b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
2297                    let j = b.emit(Op::JumpIfTrue(0), 0);
2298                    body_jumps.push(Some(j));
2299                }
2300                None => {
2301                    default_idx = Some(i);
2302                    body_jumps.push(None);
2303                }
2304            }
2305        }
2306        // No test matched: jump to default (if any) or end.
2307        let no_match_jump = b.emit(Op::Jump(0), 0);
2308        self.loops.push(LoopCtx {
2309            breaks: Vec::new(),
2310            continues: Vec::new(),
2311            break_depth: self.scope_depth,
2312            continue_depth: self.scope_depth,
2313            iter_depth: self.iter_depth,
2314            catches_continue: false,
2315            label: None,
2316        });
2317        let mut body_starts: Vec<usize> = Vec::new();
2318        for case in cases {
2319            body_starts.push(b.current_pos());
2320            self.compile_stmts(b, &case.body)?;
2321        }
2322        let end = b.current_pos();
2323        // Patch each case test-jump to its body start.
2324        for (i, j) in body_jumps.iter().enumerate() {
2325            if let Some(j) = j {
2326                b.patch_jump(*j, body_starts[i]);
2327            }
2328        }
2329        match default_idx {
2330            Some(i) => b.patch_jump(no_match_jump, body_starts[i]),
2331            None => b.patch_jump(no_match_jump, end),
2332        }
2333        let ctx = self.loops.pop().unwrap();
2334        for br in ctx.breaks {
2335            b.patch_jump(br, end);
2336        }
2337        self.emit_pop_scope(b);
2338        self.redispatch_after_loop(b);
2339        Ok(())
2340    }
2341
2342    fn compile_try(
2343        &mut self,
2344        b: &mut ChunkBuilder,
2345        block: &[Stmt],
2346        handler: &Option<(Option<Expr>, Vec<Stmt>)>,
2347        finalizer: &Option<Vec<Stmt>>,
2348    ) -> Result<(), String> {
2349        let block_chunk = self.compile_block_chunk(block)?;
2350        let handler_def = match handler {
2351            Some((param, body)) => match param {
2352                Some(Expr::Ident(n)) => {
2353                    let hbody = self.compile_block_chunk(body)?;
2354                    Some((Some(n.clone()), hbody))
2355                }
2356                // `catch ({ code })` / `catch ([a, b])`. The handler receives
2357                // ONE value under a name, so a pattern binds a temp and is
2358                // destructured out of it before the body runs. Only a bare
2359                // identifier was handled, so the pattern bound nothing at all
2360                // and the body saw a ReferenceError for every name in it.
2361                Some(pattern) => {
2362                    let tmp = self.tmp_name("catch");
2363                    let pattern = pattern.clone();
2364                    let name = tmp.clone();
2365                    let hbody = self.compile_chunk_with(body, move |s, cb| {
2366                        s.load_local(cb, &name);
2367                        s.compile_bind(cb, &pattern, BindMode::Lexical)
2368                    })?;
2369                    Some((Some(tmp), hbody))
2370                }
2371                None => {
2372                    let hbody = self.compile_block_chunk(body)?;
2373                    Some((None, hbody))
2374                }
2375            },
2376            None => None,
2377        };
2378        let final_chunk = match finalizer {
2379            Some(f) => {
2380                // 14.15.3: a `finally` that completes NORMALLY has its
2381                // completion DISCARDED — the try/catch value is what the
2382                // statement produces. `eval('try{5}finally{6}')` is 5, and was
2383                // 6 while the block updated the completion register like any
2384                // other.
2385                let saved = std::mem::take(&mut self.completion);
2386                let outer_slot = self.cslot();
2387                let saved_slot = std::mem::take(&mut self.completion_slot);
2388                let (saved_fin, body): (_, Vec<Stmt>) = if saved {
2389                    // The block tracks its own value in a register of its own,
2390                    // starting `undefined`.
2391                    let own = self.tmp_name("fin");
2392                    self.completion = true;
2393                    self.completion_slot = own.clone();
2394                    let mut body = vec![Stmt::from(StmtKind::Decl {
2395                        kind: DeclKind::Let,
2396                        decls: vec![Declarator {
2397                            target: Expr::Ident(own.clone()),
2398                            init: Some(Expr::Undefined),
2399                            bound: Vec::new(),
2400                        }],
2401                    })];
2402                    body.extend(f.iter().cloned());
2403                    (self.finalizer_completion.replace((own, outer_slot)), body)
2404                } else {
2405                    (self.finalizer_completion.take(), f.to_vec())
2406                };
2407                let chunk = self.compile_block_chunk(&body);
2408                self.finalizer_completion = saved_fin;
2409                self.completion = saved;
2410                self.completion_slot = saved_slot;
2411                Some(chunk?)
2412            }
2413            None => None,
2414        };
2415        let id = self.tries.len();
2416        self.tries.push(TryDef {
2417            block: block_chunk,
2418            handler: handler_def,
2419            finalizer: final_chunk,
2420        });
2421        b.emit(Op::LoadInt(id as i64), 0);
2422        b.emit(Op::CallBuiltin(ops::TRY, 1), 0);
2423        b.emit(Op::Pop, 0);
2424        // The try/catch/finally bodies ran as their own chunks, so a `return` or
2425        // a `break`/`continue` inside them left a signal instead of jumping.
2426        self.emit_signal_dispatch(b);
2427        Ok(())
2428    }
2429
2430    /// Compile statements into a SEPARATE chunk (a try/catch/finally body). Loops
2431    /// opened outside it are unreachable by a plain jump, so `chunk_loop_base`
2432    /// moves up for the duration.
2433    fn compile_block_chunk(&mut self, stmts: &[Stmt]) -> Result<Chunk, String> {
2434        self.compile_chunk_with(stmts, |_, _| Ok(()))
2435    }
2436
2437    /// A try/catch/finally body chunk, with `prelude` emitted ahead of the
2438    /// statements. Used to destructure a `catch ({ code })` parameter, which has
2439    /// to bind before the handler's first statement runs.
2440    fn compile_chunk_with(
2441        &mut self,
2442        stmts: &[Stmt],
2443        prelude: impl FnOnce(&mut Self, &mut ChunkBuilder) -> Result<(), String>,
2444    ) -> Result<Chunk, String> {
2445        let mut cb = ChunkBuilder::new();
2446        // A nested chunk runs on its OWN VM frame, so the enclosing chunk's
2447        // slots are not reachable from it — everything here goes by name. (The
2448        // slot analysis already refuses any chunk containing a `try`, which is
2449        // what builds these; this keeps that true if another one appears.)
2450        let saved_slot_table = std::mem::take(&mut self.slots);
2451        let base = std::mem::replace(&mut self.chunk_loop_base, self.loops.len());
2452        let signals = std::mem::take(&mut self.chunk_signals);
2453        let depth = std::mem::take(&mut self.scope_depth);
2454        let iters = std::mem::take(&mut self.iter_depth);
2455        let sites = std::mem::take(&mut self.call_sites);
2456        let yields = std::mem::take(&mut self.yield_sites);
2457        let marks = std::mem::take(&mut self.pos_marks);
2458        let events = std::mem::take(&mut self.iter_events);
2459        let r = (|| {
2460            prelude(self, &mut cb)?;
2461            self.hoist_lexical(&mut cb, stmts);
2462            self.hoist_funcs(&mut cb, stmts)?;
2463            self.compile_stmts(&mut cb, stmts)
2464        })();
2465        self.chunk_loop_base = base;
2466        self.scope_depth = depth;
2467        self.iter_depth = iters;
2468        self.slots = saved_slot_table;
2469        // A signal raised inside the nested chunk still has to be dispatched by a
2470        // loop in THIS chunk, so the flag propagates outward.
2471        self.chunk_signals |= signals;
2472        r?;
2473        let chunk = self.finish_chunk(cb);
2474        self.call_sites = sites;
2475        self.yield_sites = yields;
2476        self.pos_marks = marks;
2477        self.iter_events = events;
2478        Ok(chunk)
2479    }
2480
2481    // ── functions ────────────────────────────────────────────────────────
2482    fn build_function(
2483        &mut self,
2484        name: &str,
2485        params: &[Param],
2486        body: &[Stmt],
2487        is_generator: bool,
2488        is_async: bool,
2489    ) -> Result<usize, String> {
2490        check_function_body(params, body)?;
2491        let (param_slots, prologue) = self.lower_params(params)?;
2492        let mut fb = ChunkBuilder::new();
2493        // Each function body is its own frame, so it gets its own slot table.
2494        // The analysis sees the parameter prologue (defaults, destructuring)
2495        // ahead of the body, which is the order they are emitted in.
2496        let mut planned: Vec<Stmt> = prologue.clone();
2497        planned.extend_from_slice(body);
2498        // A sloppy function with a simple parameter list gets a MAPPED
2499        // `arguments` object (10.4.4): the parameters and `arguments[i]` alias
2500        // each other. The aliasing lives in the parameter bindings, so those
2501        // must stay bindings — the chunk gets no frame slots — and a prologue op
2502        // links them. Only a body that can name `arguments` pays for any of it.
2503        let is_arrow = std::mem::take(&mut self.arrow_next);
2504        let simple_params = params
2505            .iter()
2506            .all(|p| !p.rest && p.default.is_none() && matches!(p.pattern, Expr::Ident(_)));
2507        let maps_arguments = !is_arrow
2508            && !params.is_empty()
2509            && simple_params
2510            && !(self.strict || has_use_strict(body))
2511            && crate::slots::mentions_arguments(&planned);
2512        let saved_slot_table = std::mem::replace(
2513            &mut self.slots,
2514            if self.debug || is_generator || is_async || maps_arguments || self.with_depth > 0 {
2515                Default::default()
2516            } else {
2517                crate::slots::plan(params, &planned, false)
2518            },
2519        );
2520        if maps_arguments {
2521            let names: Vec<String> = crate::slots::param_names(params);
2522            self.name_const(&mut fb, &names.join(","));
2523            fb.emit(Op::CallBuiltin(ops::MAP_ARGS, 1), 0);
2524            fb.emit(Op::Pop, 0);
2525        }
2526        // Prologue: a parameter arrives in the call environment (`bind_params`
2527        // ran before this chunk), so copy each slotted one into its slot once,
2528        // and everything after it is a bare `GetSlot`.
2529        for name in crate::slots::param_names(params) {
2530            if let Some(slot) = self.slot_of(&name) {
2531                self.name_const(&mut fb, &name);
2532                fb.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
2533                fb.emit(Op::SetSlot(slot), 0);
2534            }
2535        }
2536        // A function body is its own control-flow universe: `break`/`continue` can
2537        // never target a loop in the enclosing function.
2538        let saved_loops = std::mem::take(&mut self.loops);
2539        let saved_base = std::mem::replace(&mut self.chunk_loop_base, 0);
2540        let saved_signals = std::mem::take(&mut self.chunk_signals);
2541        let saved_depth = std::mem::take(&mut self.scope_depth);
2542        let saved_iters = std::mem::take(&mut self.iter_depth);
2543        let saved_agen = std::mem::replace(&mut self.in_async_generator, is_generator && is_async);
2544        // Strictness is inherited by every nested function and can only be
2545        // ADDED by a body's own directive prologue — never dropped.
2546        let saved_strict = self.strict;
2547        self.strict = self.strict || has_use_strict(body);
2548        // A nested function's statements are not the SCRIPT's, so none of them
2549        // may touch the completion register.
2550        let saved_completion = std::mem::take(&mut self.completion);
2551        let saved_finalizer = std::mem::take(&mut self.finalizer_completion);
2552        let saved_cslot = std::mem::take(&mut self.completion_slot);
2553        // Captured before the restore below, since the FuncDef is built after
2554        // `self.strict` has been put back to the enclosing value.
2555        let body_strict = self.strict;
2556        // The body is a chunk of its own, so its call sites are keyed to ITS
2557        // `op_hash`; the enclosing chunk's pending ones must not be swept in.
2558        let saved_sites = std::mem::take(&mut self.call_sites);
2559        let saved_marks = std::mem::take(&mut self.pos_marks);
2560        let saved_yields = std::mem::take(&mut self.yield_sites);
2561        let saved_events = std::mem::take(&mut self.iter_events);
2562        let r = (|| {
2563            // Function-body hoisting: `var` bindings first, so a same-named
2564            // function declaration below overwrites the `undefined` rather than
2565            // being overwritten by it. Parameters are already bound, and
2566            // `hoist_var_name` leaves an existing binding alone.
2567            self.hoist_vars(&mut fb, body)?;
2568            self.hoist_funcs(&mut fb, &prologue)?;
2569            self.hoist_lexical(&mut fb, body);
2570            self.hoist_funcs(&mut fb, body)?;
2571            self.compile_stmts(&mut fb, &prologue)?;
2572            self.compile_stmts(&mut fb, body)
2573        })();
2574        self.loops = saved_loops;
2575        self.chunk_loop_base = saved_base;
2576        self.chunk_signals = saved_signals;
2577        self.scope_depth = saved_depth;
2578        self.iter_depth = saved_iters;
2579        self.in_async_generator = saved_agen;
2580        self.strict = saved_strict;
2581        self.completion = saved_completion;
2582        self.finalizer_completion = saved_finalizer;
2583        self.completion_slot = saved_cslot;
2584        self.slots = saved_slot_table;
2585        r?;
2586        let def = FuncDef {
2587            name: name.to_string(),
2588            params: param_slots,
2589            chunk: self.finish_chunk(fb),
2590            is_arrow: false,
2591            is_generator,
2592            is_async,
2593            is_method: false,
2594            self_name: false,
2595            strict: body_strict,
2596            span: (0, 0),
2597            script: None,
2598        };
2599        self.call_sites = saved_sites;
2600        self.pos_marks = saved_marks;
2601        self.yield_sites = saved_yields;
2602        self.iter_events = saved_events;
2603        self.functions.push((name.to_string(), def));
2604        Ok(self.functions.len() - 1)
2605    }
2606
2607    /// A FuncDef that only carries `span`: the source of a `class`, which has
2608    /// no function of its own when it declares no constructor.
2609    fn source_record(&mut self, name: &str, span: Span) -> usize {
2610        let def = FuncDef {
2611            name: name.to_string(),
2612            params: Vec::new(),
2613            chunk: ChunkBuilder::new().build(),
2614            is_arrow: false,
2615            is_generator: false,
2616            is_async: false,
2617            is_method: true,
2618            self_name: false,
2619            strict: true,
2620            span,
2621            script: None,
2622        };
2623        self.functions.push((name.to_string(), def));
2624        self.functions.len() - 1
2625    }
2626
2627    fn build_arrow(
2628        &mut self,
2629        params: &[Param],
2630        body: &FnBody,
2631        is_async: bool,
2632    ) -> Result<usize, String> {
2633        let stmts = match body {
2634            FnBody::Block(b) => b.clone(),
2635            FnBody::Expr(e) => vec![Stmt::from(StmtKind::Return(Some((**e).clone())))],
2636        };
2637        self.arrow_next = true;
2638        let id = self.build_function("", params, &stmts, false, is_async)?;
2639        // Mark the template as an arrow so `this` is captured lexically.
2640        self.functions[id].1.is_arrow = true;
2641        Ok(id)
2642    }
2643
2644    // ── classes ──────────────────────────────────────────────────────────
2645    /// Lower a `class` to runtime builder ops, leaving the class value on the
2646    /// stack: `MKCLASS` (name, parent, ctor) then `DEF_MEMBER`/`DEF_FIELD` for
2647    /// each member (each keeps the class on the stack).
2648    fn compile_class(&mut self, b: &mut ChunkBuilder, node: &ClassNode) -> Result<(), String> {
2649        // A class body is strict code unconditionally (10.2.4), directive or not.
2650        let saved_strict = std::mem::replace(&mut self.strict, true);
2651        let r = self.compile_class_body(b, node);
2652        self.strict = saved_strict;
2653        r
2654    }
2655
2656    /// `#name` when this member's key is a literal private name, else `None`. A
2657    /// private name is never computed, so a computed key is never one.
2658    fn private_key(m: &ClassMember) -> Option<String> {
2659        match &m.key {
2660            Expr::Str(s) if !m.computed && s.starts_with('#') => Some(s.clone()),
2661            Expr::Ident(s) if !m.computed && s.starts_with('#') => Some(s.clone()),
2662            _ => None,
2663        }
2664    }
2665
2666    fn compile_class_body(&mut self, b: &mut ChunkBuilder, node: &ClassNode) -> Result<(), String> {
2667        let cname = node.name.clone().unwrap_or_default();
2668        // Push name, parent (or undefined), constructor (or undefined).
2669        self.name_const(b, &cname);
2670        match &node.parent {
2671            Some(p) => self.compile_expr(b, p)?,
2672            None => {
2673                b.emit(Op::LoadUndef, 0);
2674            }
2675        }
2676        let ctor = node
2677            .members
2678            .iter()
2679            .find(|m| m.kind == MemberKind::Constructor);
2680        match ctor {
2681            Some(m) => {
2682                let def_id = self.build_function(&cname, &m.params, &m.body, false, false)?;
2683                self.emit_mkfunc(b, def_id);
2684            }
2685            None => {
2686                b.emit(Op::LoadUndef, 0);
2687            }
2688        }
2689        // The class's source text (`String(C)`) rides on a FuncDef that is
2690        // never called, so its span is script-relative like any function's
2691        // and its id is rebased with the rest.
2692        let record = self.source_record(&cname, node.span);
2693        b.emit(Op::LoadInt(record as i64), 0);
2694        b.emit(Op::CallBuiltin(ops::MKCLASS, 4), 0); // -> [class]
2695
2696        // 15.7.14 steps 8-17: the class body runs inside its OWN environment,
2697        // holding one immutable binding for the class name, initialized to the
2698        // class itself at step 17 — before the static-field initializers of step
2699        // 32. So `class C { static x = C.m(); static m(){return 5} }` is 5, and a
2700        // class EXPRESSION's name (`const K = class Inner { static s = Inner.name }`)
2701        // is reachable from inside the body even though it is never a binding
2702        // outside it. node-js had no such scope: both threw `ReferenceError: C is
2703        // not defined`, because the only binding was the outer one the class
2704        // DECLARATION installs afterwards. An instance method's body already
2705        // worked, but only by accident — it runs late enough for the outer
2706        // binding to exist, which a class expression never gets.
2707        let body_scope = node.name.is_some();
2708        if let Some(name) = &node.name {
2709            self.emit_push_scope(b);
2710            b.emit(Op::Dup, 0); // [class, class]
2711            self.declare_as(b, &Expr::Ident(name.clone()), BindMode::Const); // [class]
2712        }
2713
2714        // `ClassDefinitionEvaluation` (15.7.14) installs every method and
2715        // accessor while evaluating the class body, and only then runs the
2716        // static-field initializers (step 32). So a static field may call a
2717        // static method declared after it, and `getOwnPropertyNames(C)` lists
2718        // the methods before the fields regardless of source order.
2719        // A `static { … }` block is a static ELEMENT, not a method: it belongs in
2720        // the deferred group with the field initializers and runs interleaved
2721        // with them in source order (both filters are stable over `members`).
2722        let deferred = |k: &MemberKind| matches!(k, MemberKind::Field | MemberKind::StaticBlock);
2723        // Computed keys are evaluated in SOURCE order across every element
2724        // (15.7.14 ClassElementEvaluation runs top to bottom), although the
2725        // fields they name are installed later. So a field's computed key is
2726        // evaluated and parked in a hidden binding during the first pass, at
2727        // its position among the methods, and read back by the second.
2728        let mut events: Vec<(usize, bool)> = Vec::new();
2729        for (i, m) in node.members.iter().enumerate() {
2730            if !deferred(&m.kind) {
2731                events.push((i, false));
2732            } else if m.computed && m.kind == MemberKind::Field {
2733                events.push((i, true));
2734            }
2735        }
2736        for (i, m) in node.members.iter().enumerate() {
2737            if deferred(&m.kind) {
2738                events.push((i, false));
2739            }
2740        }
2741        let mut stash: std::collections::HashMap<usize, String> = std::collections::HashMap::new();
2742        let mut static_block_n = 0usize;
2743        for (idx, park_key) in events {
2744            let m = &node.members[idx];
2745            if park_key {
2746                let tmp = self.tmp_name("ckey");
2747                self.compile_expr(b, &m.key)?;
2748                b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
2749                self.declare_as(b, &Expr::Ident(tmp.clone()), BindMode::Lexical);
2750                stash.insert(idx, tmp);
2751                continue;
2752            }
2753            match m.kind {
2754                MemberKind::Constructor => {}
2755                // A PRIVATE static field declares a private element, so it
2756                // cannot be an ordinary write: `C.#s = 5` through `SETATTR`
2757                // trips the brand check that exists to reject exactly that write
2758                // on an object that has not declared `#s`. `DEF_MEMBER` installs
2759                // it directly, which is what a declaration is.
2760                MemberKind::Field if m.is_static && Self::private_key(m).is_some() => {
2761                    let key = Self::private_key(m).expect("guarded above");
2762                    // The initializer runs with `this` the class, so it is
2763                    // evaluated by a hidden static method (as a static block
2764                    // is) and its value taken from the call.
2765                    let slot = self.emit_static_initializer(b, m.field_init.as_ref());
2766                    b.emit(Op::Dup, 0);
2767                    self.name_const(b, &slot);
2768                    b.emit(Op::CallBuiltin(ops::CALL_METHOD, 2), 0); // [class, val]
2769                    if let Some(e) = m.field_init.as_ref().filter(|e| Self::is_anon_fn_def(e)) {
2770                        self.infer_name(b, e, &key);
2771                    }
2772                    self.name_const(b, &key); // [class, val, name]
2773                    b.emit(Op::Swap, 0); // [class, name, val]
2774                    b.emit(Op::LoadInt(member::STATIC_FIELD), 0);
2775                    b.emit(Op::Swap, 0); // [class, name, kind, val]
2776                    b.emit(Op::LoadTrue, 0); // is_static
2777                    b.emit(Op::Swap, 0); // [class, name, kind, static, val]
2778                    b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0); // -> [class]
2779                    self.emit_drop_slot(b, &slot);
2780                }
2781                MemberKind::Field if m.is_static => {
2782                    // A static field is evaluated once at class-definition time and
2783                    // set as an own property of the constructor: `[class]` stays on
2784                    // the stack, `Dup` it as the SETATTR receiver.
2785                    let slot = self.emit_static_initializer(b, m.field_init.as_ref());
2786                    b.emit(Op::Dup, 0);
2787                    b.emit(Op::Dup, 0); // [class, class, class]
2788                    self.emit_field_key(b, m, stash.get(&idx))?; // [class, class, class, name]
2789                    b.emit(Op::Swap, 0); // [class, class, name, class]
2790                    self.name_const(b, &slot);
2791                    b.emit(Op::CallBuiltin(ops::CALL_METHOD, 2), 0); // [class, class, name, val]
2792                                                                     // 15.7.10: a static field's initializer is named after the
2793                                                                     // field (`static s = function(){}` → `s`).
2794                    if let Some(e) = m.field_init.as_ref().filter(|e| Self::is_anon_fn_def(e)) {
2795                        match (&m.key, m.computed) {
2796                            (Expr::Str(s), false) => self.infer_name(b, e, s),
2797                            _ => {
2798                                // [.., name, val] -> [.., name, fn] via NAMED_EVAL.
2799                                b.emit(Op::Swap, 0); // [.., val, name]
2800                                b.emit(Op::Dup, 0); // [.., val, name, name]
2801                                b.emit(Op::Rot, 0); // [.., name, name, val]
2802                                b.emit(Op::LoadInt(member::METHOD), 0);
2803                                b.emit(Op::Swap, 0); // [.., name, name, kind, val]
2804                                b.emit(Op::CallBuiltin(ops::NAMED_EVAL, 3), 0);
2805                            }
2806                        }
2807                    }
2808                    // [class, class, name, val] -> SETATTR sets on the class -> [class, val]
2809                    b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0);
2810                    b.emit(Op::Pop, 0); // drop the returned value -> [class]
2811                    self.emit_drop_slot(b, &slot);
2812                }
2813                MemberKind::Field => {
2814                    // [class] name thunk name_anon -> DEF_FIELD -> [class]
2815                    self.emit_field_key(b, m, stash.get(&idx))?;
2816                    let init = m.field_init.clone().unwrap_or(Expr::Undefined);
2817                    // 15.7.10: `class C { f = function(){} }` names the function
2818                    // `f`. An instance field's initializer runs per-instance from
2819                    // a thunk, and under a computed key the key is only known at
2820                    // class-definition time, so the decision travels to the host
2821                    // as a flag rather than as an emitted rename.
2822                    let name_anon = Self::is_anon_fn_def(&init);
2823                    let stmts = vec![Stmt::from(StmtKind::Return(Some(init)))];
2824                    let def_id = self.build_function("", &[], &stmts, false, false)?;
2825                    self.emit_mkfunc(b, def_id);
2826                    b.emit(
2827                        if name_anon {
2828                            Op::LoadTrue
2829                        } else {
2830                            Op::LoadFalse
2831                        },
2832                        0,
2833                    );
2834                    b.emit(Op::CallBuiltin(ops::DEF_FIELD, 4), 0);
2835                }
2836                MemberKind::StaticBlock => {
2837                    // `static { … }` runs ONCE at class-definition time with
2838                    // `this` bound to the constructor — exactly what a static
2839                    // method called as `C.m()` gets. So it is compiled as a
2840                    // static method under a HIDDEN key, invoked, and removed
2841                    // again; the `@@` prefix keeps it out of every enumeration
2842                    // (`Object.getOwnPropertyNames(C)` and friends filter
2843                    // internal slots) for the window in which it exists, and the
2844                    // counter keeps sibling blocks from colliding.
2845                    static_block_n += 1;
2846                    let slot = format!("@@staticBlock:{static_block_n}");
2847                    // [class] name kind static fn -> DEF_MEMBER -> [class]
2848                    self.name_const(b, &slot);
2849                    b.emit(Op::LoadInt(member::METHOD), 0);
2850                    b.emit(Op::LoadTrue, 0);
2851                    let def_id = self.build_function("", &[], &m.body, false, false)?;
2852                    self.functions[def_id].1.is_method = true;
2853                    self.emit_mkfunc(b, def_id);
2854                    b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0);
2855                    // [class] -> C[slot]() -> discard the result
2856                    b.emit(Op::Dup, 0);
2857                    self.name_const(b, &slot);
2858                    b.emit(Op::CallBuiltin(ops::CALL_METHOD, 2), 0);
2859                    b.emit(Op::Pop, 0);
2860                    // [class] -> delete C[slot] -> discard the Bool
2861                    b.emit(Op::Dup, 0);
2862                    self.name_const(b, &slot);
2863                    self.emit_bool(b, false);
2864                    b.emit(Op::CallBuiltin(ops::DELPROP_NAME, 3), 0);
2865                    b.emit(Op::Pop, 0);
2866                }
2867                MemberKind::Method | MemberKind::Get | MemberKind::Set => {
2868                    // [class] name kind static fn -> DEF_MEMBER -> [class]
2869                    self.emit_member_key(b, m)?;
2870                    let kind = match m.kind {
2871                        MemberKind::Get => member::GET,
2872                        MemberKind::Set => member::SET,
2873                        _ => member::METHOD,
2874                    };
2875                    let static_op = if m.is_static {
2876                        Op::LoadTrue
2877                    } else {
2878                        Op::LoadFalse
2879                    };
2880                    // A COMPUTED key is only known at run time, so the method is
2881                    // named there (SetFunctionName via `NAMED_EVAL`): a symbol
2882                    // key gives `[description]`, so `class C { [Symbol.iterator]()
2883                    // {} }` is named `[Symbol.iterator]`, not `''`.
2884                    // [class, key] Dup kind fn -> NAMED_EVAL -> [class, key, fn]
2885                    // kind static -> [class, key, fn, kind, static]
2886                    // Rot -> [class, key, kind, static, fn]
2887                    if m.computed {
2888                        let def_id = self.build_function(
2889                            "",
2890                            &m.params,
2891                            &m.body,
2892                            m.is_generator,
2893                            m.is_async,
2894                        )?;
2895                        self.functions[def_id].1.is_method = true;
2896                        self.functions[def_id].1.span = m.span;
2897                        b.emit(Op::Dup, 0);
2898                        b.emit(Op::LoadInt(kind), 0);
2899                        self.emit_mkfunc(b, def_id);
2900                        b.emit(Op::CallBuiltin(ops::NAMED_EVAL, 3), 0);
2901                        b.emit(Op::LoadInt(kind), 0);
2902                        b.emit(static_op, 0);
2903                        b.emit(Op::Rot, 0);
2904                        b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0);
2905                        continue;
2906                    }
2907                    b.emit(Op::LoadInt(kind), 0);
2908                    b.emit(static_op, 0);
2909                    // 10.2.9 step 4: an accessor's function name carries the
2910                    // `get `/`set ` prefix — `class C { get gg(){} }` gives
2911                    // `get gg`, not `gg`.
2912                    let mname = match &m.key {
2913                        Expr::Str(s) if !m.computed => match m.kind {
2914                            MemberKind::Get => format!("get {s}"),
2915                            MemberKind::Set => format!("set {s}"),
2916                            _ => s.clone(),
2917                        },
2918                        _ => String::new(),
2919                    };
2920                    let def_id = self.build_function(
2921                        &mname,
2922                        &m.params,
2923                        &m.body,
2924                        m.is_generator,
2925                        m.is_async,
2926                    )?;
2927                    // A class method/accessor is a MethodDefinition: not a
2928                    // constructor, so it owns no `prototype` property.
2929                    self.functions[def_id].1.is_method = true;
2930                    self.functions[def_id].1.span = m.span;
2931                    self.emit_mkfunc(b, def_id);
2932                    b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0);
2933                }
2934            }
2935        }
2936        if body_scope {
2937            self.emit_pop_scope(b);
2938        }
2939        Ok(())
2940    }
2941
2942    /// Install a hidden static method whose body is `return <init>` and leave
2943    /// `[class]` as it was; the name of its slot is returned. A static field's
2944    /// initializer is called through it so that `this` is the class and `super`
2945    /// property accesses see the class's home object, as for a static method.
2946    fn emit_static_initializer(&mut self, b: &mut ChunkBuilder, init: Option<&Expr>) -> String {
2947        self.static_init_n += 1;
2948        let slot = format!("@@staticInit:{}", self.static_init_n);
2949        self.name_const(b, &slot);
2950        b.emit(Op::LoadInt(member::METHOD), 0);
2951        b.emit(Op::LoadTrue, 0);
2952        let body = vec![Stmt::from(StmtKind::Return(Some(
2953            init.cloned().unwrap_or(Expr::Undefined),
2954        )))];
2955        let def_id = self
2956            .build_function("", &[], &body, false, false)
2957            .expect("a `return <expr>` body always compiles if the initializer did");
2958        self.functions[def_id].1.is_method = true;
2959        self.emit_mkfunc(b, def_id);
2960        b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0);
2961        slot
2962    }
2963
2964    /// Remove the hidden slot [`Self::emit_static_initializer`] created.
2965    fn emit_drop_slot(&mut self, b: &mut ChunkBuilder, slot: &str) {
2966        b.emit(Op::Dup, 0);
2967        self.name_const(b, slot);
2968        self.emit_bool(b, false);
2969        b.emit(Op::CallBuiltin(ops::DELPROP_NAME, 3), 0);
2970        b.emit(Op::Pop, 0);
2971    }
2972
2973    /// A field's key: the parked value of a computed one, else
2974    /// [`Self::emit_member_key`].
2975    fn emit_field_key(
2976        &mut self,
2977        b: &mut ChunkBuilder,
2978        m: &ClassMember,
2979        parked: Option<&String>,
2980    ) -> Result<(), String> {
2981        match parked {
2982            Some(tmp) => {
2983                self.load_local(b, tmp);
2984                Ok(())
2985            }
2986            None => self.emit_member_key(b, m),
2987        }
2988    }
2989
2990    /// `IsAnonymousFunctionDefinition(expr)` — the SYNTACTIC predicate that
2991    /// decides whether NamedEvaluation applies. It is deliberately not a runtime
2992    /// "does this function have an empty name" test: measured against node
2993    /// v26.7.0, `const anon = (0, function(){}); ({ m: anon }).m.name` is `""`,
2994    /// because the property definition's right-hand side is an
2995    /// IdentifierReference, not a function definition. Renaming by value would
2996    /// also mutate a function the program still holds under another binding.
2997    fn is_anon_fn_def(init: &Expr) -> bool {
2998        match init {
2999            Expr::Function { name: None, .. } => true,
3000            Expr::Class(node) => node.name.is_none(),
3001            _ => false,
3002        }
3003    }
3004
3005    /// If `init` is an anonymous function/arrow/class (value already on TOS), set
3006    /// its `.name` to `name` (JS binding name-inference). No-op otherwise.
3007    fn infer_name(&mut self, b: &mut ChunkBuilder, init: &Expr, name: &str) {
3008        if !Self::is_anon_fn_def(init) {
3009            return;
3010        }
3011        // [fn] Dup; .name = name; drop the SETATTR result.
3012        b.emit(Op::Dup, 0);
3013        self.name_const(b, "name");
3014        self.strlit(b, name);
3015        b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0);
3016        b.emit(Op::Pop, 0);
3017    }
3018
3019    /// Compile a member's VALUE with the key already on the stack, applying
3020    /// NamedEvaluation (10.2.9 SetFunctionName) when the value is an anonymous
3021    /// function definition — `{ m: function(){} }`, `{ m(){} }`, `{ [k]: () => {} }`,
3022    /// `class C { static [k] = function(){} }`.
3023    ///
3024    /// A literal key resolves at compile time; a computed one is only known at
3025    /// run time, so the key already on the stack is duplicated and handed to
3026    /// `NAMED_EVAL` along with `kind` (which supplies the `get `/`set ` prefix).
3027    /// Leaves exactly one value on the stack either way, so every caller's
3028    /// arity is unchanged.
3029    fn emit_keyed_value(
3030        &mut self,
3031        b: &mut ChunkBuilder,
3032        key: &Expr,
3033        value: &Expr,
3034        computed: bool,
3035        kind: i64,
3036    ) -> Result<(), String> {
3037        match (Self::is_anon_fn_def(value), computed, key) {
3038            (true, false, Expr::Str(s)) => {
3039                self.compile_expr(b, value)?;
3040                let name = match kind {
3041                    member::GET => format!("get {s}"),
3042                    member::SET => format!("set {s}"),
3043                    _ => s.clone(),
3044                };
3045                self.infer_name(b, value, &name);
3046            }
3047            // [.., key] -> [.., key, key, kind, fn] -> NAMED_EVAL -> [.., key, fn]
3048            (true, true, _) => {
3049                b.emit(Op::Dup, 0);
3050                b.emit(Op::LoadInt(kind), 0);
3051                self.compile_expr(b, value)?;
3052                b.emit(Op::CallBuiltin(ops::NAMED_EVAL, 3), 0);
3053            }
3054            _ => self.compile_expr(b, value)?,
3055        }
3056        Ok(())
3057    }
3058
3059    /// Push a class/object member's property key: a computed expression coerced
3060    /// via `PROPKEY` (Symbol-aware), or a static name constant.
3061    fn emit_member_key(&mut self, b: &mut ChunkBuilder, m: &ClassMember) -> Result<(), String> {
3062        if m.computed {
3063            self.compile_expr(b, &m.key)?;
3064            b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3065        } else if let Expr::Str(s) = &m.key {
3066            self.name_const(b, s);
3067        } else {
3068            self.compile_expr(b, &m.key)?;
3069            b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3070        }
3071        Ok(())
3072    }
3073
3074    // ── generators / yield ───────────────────────────────────────────────
3075    fn compile_yield(
3076        &mut self,
3077        b: &mut ChunkBuilder,
3078        arg: &Option<Box<Expr>>,
3079        delegate: bool,
3080    ) -> Result<(), String> {
3081        if delegate && self.in_async_generator {
3082            // `yield* x` inside an `async function*` delegates over the ASYNC
3083            // iterator: await each step, re-yield its value, and evaluate to the
3084            // delegate's return value.
3085            match arg {
3086                Some(e) => self.compile_expr(b, e)?,
3087                None => {
3088                    b.emit(Op::LoadUndef, 0);
3089                }
3090            }
3091            b.emit(Op::CallBuiltin(ops::GET_ASYNC_ITER, 1), 0); // [aiter]
3092            let start = b.current_pos();
3093            b.emit(Op::Dup, 0); // [aiter, aiter]
3094            b.emit(Op::CallBuiltin(ops::ASYNC_STEP, 1), 0); // [aiter, stepPromise]
3095            b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0); // [aiter, step]
3096            b.emit(Op::CallBuiltin(ops::ITER_RESULT, 1), 0); // [aiter, step]
3097            b.emit(Op::Dup, 0); // [aiter, step, step]
3098            self.name_const(b, "done");
3099            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
3100            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
3101            let jdone = b.emit(Op::JumpIfTrue(0), 0); // [aiter, step]
3102            self.name_const(b, "value");
3103            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [aiter, value]
3104            let at = b.emit(Op::CallBuiltin(ops::YIELD, 1), 0); // [aiter, sent]
3105            self.yield_sites.push((at, self.iter_depth));
3106            b.emit(Op::Pop, 0); // [aiter]
3107            b.emit(Op::Jump(start), 0);
3108            let done = b.current_pos();
3109            b.patch_jump(jdone, done);
3110            self.name_const(b, "value"); // [aiter, step, "value"]
3111            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [aiter, returnValue]
3112            b.emit(Op::Swap, 0); // [returnValue, aiter]
3113            b.emit(Op::Pop, 0); // [returnValue]
3114        } else if delegate {
3115            // `yield* iterable`: step the delegate through the iterator protocol,
3116            // re-yielding each value and FORWARDING whatever `.next(x)` sent in.
3117            // The expression's value is the delegate's RETURN value, which
3118            // `FORITER` discards — hence the explicit `.next()` calls.
3119            let sent_tmp = self.tmp_name("delegated");
3120            match arg {
3121                Some(e) => self.compile_expr(b, e)?,
3122                None => {
3123                    b.emit(Op::LoadUndef, 0);
3124                }
3125            }
3126            b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
3127                                                         // The delegate is parked on the stack for the whole delegation, so
3128                                                         // it counts as a live iterator: a `.return()`/`.throw()` injected
3129                                                         // into the OUTER generator has to close it (7.4.9 IteratorClose),
3130                                                         // which is what runs the delegate's pending `finally`.
3131            self.iter_depth += 1;
3132            self.note_iter_depth(b);
3133            self.name_const(b, &sent_tmp);
3134            b.emit(Op::LoadUndef, 0);
3135            b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
3136            b.emit(Op::Pop, 0);
3137            let start = b.current_pos();
3138            // One delegation step: `next(sent)`, or — after a forced
3139            // `.return()`/`.throw()` — the delegate's `return`/`throw`.
3140            self.load_local(b, &sent_tmp);
3141            b.emit(Op::CallBuiltin(ops::DELEGATE_STEP, 1), 0); // [iterator, step]
3142            b.emit(Op::Dup, 0);
3143            self.name_const(b, "done");
3144            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
3145            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
3146            let jdone = b.emit(Op::JumpIfTrue(0), 0); // [iterator, step]
3147            self.name_const(b, "value");
3148            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [iterator, value]
3149            let at = b.emit(Op::CallBuiltin(ops::YIELD_DELEGATE, 1), 0); // [iterator, sent]
3150            self.yield_sites.push((at, self.iter_depth));
3151            self.name_const(b, &sent_tmp);
3152            b.emit(Op::Swap, 0);
3153            b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
3154            b.emit(Op::Pop, 0);
3155            b.emit(Op::Jump(start), 0);
3156            let done = b.current_pos();
3157            b.patch_jump(jdone, done);
3158            self.name_const(b, "value"); // [iterator, step, "value"]
3159            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [iterator, returnValue]
3160            b.emit(Op::Swap, 0);
3161            b.emit(Op::Pop, 0); // [returnValue]
3162            self.iter_depth -= 1;
3163            self.note_iter_depth(b);
3164        } else {
3165            match arg {
3166                Some(e) => self.compile_expr(b, e)?,
3167                None => {
3168                    b.emit(Op::LoadUndef, 0);
3169                }
3170            }
3171            // YIELD suspends and leaves the value sent by `.next(x)` on the stack.
3172            let at = b.emit(Op::CallBuiltin(ops::YIELD, 1), 0);
3173            self.yield_sites.push((at, self.iter_depth));
3174        }
3175        Ok(())
3176    }
3177
3178    /// Lower a formal-parameter list into simple slots plus prologue statements
3179    /// (defaults + destructuring), executed at the top of the body.
3180    fn lower_params(&mut self, params: &[Param]) -> Result<(Vec<ParamSlot>, Vec<Stmt>), String> {
3181        // Strict code refuses a DUPLICATE parameter name, and refuses `eval` or
3182        // `arguments` as one. Both are early errors, so they fire before the
3183        // body runs — sloppy code still allows the duplicate, where the LAST
3184        // one wins.
3185        if self.strict {
3186            let mut seen: Vec<String> = Vec::new();
3187            for p in params {
3188                for n in binding_names(&p.pattern) {
3189                    if RESERVED_IN_STRICT.contains(&n.as_str()) {
3190                        return Err(strict_reserved_error());
3191                    }
3192                    if seen.contains(&n) {
3193                        return Err(
3194                            "SyntaxError: Duplicate parameter name not allowed in this context"
3195                                .to_string(),
3196                        );
3197                    }
3198                    seen.push(n);
3199                }
3200            }
3201        }
3202        let mut slots = Vec::new();
3203        let mut prologue: Vec<Stmt> = Vec::new();
3204        for (i, p) in params.iter().enumerate() {
3205            if p.rest {
3206                let name = match &p.pattern {
3207                    Expr::Ident(n) => n.clone(),
3208                    _ => return Err("SyntaxError: rest parameter must be an identifier".into()),
3209                };
3210                slots.push(ParamSlot {
3211                    name,
3212                    rest: true,
3213                    has_default: false,
3214                });
3215                continue;
3216            }
3217            match &p.pattern {
3218                Expr::Ident(name) => {
3219                    slots.push(ParamSlot {
3220                        name: name.clone(),
3221                        rest: false,
3222                        has_default: p.default.is_some(),
3223                    });
3224                    if let Some(d) = &p.default {
3225                        prologue.push(default_stmt(name, d));
3226                    }
3227                }
3228                pattern => {
3229                    let synth = format!(".param{i}");
3230                    slots.push(ParamSlot {
3231                        name: synth.clone(),
3232                        rest: false,
3233                        has_default: p.default.is_some(),
3234                    });
3235                    if let Some(d) = &p.default {
3236                        prologue.push(default_stmt(&synth, d));
3237                    }
3238                    prologue.push(Stmt::from(StmtKind::Decl {
3239                        kind: DeclKind::Let,
3240                        decls: vec![Declarator {
3241                            target: pattern.clone(),
3242                            init: Some(Expr::Ident(synth)),
3243                            bound: Vec::new(),
3244                        }],
3245                    }));
3246                }
3247            }
3248        }
3249        Ok((slots, prologue))
3250    }
3251
3252    // ── expressions ──────────────────────────────────────────────────────
3253    fn compile_expr(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
3254        match e {
3255            Expr::Undefined => {
3256                b.emit(Op::LoadUndef, 0);
3257            }
3258            // A hole only carries its extra meaning INSIDE an array literal
3259            // (`compile_array` records it); evaluated anywhere else it is just
3260            // the `undefined` an elided read produces.
3261            Expr::Hole => {
3262                b.emit(Op::LoadUndef, 0);
3263            }
3264            Expr::Null => {
3265                b.emit(Op::CallBuiltin(ops::LOAD_NULL, 0), 0);
3266            }
3267            Expr::True => {
3268                b.emit(Op::LoadTrue, 0);
3269            }
3270            Expr::False => {
3271                b.emit(Op::LoadFalse, 0);
3272            }
3273            Expr::Number(n) => {
3274                b.emit(Op::LoadFloat(*n), 0);
3275            }
3276            Expr::BigInt(digits) => {
3277                // The canonical decimal digit string travels as a native constant;
3278                // MKBIGINT parses it into a heap BigInt at runtime.
3279                let k = b.add_constant(Value::str(digits));
3280                b.emit(Op::LoadConst(k), 0);
3281                b.emit(Op::CallBuiltin(ops::MKBIGINT, 1), 0);
3282            }
3283            Expr::Regex(pat, flags) => {
3284                let kp = b.add_constant(Value::str(pat));
3285                b.emit(Op::LoadConst(kp), 0);
3286                let kf = b.add_constant(Value::str(flags));
3287                b.emit(Op::LoadConst(kf), 0);
3288                b.emit(Op::CallBuiltin(ops::MKREGEX, 2), 0);
3289            }
3290            Expr::Str(s) => self.strlit(b, s),
3291            Expr::Template { quasis, exprs } => self.compile_template(b, quasis, exprs)?,
3292            Expr::TaggedTemplate {
3293                tag,
3294                quasis,
3295                raws,
3296                exprs,
3297            } => self.compile_tagged_template(b, tag, quasis, raws, exprs)?,
3298            Expr::Ident(n) => self.load_local(b, n),
3299            Expr::This => {
3300                b.emit(Op::CallBuiltin(ops::THIS, 0), 0);
3301            }
3302            Expr::Array(items) => self.compile_array(b, items)?,
3303            Expr::Object(props) => self.compile_object(b, props)?,
3304            Expr::Spread(inner) => self.compile_expr(b, inner)?,
3305            Expr::Logical(op, l, r) => self.compile_logical(b, *op, l, r)?,
3306            Expr::Unary(op, e) => self.compile_unary(b, *op, e)?,
3307            Expr::Binary(op, l, r) => self.compile_binary(b, *op, l, r)?,
3308            Expr::Conditional { test, cons, alt } => {
3309                self.compile_condition(b, test)?;
3310                let jf = b.emit(Op::JumpIfFalse(0), 0);
3311                self.compile_expr(b, cons)?;
3312                let je = b.emit(Op::Jump(0), 0);
3313                let els = b.current_pos();
3314                b.patch_jump(jf, els);
3315                self.compile_expr(b, alt)?;
3316                let end = b.current_pos();
3317                b.patch_jump(je, end);
3318            }
3319            // A COMPOUND assignment (`o[k()] += 1`) evaluates the target
3320            // reference once. Handled ahead of the plain-`=` arms below because
3321            // it must keep that reference on the stack across the read, the
3322            // computation and the write, which a plain assignment never does.
3323            // An unassignable target is rejected (or, for a call, deferred to a
3324            // runtime ReferenceError) before anything else looks at it. A
3325            // destructuring pattern is only legal for plain `=`.
3326            Expr::Assign { target, op, .. }
3327                if self.reject_bad_target(
3328                    b,
3329                    target,
3330                    op.is_none(),
3331                    "Invalid left-hand side in assignment",
3332                )? =>
3333            {
3334                // The throw is already emitted; leave a value for the
3335                // expression's consumer (never reached).
3336                b.emit(Op::LoadUndef, 0);
3337            }
3338            Expr::Update { target, prefix, .. }
3339                if self.reject_bad_target(
3340                    b,
3341                    target,
3342                    false,
3343                    if *prefix {
3344                        "Invalid left-hand side expression in prefix operation"
3345                    } else {
3346                        "Invalid left-hand side expression in postfix operation"
3347                    },
3348                )? =>
3349            {
3350                b.emit(Op::LoadUndef, 0);
3351            }
3352            Expr::Assign {
3353                target,
3354                op: Some(aop),
3355                value,
3356            } => self.compile_compound_assign(b, target, *aop, value)?,
3357            // 13.15.1 / 13.4.1: strict code may not assign to, or update,
3358            // `eval` or `arguments`. Both are early errors.
3359            Expr::Assign { target, .. } | Expr::Update { target, .. }
3360                if self.strict
3361                    && matches!(&**target, Expr::Ident(n)
3362                        if RESERVED_IN_STRICT.contains(&n.as_str())) =>
3363            {
3364                return Err(strict_reserved_error());
3365            }
3366            Expr::Assign { target, value, .. } => match &**target {
3367                // 13.15.2 steps 1.a-1.f: for a PROPERTY target the reference is
3368                // evaluated first — the object, then the key — and only then the
3369                // right-hand side. Routing these through `compile_bind` emitted
3370                // the value first and the reference after, so every side effect
3371                // in the target ran in the wrong order: `o[k()] = v()` called
3372                // `v` before `k`, and `a[i++] = f()` passed `f` the
3373                // already-incremented index. Both builtins return the value they
3374                // stored, which is also the value of the assignment expression,
3375                // so the `Dup`/`Rot`/`Pop` the generic path needed all fall away.
3376                Expr::Member {
3377                    object, property, ..
3378                } if matches!(**object, Expr::Super) => {
3379                    self.name_const(b, property); // [name]
3380                    self.compile_expr(b, value)?; // [name, value]
3381                    b.emit(Op::CallBuiltin(ops::SUPER_SET, 2), 0); // [value]
3382                }
3383                Expr::Index { object, index, .. } if matches!(**object, Expr::Super) => {
3384                    self.compile_expr(b, index)?; // [key]
3385                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3386                    self.compile_expr(b, value)?; // [key, value]
3387                    b.emit(Op::CallBuiltin(ops::SUPER_SET, 2), 0); // [value]
3388                }
3389                Expr::Member {
3390                    object, property, ..
3391                } => {
3392                    self.compile_expr(b, object)?; // [recv]
3393                    self.name_const(b, property); // [recv, name]
3394                    self.compile_expr(b, value)?; // [recv, name, value]
3395                    b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0); // [value]
3396                }
3397                Expr::Index { object, index, .. } => {
3398                    self.compile_expr(b, object)?; // [recv]
3399                    self.compile_expr(b, index)?; // [recv, idx]
3400                    self.compile_expr(b, value)?; // [recv, idx, value]
3401                    b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0); // [value]
3402                }
3403                _ => {
3404                    self.compile_expr(b, value)?;
3405                    // 13.15.2 step 1.e: `h = function(){}` names the function `h`.
3406                    // Only an IdentifierReference target counts — `o.p = function(){}`
3407                    // leaves the name empty in node too.
3408                    if let Expr::Ident(n) = &**target {
3409                        self.infer_name(b, value, n);
3410                    }
3411                    b.emit(Op::Dup, 0); // assignment yields the value
3412                    self.destructure_src = destructure_source_text(value);
3413                    let r = self.compile_bind(b, target, BindMode::Assign);
3414                    self.destructure_src = None;
3415                    r?;
3416                }
3417            },
3418            Expr::Update { op, prefix, target } => self.compile_update(b, *op, *prefix, target)?,
3419            // A chain's ROOT opens the frame its `?.` links park their jumps
3420            // in; nested links see it already open and add to it.
3421            Expr::Call { pos, .. } | Expr::Member { pos, .. } | Expr::Index { pos, .. }
3422                if self.opt_chain.is_empty() && Self::spine_has_optional(e) =>
3423            {
3424                let start = b.current_pos();
3425                self.compile_chain_root(b, e)?;
3426                self.mark_pos(b, start, *pos, PosScope::Operation);
3427            }
3428            Expr::Call {
3429                func,
3430                args,
3431                optional,
3432                pos,
3433            } => {
3434                let start = b.current_pos();
3435                self.compile_call(b, func, args, *optional)?;
3436                self.mark_pos(b, start, *pos, PosScope::Operation);
3437            }
3438            Expr::New { callee, args, pos } => {
3439                let start = b.current_pos();
3440                self.compile_new(b, callee, args)?;
3441                self.mark_pos(b, start, *pos, PosScope::Operation);
3442            }
3443            Expr::Member {
3444                object,
3445                property,
3446                optional,
3447                pos,
3448            } => {
3449                let start = b.current_pos();
3450                self.compile_member(b, object, property, *optional)?;
3451                self.mark_pos(b, start, *pos, PosScope::Operation);
3452            }
3453            Expr::Index {
3454                object,
3455                index,
3456                optional,
3457                pos,
3458            } => {
3459                let start = b.current_pos();
3460                self.compile_index(b, object, index, *optional)?;
3461                self.mark_pos(b, start, *pos, PosScope::Operation);
3462            }
3463            Expr::Function {
3464                params,
3465                body,
3466                is_arrow,
3467                name,
3468                is_generator,
3469                is_async,
3470                is_method,
3471                span,
3472            } => {
3473                let def_id = if *is_arrow {
3474                    self.build_arrow(params, body, *is_async)?
3475                } else {
3476                    let n = name.clone().unwrap_or_default();
3477                    let stmts = match body {
3478                        FnBody::Block(b) => b.clone(),
3479                        FnBody::Expr(e) => vec![Stmt::from(StmtKind::Return(Some((**e).clone())))],
3480                    };
3481                    let id = self.build_function(&n, params, &stmts, *is_generator, *is_async)?;
3482                    // A NAMED function expression binds its own name inside the body
3483                    // (object/class methods parse with `name: None`, so this only
3484                    // fires for `function name(…) {…}` in expression position).
3485                    if name.is_some() {
3486                        self.functions[id].1.self_name = true;
3487                    }
3488                    self.functions[id].1.is_method = *is_method;
3489                    id
3490                };
3491                self.functions[def_id].1.span = *span;
3492                self.emit_mkfunc(b, def_id);
3493            }
3494            Expr::Class(node) => self.compile_class(b, node)?,
3495            Expr::Super => {
3496                // Bare `super` only appears as a call/member callee, handled by
3497                // compile_call / compile_member; a stray `super` yields undefined.
3498                b.emit(Op::LoadUndef, 0);
3499            }
3500            Expr::NewTarget => {
3501                b.emit(Op::CallBuiltin(ops::NEW_TARGET, 0), 0);
3502            }
3503            Expr::Yield { arg, delegate } => self.compile_yield(b, arg, *delegate)?,
3504            Expr::Await(inner, pos) => {
3505                self.compile_expr(b, inner)?;
3506                let start = b.current_pos();
3507                b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0);
3508                self.mark_pos(b, start, *pos, PosScope::Operation);
3509            }
3510            Expr::Sequence(items) => {
3511                for (i, it) in items.iter().enumerate() {
3512                    self.compile_expr(b, it)?;
3513                    if i + 1 < items.len() {
3514                        b.emit(Op::Pop, 0);
3515                    }
3516                }
3517            }
3518        }
3519        Ok(())
3520    }
3521
3522    fn compile_template(
3523        &mut self,
3524        b: &mut ChunkBuilder,
3525        quasis: &[String],
3526        exprs: &[Expr],
3527    ) -> Result<(), String> {
3528        let mut n = 0;
3529        for (i, q) in quasis.iter().enumerate() {
3530            let k = b.add_constant(Value::str(q));
3531            b.emit(Op::LoadConst(k), 0);
3532            n += 1;
3533            if i < exprs.len() {
3534                self.compile_expr(b, &exprs[i])?;
3535                b.emit(Op::CallBuiltin(ops::TOSTR, 1), 0);
3536                n += 1;
3537            }
3538        }
3539        b.emit(Op::CallBuiltin(ops::MKSTR, argc(n)?), 0);
3540        Ok(())
3541    }
3542
3543    /// Lower a tagged template to `TAG_TMPL`. Operand layout (matching
3544    /// `builtins::b_tag_tmpl`): `[this, tag, n, m, site, cooked×n, raw×n,
3545    /// values×m]`, where `n = quasis.len()` and `m = exprs.len()`
3546    /// (`n == m + 1`).
3547    ///
3548    /// `this` is the tag's receiver. A tagged template IS a call (13.3.11.1
3549    /// evaluates the tag as a MemberExpression and passes its reference's base
3550    /// as the `this` argument), so ``o.m`a` `` runs `m` with `this === o` — it
3551    /// ran with `this` undefined, which broke every tag written as a method.
3552    /// `undefined` for a tag that is not a property reference.
3553    ///
3554    /// `site` is this site's ordinal in the compilation; the runtime caches the
3555    /// template object under it so a site evaluated twice hands back the same
3556    /// object.
3557    fn compile_tagged_template(
3558        &mut self,
3559        b: &mut ChunkBuilder,
3560        tag: &Expr,
3561        quasis: &[String],
3562        raws: &[String],
3563        exprs: &[Expr],
3564    ) -> Result<(), String> {
3565        match tag {
3566            // `o.m`…`` / `o?.m`…`` — the receiver stays on the stack under the
3567            // method, so both are evaluated exactly once.
3568            Expr::Member {
3569                object,
3570                property,
3571                optional: false,
3572                ..
3573            } if !matches!(**object, Expr::Super) => {
3574                self.compile_expr(b, object)?; // [o]
3575                b.emit(Op::Dup, 0); // [o, o]
3576                self.name_const(b, property);
3577                b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [o, f]
3578            }
3579            _ => {
3580                b.emit(Op::LoadUndef, 0);
3581                self.compile_expr(b, tag)?;
3582            }
3583        }
3584        let n = quasis.len();
3585        let m = exprs.len();
3586        let site = self.tmpl_sites;
3587        self.tmpl_sites += 1;
3588        b.emit(Op::LoadInt(n as i64), 0);
3589        b.emit(Op::LoadInt(m as i64), 0);
3590        b.emit(Op::LoadInt(site as i64), 0);
3591        for q in quasis {
3592            self.strlit(b, q); // cooked strings (heap)
3593        }
3594        for r in raws {
3595            self.strlit(b, r); // raw strings (heap)
3596        }
3597        for e in exprs {
3598            self.compile_expr(b, e)?; // substitution values
3599        }
3600        b.emit(Op::CallBuiltin(ops::TAG_TMPL, argc(5 + 2 * n + m)?), 0);
3601        Ok(())
3602    }
3603
3604    fn compile_array(&mut self, b: &mut ChunkBuilder, items: &[Expr]) -> Result<(), String> {
3605        if items.iter().any(|e| matches!(e, Expr::Spread(_))) {
3606            // (tag, value) pairs; tag 1 = spread, tag 2 = elision. A spread
3607            // makes every later element's index a RUN-TIME quantity, so the
3608            // holes cannot be recorded from here — the tag carries the fact and
3609            // `BUILD_ARGS` marks them as it walks.
3610            for it in items {
3611                match it {
3612                    Expr::Spread(inner) => {
3613                        b.emit(Op::LoadInt(1), 0);
3614                        self.compile_expr(b, inner)?;
3615                    }
3616                    Expr::Hole => {
3617                        b.emit(Op::LoadInt(2), 0);
3618                        b.emit(Op::LoadUndef, 0);
3619                    }
3620                    _ => {
3621                        b.emit(Op::LoadInt(0), 0);
3622                        self.compile_expr(b, it)?;
3623                    }
3624                }
3625            }
3626            let at = b.current_pos();
3627            b.emit(Op::CallBuiltin(ops::BUILD_ARGS, argc(items.len() * 2)?), 0);
3628            // A spread over a non-iterable names the SOURCE: `[...o]` reports
3629            // `o is not iterable`. One op covers the whole literal, so the text
3630            // is recorded only when a SINGLE spread could have raised it —
3631            // with two, this cannot say which one did, and naming the wrong
3632            // expression is worse than rendering the value.
3633            let texts: Vec<Option<String>> = items
3634                .iter()
3635                .filter_map(|e| match e {
3636                    Expr::Spread(inner) => Some(callee_text(inner)),
3637                    _ => None,
3638                })
3639                .collect();
3640            // One op covers the whole literal, so a name can be recorded only
3641            // when every spread would produce the SAME one — with one spread
3642            // trivially, and with `[...o, ...o]` because either is the answer.
3643            // Two DIFFERENT sources cannot be told apart here, and naming the
3644            // wrong expression is worse than rendering the value.
3645            if let Some(first) = texts.first().cloned().flatten() {
3646                if texts.iter().all(|t| t.as_deref() == Some(first.as_str())) {
3647                    self.call_sites.push((at, first));
3648                }
3649            }
3650        } else if items.len() <= u8::MAX as usize {
3651            for it in items {
3652                self.compile_expr(b, it)?;
3653            }
3654            b.emit(Op::CallBuiltin(ops::MKARR, argc(items.len())?), 0);
3655            self.mark_literal_holes(b, items);
3656        } else {
3657            // A literal larger than one CallBuiltin's u8 arg count can hold (the
3658            // generated data tables in iconv-lite hit this): start from an empty
3659            // array and append each element with an indexed store, keeping the
3660            // array on the stack across iterations.
3661            b.emit(Op::CallBuiltin(ops::MKARR, 0), 0); // [arr]
3662            for (i, it) in items.iter().enumerate() {
3663                b.emit(Op::Dup, 0); // [arr, arr]
3664                b.emit(Op::LoadInt(i as i64), 0); // [arr, arr, i]
3665                self.compile_expr(b, it)?; // [arr, arr, i, val]
3666                b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0); // -> [arr, val]
3667                b.emit(Op::Pop, 0); // [arr]
3668            }
3669            // After the writes: a `SETITEM` CLEARS the hole at the index it
3670            // writes, so marking has to come last.
3671            self.mark_literal_holes(b, items);
3672        }
3673        Ok(())
3674    }
3675
3676    /// Emit a `MARK_HOLE` per elided position of a spread-free array literal,
3677    /// with the finished array on top of the stack. Emits nothing at all for the
3678    /// dense literals that are essentially every literal in real code.
3679    fn mark_literal_holes(&mut self, b: &mut ChunkBuilder, items: &[Expr]) {
3680        for (i, it) in items.iter().enumerate() {
3681            if !matches!(it, Expr::Hole) {
3682                continue;
3683            }
3684            b.emit(Op::Dup, 0); // [arr, arr]
3685            b.emit(Op::LoadInt(i as i64), 0); // [arr, arr, i]
3686            b.emit(Op::CallBuiltin(ops::MARK_HOLE, 2), 0); // [arr, undefined]
3687            b.emit(Op::Pop, 0); // [arr]
3688        }
3689    }
3690
3691    fn compile_object(&mut self, b: &mut ChunkBuilder, props: &[Prop]) -> Result<(), String> {
3692        // (tag, key, val) triples for the data/spread props; tag 1 = ...spread.
3693        // Accessors are installed afterward via DEF_ACCESSOR.
3694        // An ACCESSOR keeps its slot in this list — with a tag of its own — so
3695        // the object enumerates it where the source declared it. The pair
3696        // `get`/`set` for one key contributes ONE slot.
3697        let mut seen_accessor: Vec<String> = Vec::new();
3698        let data: Vec<&Prop> = props
3699            .iter()
3700            .filter(|p| match p {
3701                Prop::Accessor { key, computed, .. } => {
3702                    // Only a literal key can be de-duplicated at compile time; a
3703                    // computed one is settled by `b_mkobj`'s `or_insert`.
3704                    let literal = match (key, computed) {
3705                        (Expr::Str(s), false) => Some(s.clone()),
3706                        _ => None,
3707                    };
3708                    match literal {
3709                        Some(k) if seen_accessor.contains(&k) => false,
3710                        Some(k) => {
3711                            seen_accessor.push(k);
3712                            true
3713                        }
3714                        None => true,
3715                    }
3716                }
3717                _ => true,
3718            })
3719            .collect();
3720        let has_spread = data.iter().any(|p| matches!(p, Prop::Spread(_)));
3721        // A spread-free literal with more triples than one CallBuiltin's u8 arg
3722        // count can hold (iconv-lite's generated codepage tables are 150+ keys)
3723        // is built incrementally: start empty, store each key, keeping the object
3724        // on the stack. Spread merges need the single-shot MKOBJ tag path, so
3725        // large-with-spread stays on it (a rare, genuine limitation).
3726        if data.len() * 3 > u8::MAX as usize && !has_spread {
3727            b.emit(Op::CallBuiltin(ops::MKOBJ, 0), 0); // [obj]
3728            for p in &data {
3729                if let Prop::KeyValue {
3730                    key,
3731                    value,
3732                    computed,
3733                } = p
3734                {
3735                    b.emit(Op::Dup, 0); // [obj, obj]
3736                    self.compile_expr(b, key)?;
3737                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0); // [obj, obj, key]
3738                    self.emit_keyed_value(b, key, value, *computed, member::METHOD)?;
3739                    b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0); // -> [obj, val]
3740                    b.emit(Op::Pop, 0); // [obj]
3741                }
3742            }
3743            // The incremental path's accessors keep their trailing order: a
3744            // literal that large is a generated data table, and none carry one.
3745            return self.compile_object_accessors(b, props);
3746        }
3747        for p in &data {
3748            match p {
3749                Prop::KeyValue {
3750                    key,
3751                    value,
3752                    computed,
3753                } => {
3754                    // Tag 3 marks a METHOD DEFINITION, so `MKOBJ` can give it
3755                    // the literal as its `[[HomeObject]]`. It has to be decided
3756                    // HERE: a method assigned from elsewhere (`{ m: other.m }`)
3757                    // is an ordinary value whose home object was fixed where it
3758                    // was defined, and the runtime cannot tell the two apart
3759                    // from the value alone.
3760                    let defines_method = matches!(
3761                        value,
3762                        Expr::Function {
3763                            is_method: true,
3764                            ..
3765                        }
3766                    );
3767                    // Tag 4 marks a COMPUTED key: `{ ["__proto__"]: v }` defines an own
3768                    // property (B.3.1 applies only to the literal `__proto__: v` form).
3769                    let tag = if defines_method {
3770                        3
3771                    } else if *computed {
3772                        4
3773                    } else {
3774                        0
3775                    };
3776                    b.emit(Op::LoadInt(tag), 0);
3777                    // Key coerces to a property key (Symbol-aware: a Symbol maps to
3778                    // its internal `@@…` key rather than a `String()` coercion).
3779                    self.compile_expr(b, key)?;
3780                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3781                    self.emit_keyed_value(b, key, value, *computed, member::METHOD)?;
3782                }
3783                Prop::Spread(src) => {
3784                    b.emit(Op::LoadInt(1), 0);
3785                    self.compile_expr(b, src)?;
3786                    b.emit(Op::LoadUndef, 0);
3787                }
3788                // Reserve the accessor's enumeration slot; `DEF_ACCESSOR` below
3789                // installs the functions themselves.
3790                Prop::Accessor { key, computed, .. } => {
3791                    let _ = computed; // the key expression covers both forms
3792                    b.emit(Op::LoadInt(2), 0);
3793                    self.compile_expr(b, key)?;
3794                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3795                    b.emit(Op::LoadUndef, 0);
3796                }
3797            }
3798        }
3799        b.emit(Op::CallBuiltin(ops::MKOBJ, argc(data.len() * 3)?), 0); // [obj]
3800        self.compile_object_accessors(b, props)
3801    }
3802
3803    /// Install any getter/setter accessors of an object literal onto the object
3804    /// left on the stack (shared by the single-shot and incremental build paths).
3805    fn compile_object_accessors(
3806        &mut self,
3807        b: &mut ChunkBuilder,
3808        props: &[Prop],
3809    ) -> Result<(), String> {
3810        for p in props {
3811            if let Prop::Accessor {
3812                key,
3813                computed,
3814                is_getter,
3815                func,
3816            } = p
3817            {
3818                if *computed {
3819                    self.compile_expr(b, key)?;
3820                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3821                } else if let Expr::Str(s) = key {
3822                    self.name_const(b, s);
3823                } else {
3824                    self.compile_expr(b, key)?;
3825                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
3826                }
3827                let kind = if *is_getter { member::GET } else { member::SET };
3828                b.emit(Op::LoadInt(kind), 0);
3829                // `{ get g(){} }` names the getter `get g` (10.2.9 step 4 via
3830                // 13.2.5.5). A COMPUTED accessor key is the one member position
3831                // whose key is not still reachable on the stack here — `kind`
3832                // sits between it and the function — so it keeps the empty name.
3833                if *computed {
3834                    self.compile_expr(b, func)?;
3835                } else if let Expr::Str(s) = key {
3836                    self.compile_expr(b, func)?;
3837                    let prefix = if *is_getter { "get" } else { "set" };
3838                    self.infer_name(b, func, &format!("{prefix} {s}"));
3839                } else {
3840                    self.compile_expr(b, func)?;
3841                }
3842                b.emit(Op::CallBuiltin(ops::DEF_ACCESSOR, 4), 0);
3843            }
3844        }
3845        Ok(())
3846    }
3847
3848    fn compile_logical(
3849        &mut self,
3850        b: &mut ChunkBuilder,
3851        op: LogicalOp,
3852        l: &Expr,
3853        r: &Expr,
3854    ) -> Result<(), String> {
3855        self.compile_expr(b, l)?;
3856        b.emit(Op::Dup, 0);
3857        let test_op = match op {
3858            LogicalOp::And | LogicalOp::Or => ops::TRUTHY,
3859            LogicalOp::Nullish => ops::NULLISH,
3860        };
3861        b.emit(Op::CallBuiltin(test_op, 1), 0);
3862        let jump = match op {
3863            LogicalOp::And => b.emit(Op::JumpIfFalse(0), 0), // false -> keep left
3864            LogicalOp::Or => b.emit(Op::JumpIfTrue(0), 0),   // true -> keep left
3865            LogicalOp::Nullish => b.emit(Op::JumpIfFalse(0), 0), // not-nullish -> keep left
3866        };
3867        b.emit(Op::Pop, 0); // drop left, evaluate right
3868        self.compile_expr(b, r)?;
3869        let end = b.current_pos();
3870        b.patch_jump(jump, end);
3871        Ok(())
3872    }
3873
3874    /// `target op= value` with the target reference evaluated exactly ONCE.
3875    ///
3876    /// The parser hands the operator over instead of rewriting `a op= b` into
3877    /// `a = a op b`; that rewrite duplicated the target subtree, so every side
3878    /// effect in it ran twice (`o[k()] += 1` called `k` twice, and the logical
3879    /// forms called it twice even when they short-circuited and never wrote).
3880    /// The duplication could not be repaired downstream: after the rewrite,
3881    /// `o[k()] += 1` and the genuinely-twice-calling `o[k()] = o[k()] + 1` are
3882    /// the same tree.
3883    ///
3884    /// For a property target the reference is the pair `[recv, key]`, which
3885    /// `Dup2` copies for the read while the originals serve for the write. An
3886    /// identifier target has no reference to preserve — reading a name twice
3887    /// has no observable effect — so it keeps the simple lowering.
3888    fn compile_compound_assign(
3889        &mut self,
3890        b: &mut ChunkBuilder,
3891        target: &Expr,
3892        aop: AssignOp,
3893        value: &Expr,
3894    ) -> Result<(), String> {
3895        // The reference: leave `[recv, key]` on the stack, and report which
3896        // builtin pair reads and writes through it.
3897        let (get, set) = match target {
3898            // `super.x op= v` has no `[recv, key]` pair to keep: `super` is not
3899            // a value. Reading it twice is unobservable, so it takes the
3900            // identifier lowering (`super.x = super.x op v`).
3901            Expr::Member { object, .. } | Expr::Index { object, .. }
3902                if matches!(**object, Expr::Super) =>
3903            {
3904                return self.compile_compound_ident(b, target, aop, value);
3905            }
3906            Expr::Member {
3907                object, property, ..
3908            } => {
3909                self.compile_expr(b, object)?; // [recv]
3910                self.name_const(b, property); // [recv, name]
3911                (ops::GETATTR, ops::SETATTR)
3912            }
3913            Expr::Index { object, index, .. } => {
3914                self.compile_expr(b, object)?; // [recv]
3915                self.compile_expr(b, index)?; // [recv, idx]
3916                (ops::GETITEM, ops::SETITEM)
3917            }
3918            // An identifier (or anything else `compile_bind` accepts): no
3919            // reference to preserve, so read it, combine, and bind the result.
3920            _ => return self.compile_compound_ident(b, target, aop, value),
3921        };
3922        b.emit(Op::Dup2, 0); // [recv, key, recv, key]
3923        b.emit(Op::CallBuiltin(get, 2), 0); // [recv, key, old]
3924        match aop {
3925            AssignOp::Binary(op) => {
3926                self.emit_compound_binop(b, op, value)?; // [recv, key, new]
3927                b.emit(Op::CallBuiltin(set, 3), 0); // [new]
3928            }
3929            AssignOp::Logical(lop) => {
3930                // Short-circuit: the write is skipped entirely when the old
3931                // value already decides the result. That is the case the
3932                // duplicating desugaring got most visibly wrong — it evaluated
3933                // the target a second time to perform a write that the spec
3934                // says never happens.
3935                b.emit(Op::Dup, 0); // [recv, key, old, old]
3936                let test_op = match lop {
3937                    LogicalOp::And | LogicalOp::Or => ops::TRUTHY,
3938                    LogicalOp::Nullish => ops::NULLISH,
3939                };
3940                b.emit(Op::CallBuiltin(test_op, 1), 0); // [recv, key, old, cond]
3941                let skip = match lop {
3942                    LogicalOp::And => b.emit(Op::JumpIfFalse(0), 0), // falsy -> keep old
3943                    LogicalOp::Or => b.emit(Op::JumpIfTrue(0), 0),   // truthy -> keep old
3944                    LogicalOp::Nullish => b.emit(Op::JumpIfFalse(0), 0), // non-nullish -> keep old
3945                };
3946                b.emit(Op::Pop, 0); // drop old: [recv, key]
3947                self.compile_expr(b, value)?; // [recv, key, rhs]
3948                b.emit(Op::CallBuiltin(set, 3), 0); // [rhs]
3949                let done = b.emit(Op::Jump(0), 0);
3950                // Short-circuit landing: `[recv, key, old]` has to become
3951                // `[old]` with no write. There is no "drop the two below the
3952                // top", so the old value is rotated under and the reference
3953                // popped out from beneath it.
3954                let short = b.current_pos();
3955                b.patch_jump(skip, short);
3956                b.emit(Op::Rot, 0); // [key, old, recv]
3957                b.emit(Op::Pop, 0); // [key, old]
3958                b.emit(Op::Swap, 0); // [old, key]
3959                b.emit(Op::Pop, 0); // [old]
3960                let end = b.current_pos();
3961                b.patch_jump(done, end);
3962            }
3963        }
3964        Ok(())
3965    }
3966
3967    /// `x op= value` for an identifier target: the name may be read twice with
3968    /// no observable difference, so this keeps the pre-existing desugaring.
3969    fn compile_compound_ident(
3970        &mut self,
3971        b: &mut ChunkBuilder,
3972        target: &Expr,
3973        aop: AssignOp,
3974        value: &Expr,
3975    ) -> Result<(), String> {
3976        let rebuilt = match aop {
3977            AssignOp::Binary(op) => {
3978                Expr::Binary(op, Box::new(target.clone()), Box::new(value.clone()))
3979            }
3980            AssignOp::Logical(lop) => {
3981                Expr::Logical(lop, Box::new(target.clone()), Box::new(value.clone()))
3982            }
3983        };
3984        self.compile_expr(
3985            b,
3986            &Expr::Assign {
3987                target: Box::new(target.clone()),
3988                op: None,
3989                value: Box::new(rebuilt),
3990            },
3991        )
3992    }
3993
3994    /// The old value is already on the stack; compile `rhs` and combine the two
3995    /// with `op`, leaving one value in their place.
3996    ///
3997    /// This mirrors [`Self::compile_binary`], which cannot be reused because it
3998    /// compiles both operands itself — and for the bitwise family it pushes an
3999    /// operator TAG *below* them, which is why those arms slide the tag under
4000    /// the already-present old value rather than simply emitting it.
4001    fn emit_compound_binop(
4002        &mut self,
4003        b: &mut ChunkBuilder,
4004        op: BinOp,
4005        rhs: &Expr,
4006    ) -> Result<(), String> {
4007        let bitwise = match op {
4008            BinOp::BitAnd => Some(bop::BITAND),
4009            BinOp::BitOr => Some(bop::BITOR),
4010            BinOp::BitXor => Some(bop::BITXOR),
4011            BinOp::Shl => Some(bop::SHL),
4012            BinOp::Shr => Some(bop::SHR),
4013            BinOp::UShr => Some(bop::USHR),
4014            _ => None,
4015        };
4016        if let Some(tag) = bitwise {
4017            b.emit(Op::LoadInt(tag), 0); // [old, tag]
4018            b.emit(Op::Swap, 0); // [tag, old]
4019            self.compile_expr(b, rhs)?; // [tag, old, rhs]
4020            b.emit(Op::CallBuiltin(ops::BINOP, 3), 0);
4021            return Ok(());
4022        }
4023        self.compile_expr(b, rhs)?; // [old, rhs]
4024        match op {
4025            BinOp::Add => b.emit(Op::Add, 0),
4026            BinOp::Sub => b.emit(Op::Sub, 0),
4027            BinOp::Mul => b.emit(Op::Mul, 0),
4028            BinOp::Mod => b.emit(Op::Mod, 0),
4029            // `/` and `**` are builtins rather than the native ops, for the same
4030            // reason `compile_binary` routes them that way: fusevm's division
4031            // answers `Undef` on a zero divisor and its `pow` is IEEE-754.
4032            BinOp::Div => b.emit(Op::CallBuiltin(ops::DIV, 2), 0),
4033            BinOp::Pow => b.emit(Op::CallBuiltin(ops::POW, 2), 0),
4034            // No other operator has an `op=` spelling.
4035            _ => return Err(format!("unsupported compound assignment operator {op:?}")),
4036        };
4037        Ok(())
4038    }
4039
4040    fn compile_unary(&mut self, b: &mut ChunkBuilder, op: UnOp, e: &Expr) -> Result<(), String> {
4041        match op {
4042            UnOp::Neg => {
4043                self.compile_expr(b, e)?;
4044                b.emit(Op::Negate, 0);
4045            }
4046            UnOp::Not => {
4047                self.compile_condition(b, e)?;
4048                b.emit(Op::LogNot, 0);
4049            }
4050            UnOp::Pos => {
4051                b.emit(Op::LoadInt(unop::POS), 0);
4052                self.compile_expr(b, e)?;
4053                b.emit(Op::CallBuiltin(ops::UNARY, 2), 0);
4054            }
4055            UnOp::BitNot => {
4056                b.emit(Op::LoadInt(unop::BITNOT), 0);
4057                self.compile_expr(b, e)?;
4058                b.emit(Op::CallBuiltin(ops::UNARY, 2), 0);
4059            }
4060            UnOp::TypeOf => {
4061                // `typeof <bare ident>` must NOT throw when the name is unbound —
4062                // JS returns "undefined". Route a plain identifier through a
4063                // non-throwing name read; any other operand evaluates normally.
4064                if let Expr::Ident(n) = e {
4065                    // A slotted local is always bound by the time it is read
4066                    // (that is rule 3 of the slot analysis), so there is no
4067                    // unbound case for `TYPEOF_NAME` to absorb.
4068                    if let Some(slot) = self.slot_of(n) {
4069                        b.emit(Op::GetSlot(slot), 0);
4070                        b.emit(Op::CallBuiltin(ops::TYPEOF, 1), 0);
4071                        return Ok(());
4072                    }
4073                    self.name_const(b, n);
4074                    let op = if self.with_depth > 0 {
4075                        ops::WITH_TYPEOF
4076                    } else {
4077                        ops::TYPEOF_NAME
4078                    };
4079                    b.emit(Op::CallBuiltin(op, 1), 0);
4080                } else {
4081                    self.compile_expr(b, e)?;
4082                    b.emit(Op::CallBuiltin(ops::TYPEOF, 1), 0);
4083                }
4084            }
4085            UnOp::Void => {
4086                self.compile_expr(b, e)?;
4087                b.emit(Op::Pop, 0);
4088                b.emit(Op::LoadUndef, 0);
4089            }
4090            // STRICT mode turns a refused delete into a TypeError (13.5.1.2
4091            // step 5.b). Strictness is static, so it rides along as a third
4092            // operand rather than being looked up at run time — and the error
4093            // is raised where the key and the receiver are both still in hand,
4094            // which a compiler-side check after the Bool could not manage.
4095            UnOp::Delete if self.strict && matches!(e, Expr::Ident(_)) => {
4096                // 13.5.1.1: `delete x` on a plain name is an early error in
4097                // strict code, whatever `x` is bound to.
4098                return Err(
4099                    "SyntaxError: Delete of an unqualified identifier in strict mode.".to_string(),
4100                );
4101            }
4102            // `delete a?.b.c`: the operand is an optional chain, and a
4103            // short-circuit anywhere along it makes the whole `delete` evaluate
4104            // to `true` without touching any object (13.5.1.2 step 1 — the
4105            // OptionalExpression evaluates to `undefined`, not a Reference).
4106            UnOp::Delete if Self::spine_has_optional(e) => {
4107                self.opt_chain.push(Vec::new());
4108                let r = self.compile_delete_target(b, e);
4109                let pending = self.opt_chain.pop().unwrap_or_default();
4110                r?;
4111                let jdone = b.emit(Op::Jump(0), 0);
4112                let short = b.current_pos();
4113                for j in pending {
4114                    b.patch_jump(j, short);
4115                }
4116                // A short-circuit lands with `undefined` on the stack.
4117                b.emit(Op::Pop, 0);
4118                b.emit(Op::LoadTrue, 0);
4119                let end = b.current_pos();
4120                b.patch_jump(jdone, end);
4121            }
4122            UnOp::Delete => self.compile_delete_target(b, e)?,
4123        }
4124        Ok(())
4125    }
4126
4127    /// Lower the operand of `delete`: a property reference deletes, anything
4128    /// else evaluates to `true`. Inside an open optional chain the LAST link's
4129    /// own `?.` parks its short-circuit in the chain frame like any other link.
4130    fn compile_delete_target(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
4131        match e {
4132            Expr::Member {
4133                object,
4134                property,
4135                optional,
4136                ..
4137            } => {
4138                self.compile_expr(b, object)?;
4139                if *optional {
4140                    self.park_optional_guard(b);
4141                }
4142                self.name_const(b, property);
4143                self.emit_bool(b, self.strict);
4144                b.emit(Op::CallBuiltin(ops::DELPROP_NAME, 3), 0);
4145            }
4146            Expr::Index {
4147                object,
4148                index,
4149                optional,
4150                ..
4151            } => {
4152                self.compile_expr(b, object)?;
4153                if *optional {
4154                    self.park_optional_guard(b);
4155                }
4156                self.compile_off_spine(b, index)?;
4157                self.emit_bool(b, self.strict);
4158                b.emit(Op::CallBuiltin(ops::DELITEM, 3), 0);
4159            }
4160            Expr::Ident(_) => {
4161                b.emit(Op::LoadTrue, 0);
4162            }
4163            // 13.5.1.2 step 2: a non-Reference operand is still EVALUATED —
4164            // `delete f()` calls `f` — and the result is `true`.
4165            _ => {
4166                self.compile_expr(b, e)?;
4167                b.emit(Op::Pop, 0);
4168                b.emit(Op::LoadTrue, 0);
4169            }
4170        }
4171        Ok(())
4172    }
4173
4174    /// Emit a `?.` guard whose short-circuit jump belongs to the innermost open
4175    /// chain frame. Only called with a frame open.
4176    fn park_optional_guard(&mut self, b: &mut ChunkBuilder) {
4177        let j = self.emit_optional_guard(b);
4178        if let Some(frame) = self.opt_chain.last_mut() {
4179            frame.push(j);
4180        }
4181    }
4182
4183    fn compile_binary(
4184        &mut self,
4185        b: &mut ChunkBuilder,
4186        op: BinOp,
4187        l: &Expr,
4188        r: &Expr,
4189    ) -> Result<(), String> {
4190        // Native fast path (JIT-traceable); the numeric hook supplies JS
4191        // semantics for non-number operands.
4192        macro_rules! native {
4193            ($opc:expr) => {{
4194                self.compile_expr(b, l)?;
4195                self.compile_expr(b, r)?;
4196                b.emit($opc, 0);
4197                return Ok(());
4198            }};
4199        }
4200        match op {
4201            BinOp::Add => native!(Op::Add),
4202            BinOp::Sub => native!(Op::Sub),
4203            BinOp::Mul => native!(Op::Mul),
4204            BinOp::Div => {
4205                // NOT native `Op::Div`: fusevm returns `Undef` for a zero divisor,
4206                // but JS needs `x/0 === ±Infinity` / `0/0 === NaN`, so `/` is a
4207                // builtin (fusevm's own documented pattern for non-default `/`).
4208                self.compile_expr(b, l)?;
4209                self.compile_expr(b, r)?;
4210                b.emit(Op::CallBuiltin(ops::DIV, 2), 0);
4211                return Ok(());
4212            }
4213            BinOp::Mod => native!(Op::Mod),
4214            // NOT native `Op::Pow`, for the same reason `/` is a builtin above:
4215            // fusevm's is IEEE-754 `pow`, where `(-1) ** Infinity` and `1 ** NaN`
4216            // come back 1 rather than the spec's NaN.
4217            BinOp::Pow => {
4218                self.compile_expr(b, l)?;
4219                self.compile_expr(b, r)?;
4220                b.emit(Op::CallBuiltin(ops::POW, 2), 0);
4221                return Ok(());
4222            }
4223            BinOp::Lt => native!(Op::NumLt),
4224            BinOp::Le => native!(Op::NumLe),
4225            BinOp::Gt => native!(Op::NumGt),
4226            BinOp::Ge => native!(Op::NumGe),
4227            BinOp::EqEqEq => {
4228                self.compile_expr(b, l)?;
4229                self.compile_expr(b, r)?;
4230                b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
4231            }
4232            BinOp::NeEqEq => {
4233                self.compile_expr(b, l)?;
4234                self.compile_expr(b, r)?;
4235                b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
4236                b.emit(Op::LogNot, 0);
4237            }
4238            BinOp::EqEq => {
4239                self.compile_expr(b, l)?;
4240                self.compile_expr(b, r)?;
4241                b.emit(Op::CallBuiltin(ops::LOOSE_EQ, 2), 0);
4242            }
4243            BinOp::NeEq => {
4244                self.compile_expr(b, l)?;
4245                self.compile_expr(b, r)?;
4246                b.emit(Op::CallBuiltin(ops::LOOSE_EQ, 2), 0);
4247                b.emit(Op::LogNot, 0);
4248            }
4249            BinOp::In => {
4250                // `#field in obj` is the private-brand check: the left operand is a
4251                // private NAME, not a variable read, so it lowers to the key string
4252                // (private fields live as `#`-prefixed properties on the instance).
4253                match l {
4254                    Expr::Ident(n) if n.starts_with('#') => self.name_const(b, n),
4255                    _ => self.compile_expr(b, l)?,
4256                }
4257                self.compile_expr(b, r)?;
4258                b.emit(Op::CallBuiltin(ops::CONTAINS, 2), 0);
4259            }
4260            BinOp::InstanceOf => {
4261                self.compile_expr(b, l)?;
4262                self.compile_expr(b, r)?;
4263                b.emit(Op::CallBuiltin(ops::INSTANCEOF, 2), 0);
4264            }
4265            BinOp::BitAnd => self.emit_bitwise(b, bop::BITAND, l, r)?,
4266            BinOp::BitOr => self.emit_bitwise(b, bop::BITOR, l, r)?,
4267            BinOp::BitXor => self.emit_bitwise(b, bop::BITXOR, l, r)?,
4268            BinOp::Shl => self.emit_bitwise(b, bop::SHL, l, r)?,
4269            BinOp::Shr => self.emit_bitwise(b, bop::SHR, l, r)?,
4270            BinOp::UShr => self.emit_bitwise(b, bop::USHR, l, r)?,
4271        }
4272        Ok(())
4273    }
4274
4275    fn emit_bitwise(
4276        &mut self,
4277        b: &mut ChunkBuilder,
4278        tag: i64,
4279        l: &Expr,
4280        r: &Expr,
4281    ) -> Result<(), String> {
4282        b.emit(Op::LoadInt(tag), 0);
4283        self.compile_expr(b, l)?;
4284        self.compile_expr(b, r)?;
4285        b.emit(Op::CallBuiltin(ops::BINOP, 3), 0);
4286        Ok(())
4287    }
4288
4289    fn compile_update(
4290        &mut self,
4291        b: &mut ChunkBuilder,
4292        op: UpdateOp,
4293        prefix: bool,
4294        target: &Expr,
4295    ) -> Result<(), String> {
4296        // `NUM_STEP(tag, old)` computes `ToNumeric(old)` and `old ± 1` preserving
4297        // the operand's numeric type — so `x++` on a BigInt stays a BigInt
4298        // (`+old`/`old + 1` would throw the mix error). It pushes the coerced old
4299        // value and returns the new value: stack `[tag, old]` → `[oldN, new]`.
4300        let tag = if matches!(op, UpdateOp::Inc) { 1 } else { -1 };
4301        // A slot that provably holds a Number needs none of that: `ToNumeric`
4302        // is the identity on it and `Number ± 1` is a Number, so the whole
4303        // update is `GetSlot`, a native `Add`, and `SetSlot`. This is what takes
4304        // the last `CallBuiltin` out of a counting loop's body — and with it the
4305        // reason fusevm's tiers decline the loop.
4306        if let Expr::Ident(n) = target {
4307            // `c++` on a `const` is an assignment and throws like one. The
4308            // numeric fast path below writes the slot directly, and the general
4309            // path reaches the check through `compile_bind`, so this has to come
4310            // before both — otherwise `const c = 1; c++` silently incremented a
4311            // constant while `c = 2` correctly threw.
4312            if self.slots.consts.contains(n) {
4313                self.throw_const_assignment(b);
4314                return Ok(());
4315            }
4316            if let Some(slot) = self.numeric_slot_of(n) {
4317                b.emit(Op::GetSlot(slot), 0); // [old]
4318                if !prefix {
4319                    b.emit(Op::Dup, 0); // [old, old]
4320                }
4321                b.emit(Op::LoadFloat(tag as f64), 0);
4322                b.emit(Op::Add, 0); // [ (old,) new ]
4323                if prefix {
4324                    b.emit(Op::Dup, 0); // [new, new]
4325                }
4326                b.emit(Op::SetSlot(slot), 0); // stores, leaves the yielded value
4327                return Ok(());
4328            }
4329        }
4330        b.emit(Op::LoadInt(tag), 0);
4331        self.compile_expr(b, target)?; // [tag, old]
4332        b.emit(Op::CallBuiltin(ops::NUM_STEP, 2), 0); // [oldN, new]
4333        if prefix {
4334            // ++x: discard oldN, store new, yield new.
4335            b.emit(Op::Swap, 0); // [new, oldN]
4336            b.emit(Op::Pop, 0); // [new]
4337            b.emit(Op::Dup, 0); // [new, new]
4338            self.compile_bind(b, target, BindMode::Assign)?; // stores new -> [new]
4339        } else {
4340            // x++: store new, yield oldN.
4341            self.compile_bind(b, target, BindMode::Assign)?; // stores new -> [oldN]
4342        }
4343        Ok(())
4344    }
4345
4346    fn compile_member(
4347        &mut self,
4348        b: &mut ChunkBuilder,
4349        object: &Expr,
4350        property: &str,
4351        optional: bool,
4352    ) -> Result<(), String> {
4353        // `super.prop` — read a data/accessor property off the parent prototype.
4354        if matches!(object, Expr::Super) {
4355            self.name_const(b, property);
4356            b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0);
4357            return Ok(());
4358        }
4359        self.compile_expr(b, object)?;
4360        if optional {
4361            let jshort = self.emit_optional_guard(b);
4362            self.name_const(b, property);
4363            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
4364            // Inside a chain the jump belongs to the chain's end, not to this
4365            // link's — otherwise the rest of the chain runs on the `undefined`
4366            // the short-circuit just produced.
4367            match self.opt_chain.last_mut() {
4368                Some(frame) => frame.push(jshort),
4369                None => {
4370                    let end = b.current_pos();
4371                    b.patch_jump(jshort, end);
4372                }
4373            }
4374        } else {
4375            self.name_const(b, property);
4376            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
4377        }
4378        Ok(())
4379    }
4380
4381    fn compile_index(
4382        &mut self,
4383        b: &mut ChunkBuilder,
4384        object: &Expr,
4385        index: &Expr,
4386        optional: bool,
4387    ) -> Result<(), String> {
4388        // `super[expr]` READ — the computed twin of `super.prop`, which
4389        // `compile_member` handles. Without it `super` compiled as a value and
4390        // the read went against `undefined`.
4391        if matches!(object, Expr::Super) {
4392            self.compile_expr(b, index)?;
4393            b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0);
4394            return Ok(());
4395        }
4396        self.compile_expr(b, object)?;
4397        if optional {
4398            let jshort = self.emit_optional_guard(b);
4399            self.compile_off_spine(b, index)?;
4400            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0);
4401            match self.opt_chain.last_mut() {
4402                Some(frame) => frame.push(jshort),
4403                None => {
4404                    let end = b.current_pos();
4405                    b.patch_jump(jshort, end);
4406                }
4407            }
4408        } else {
4409            self.compile_off_spine(b, index)?;
4410            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0);
4411        }
4412        Ok(())
4413    }
4414
4415    /// For an optional access: object on TOS. If nullish, replace with undefined
4416    /// and jump over the access. Returns the jump index to patch to the end.
4417    // ── block scopes ─────────────────────────────────────────────────────
4418    /// Enter a block scope: `let`/`const` declared after this point die at the
4419    /// matching [`Self::emit_pop_scope`].
4420    /// Push a literal boolean.
4421    fn emit_bool(&self, b: &mut ChunkBuilder, v: bool) {
4422        b.emit(if v { Op::LoadTrue } else { Op::LoadFalse }, 0);
4423    }
4424
4425    fn emit_push_scope(&mut self, b: &mut ChunkBuilder) {
4426        b.emit(Op::CallBuiltin(ops::PUSH_SCOPE, 0), 0);
4427        b.emit(Op::Pop, 0);
4428        self.scope_depth += 1;
4429    }
4430
4431    fn emit_pop_scope(&mut self, b: &mut ChunkBuilder) {
4432        b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
4433        b.emit(Op::Pop, 0);
4434        self.scope_depth -= 1;
4435    }
4436
4437    /// Replace the innermost scope with a copy of its bindings — the per-iteration
4438    /// environment that makes each `for (let i …)` pass capture its own `i`.
4439    fn emit_copy_scope(&self, b: &mut ChunkBuilder) {
4440        b.emit(Op::CallBuiltin(ops::COPY_SCOPE, 0), 0);
4441        b.emit(Op::Pop, 0);
4442    }
4443
4444    /// Close and drop every for-of/for-in iterator between here and `target`
4445    /// depth. A jump to an OUTER loop abandons the inner loops, and their
4446    /// iterators are parked on the VM stack, so they must be popped (running a
4447    /// generator's `finally` / the iterator protocol's `.return()`) or the outer
4448    /// `FORITER` would read the wrong stack slot.
4449    /// Close every iterator this chunk has parked, with a value already on top
4450    /// of the stack that must survive: the iterators sit UNDER it, so each one
4451    /// is swapped up, closed, and its result dropped.
4452    /// Build the chunk being emitted and hand the host its call-site table. Every
4453    /// chunk goes through here so a site is registered exactly once, under the
4454    /// `op_hash` `build()` computes.
4455    fn finish_chunk(&mut self, b: ChunkBuilder) -> Chunk {
4456        let sites = std::mem::take(&mut self.call_sites);
4457        let mut yields = std::mem::take(&mut self.yield_sites);
4458        let events = std::mem::take(&mut self.iter_events);
4459        let marks = std::mem::take(&mut self.pos_marks);
4460        let mut chunk = b.build();
4461        for m in marks {
4462            let range = m.start..m.end;
4463            match m.scope {
4464                PosScope::Statement => {
4465                    for line in chunk.lines[range].iter_mut().filter(|l| **l == 0) {
4466                        *line = m.pos;
4467                    }
4468                }
4469                PosScope::Operation => {
4470                    let op = range.rev().find(|&i| {
4471                        matches!(chunk.ops[i], Op::CallBuiltin(..)) && chunk.lines[i] == 0
4472                    });
4473                    if let Some(i) = op {
4474                        chunk.lines[i] = m.pos;
4475                    }
4476                }
4477            }
4478        }
4479        // Every builtin call inside a `for…of` / `for…in` body can raise, and a
4480        // raise abandons the iterators parked beneath it. The depth recorded
4481        // per yield op is what closes them there; the same table answers for
4482        // any other op once it is filled in here.
4483        if !events.is_empty() {
4484            let known: std::collections::HashSet<usize> =
4485                yields.iter().map(|(ip, _)| *ip).collect();
4486            let mut at = 0;
4487            let mut depth = 0;
4488            for (ip, op) in chunk.ops.iter().enumerate() {
4489                while at < events.len() && events[at].0 <= ip {
4490                    depth = events[at].1;
4491                    at += 1;
4492                }
4493                if depth > 0 && matches!(op, Op::CallBuiltin(..)) && !known.contains(&ip) {
4494                    yields.push((ip, depth));
4495                }
4496            }
4497        }
4498        crate::host::register_call_sites(chunk.op_hash, sites);
4499        crate::host::register_yield_sites(chunk.op_hash, yields);
4500        chunk
4501    }
4502
4503    /// Record that the parked-iterator depth is now `self.iter_depth`, from the
4504    /// next op to be emitted onward.
4505    fn note_iter_depth(&mut self, b: &ChunkBuilder) {
4506        self.iter_events.push((b.current_pos(), self.iter_depth));
4507    }
4508
4509    /// Place the ops emitted since `start` at source position `pos` — see
4510    /// [`PosScope`] for which of them.
4511    fn mark_pos(&mut self, b: &ChunkBuilder, start: usize, pos: Pos, scope: PosScope) {
4512        let end = b.current_pos();
4513        if pos != 0 && end > start {
4514            self.pos_marks.push(PosMark {
4515                start,
4516                end,
4517                pos,
4518                scope,
4519            });
4520        }
4521    }
4522
4523    /// Record the callee's source text for the call op just emitted at `at`, so
4524    /// a `TypeError` raised there can name the callee the way V8 does. Nothing
4525    /// is recorded for a shape `callee_text` declines to print.
4526    fn note_call_site(&mut self, at: usize, callee: &Expr) {
4527        if let Some(text) = callee_text(callee) {
4528            self.call_sites.push((at, text));
4529        }
4530    }
4531
4532    fn emit_close_iters_under_value(&self, b: &mut ChunkBuilder) {
4533        for _ in 0..self.iter_depth {
4534            b.emit(Op::Swap, 0); // [.., iter, val] -> [.., val, iter]
4535            b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0); // -> [.., val, result]
4536            b.emit(Op::Pop, 0); // -> [.., val]
4537        }
4538    }
4539
4540    fn emit_close_iters(&self, b: &mut ChunkBuilder, target: usize) {
4541        for _ in target..self.iter_depth {
4542            b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0);
4543            b.emit(Op::Pop, 0);
4544        }
4545    }
4546
4547    /// Close every block scope between here and `target` depth, without changing
4548    /// the compile-time depth (the jump that follows leaves this code path).
4549    fn emit_unwind_scopes(&self, b: &mut ChunkBuilder, target: usize) {
4550        for _ in target..self.scope_depth {
4551            b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
4552            b.emit(Op::Pop, 0);
4553        }
4554    }
4555
4556    /// Raise a `break`/`continue` whose target loop is outside this chunk.
4557    fn emit_signal_jump(&mut self, b: &mut ChunkBuilder, op: u16, label: Option<&str>) {
4558        self.name_const(b, label.unwrap_or(""));
4559        b.emit(Op::CallBuiltin(op, 1), 0);
4560        b.emit(Op::Pop, 0);
4561        self.chunk_signals = true;
4562    }
4563
4564    /// Emit the `SIG_UNWIND` dispatch that runs right after a `TRY` (or after a
4565    /// loop that may still hold a signal for an outer labeled loop): route a
4566    /// pending `break`/`continue` to the enclosing loop's exit/continue target, or
4567    /// halt the chunk so a `return` (or a signal for a loop further out) keeps
4568    /// propagating.
4569    fn emit_signal_dispatch(&mut self, b: &mut ChunkBuilder) {
4570        // `break` lands on the innermost enclosing context, `continue` on the
4571        // innermost one that CATCHES it — a `switch` catches `break` but not
4572        // `continue`, so the two targets are resolved INDEPENDENTLY. Either may be
4573        // absent from this chunk, in which case a signal of that kind keeps
4574        // travelling outward. (`cont` implies `brk`: a continue-catching loop is
4575        // itself breakable, so it can never sit above the innermost context.)
4576        let brk = self
4577            .loops
4578            .len()
4579            .checked_sub(1)
4580            .filter(|i| *i >= self.chunk_loop_base);
4581        let cont = self
4582            .loops
4583            .iter()
4584            .rposition(|c| c.catches_continue)
4585            .filter(|i| *i >= self.chunk_loop_base);
4586        let tag_of = |i: Option<usize>, loops: &[LoopCtx]| match i {
4587            Some(i) => loops[i]
4588                .label
4589                .clone()
4590                .unwrap_or_else(|| unwind::PLAIN_LOOP.to_string()),
4591            None => unwind::NO_LOOP.to_string(),
4592        };
4593        let brk_tag = tag_of(brk, &self.loops);
4594        let cont_tag = tag_of(cont, &self.loops);
4595        self.name_const(b, &brk_tag);
4596        self.name_const(b, &cont_tag);
4597        b.emit(Op::CallBuiltin(ops::SIG_UNWIND, 2), 0); // [code]
4598        let Some(idx) = brk else {
4599            // Nothing in this chunk can catch the signal; `SIG_UNWIND` already
4600            // halted the chunk, so just drop its code.
4601            b.emit(Op::Pop, 0);
4602            return;
4603        };
4604        b.emit(Op::Dup, 0);
4605        b.emit(Op::LoadInt(unwind::BREAK), 0);
4606        b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
4607        let jb = b.emit(Op::JumpIfTrue(0), 0);
4608        let jc = cont.map(|_| {
4609            b.emit(Op::Dup, 0);
4610            b.emit(Op::LoadInt(unwind::CONTINUE), 0);
4611            b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
4612            b.emit(Op::JumpIfTrue(0), 0)
4613        });
4614        b.emit(Op::Pop, 0); // no signal: drop the code and fall through
4615        let jafter = b.emit(Op::Jump(0), 0);
4616        // The landing pads leave every block scope and iterator opened between
4617        // here and the target, exactly as the plain compiler-resolved `break` /
4618        // `continue` does. Skipping this leaked a scope onto the frame, so the
4619        // NEXT `let`/`const` at that level bound in a dead child env and became
4620        // invisible to any closure created afterwards.
4621        let (brk_scope, brk_iter) = (self.loops[idx].break_depth, self.loops[idx].iter_depth);
4622        let brk_land = b.current_pos();
4623        b.emit(Op::Pop, 0);
4624        self.emit_unwind_scopes(b, brk_scope);
4625        self.emit_close_iters(b, brk_iter);
4626        let brk_jump = b.emit(Op::Jump(0), 0);
4627        let cont_jump = jc.map(|_| {
4628            let (cs, ci) = cont
4629                .map(|i| (self.loops[i].continue_depth, self.loops[i].iter_depth))
4630                .unwrap_or((self.scope_depth, self.iter_depth));
4631            let cont_land = b.current_pos();
4632            b.emit(Op::Pop, 0);
4633            self.emit_unwind_scopes(b, cs);
4634            self.emit_close_iters(b, ci);
4635            (cont_land, b.emit(Op::Jump(0), 0))
4636        });
4637        let after = b.current_pos();
4638        b.patch_jump(jb, brk_land);
4639        if let (Some(jc), Some((cont_land, _))) = (jc, cont_jump) {
4640            b.patch_jump(jc, cont_land);
4641        }
4642        b.patch_jump(jafter, after);
4643        self.loops[idx].breaks.push(brk_jump);
4644        if let (Some(cont_idx), Some((_, cj))) = (cont, cont_jump) {
4645            self.loops[cont_idx].continues.push(cj);
4646        }
4647    }
4648
4649    /// Whether `e` is a link in an optional chain that short-circuits — i.e.
4650    /// walking the SPINE (a member's object, an index's object, a call's
4651    /// callee) reaches a `?.`. An argument or a computed index is not on the
4652    /// spine: `a?.b[c?.d]` is two chains, not one.
4653    fn spine_has_optional(e: &Expr) -> bool {
4654        match e {
4655            Expr::Member {
4656                object, optional, ..
4657            } => *optional || Self::spine_has_optional(object),
4658            Expr::Index {
4659                object, optional, ..
4660            } => *optional || Self::spine_has_optional(object),
4661            Expr::Call { func, optional, .. } => *optional || Self::spine_has_optional(func),
4662            _ => false,
4663        }
4664    }
4665
4666    /// Lower `e` as the ROOT of an optional chain: every `?.` inside its spine
4667    /// parks a jump, and all of them land here, past the whole chain.
4668    fn compile_chain_root(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
4669        self.opt_chain.push(Vec::new());
4670        let r = self.compile_expr(b, e);
4671        let pending = self.opt_chain.pop().unwrap_or_default();
4672        r?;
4673        let end = b.current_pos();
4674        for j in pending {
4675            b.patch_jump(j, end);
4676        }
4677        Ok(())
4678    }
4679
4680    /// Lower `e` with the enclosing chain SUSPENDED, so a `?.` inside it forms
4681    /// its own chain. Used for the parts that are not on the spine — call
4682    /// arguments and a computed index.
4683    fn compile_off_spine(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
4684        let saved = std::mem::take(&mut self.opt_chain);
4685        let r = self.compile_expr(b, e);
4686        self.opt_chain = saved;
4687        r
4688    }
4689
4690    fn emit_optional_guard(&mut self, b: &mut ChunkBuilder) -> usize {
4691        b.emit(Op::Dup, 0);
4692        b.emit(Op::CallBuiltin(ops::NULLISH, 1), 0);
4693        let jnull = b.emit(Op::JumpIfFalse(0), 0); // not nullish -> continue access
4694                                                   // nullish: drop object, push undefined, jump to end.
4695        b.emit(Op::Pop, 0);
4696        b.emit(Op::LoadUndef, 0);
4697        let jend = b.emit(Op::Jump(0), 0);
4698        let cont = b.current_pos();
4699        b.patch_jump(jnull, cont);
4700        jend
4701    }
4702
4703    /// `callee?.(args)` — the CALLEE itself may be nullish, in which case the whole
4704    /// call short-circuits to `undefined` without evaluating the arguments. A
4705    /// method callee (`obj.m?.()`) must still be invoked with `this === obj`, so it
4706    /// is dispatched through `m.call(obj, …)` / `m.apply(obj, …)`.
4707    fn compile_optional_call(
4708        &mut self,
4709        b: &mut ChunkBuilder,
4710        func: &Expr,
4711        args: &[Expr],
4712    ) -> Result<(), String> {
4713        let has_spread = args.iter().any(|a| matches!(a, Expr::Spread(_)));
4714        if let Expr::Member {
4715            object,
4716            property,
4717            optional: obj_optional,
4718            ..
4719        } = func
4720        {
4721            self.compile_expr(b, object)?; // [recv]
4722            let jobj = if *obj_optional {
4723                Some(self.emit_optional_guard(b))
4724            } else {
4725                None
4726            };
4727            b.emit(Op::Dup, 0); // [recv, recv]
4728            self.name_const(b, property); // [recv, recv, name]
4729            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [recv, fn]
4730                                                         // Nullish callee: drop both the method and the receiver.
4731            b.emit(Op::Dup, 0);
4732            b.emit(Op::CallBuiltin(ops::NULLISH, 1), 0);
4733            let jlive = b.emit(Op::JumpIfFalse(0), 0);
4734            b.emit(Op::Pop, 0);
4735            b.emit(Op::Pop, 0);
4736            b.emit(Op::LoadUndef, 0);
4737            let jend = b.emit(Op::Jump(0), 0);
4738            let live = b.current_pos();
4739            b.patch_jump(jlive, live);
4740            // [recv, fn] -> fn.call(recv, …) / fn.apply(recv, argsArray)
4741            let via = if has_spread { "apply" } else { "call" };
4742            self.name_const(b, via); // [recv, fn, via]
4743            b.emit(Op::Rot, 0); // [fn, via, recv]
4744            let extra = if has_spread {
4745                self.compile_spread_args(b, args)?; // [fn, via, recv, argsArray]
4746                1
4747            } else {
4748                for a in args {
4749                    self.compile_expr(b, a)?;
4750                }
4751                args.len()
4752            };
4753            b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + extra)?), 0);
4754            match self.opt_chain.last_mut() {
4755                Some(frame) => {
4756                    frame.push(jend);
4757                    if let Some(j) = jobj {
4758                        frame.push(j);
4759                    }
4760                }
4761                None => {
4762                    let end = b.current_pos();
4763                    b.patch_jump(jend, end);
4764                    if let Some(j) = jobj {
4765                        b.patch_jump(j, end);
4766                    }
4767                }
4768            }
4769            return Ok(());
4770        }
4771        // `recv[expr]?.(…)` — the optional-call form of a COMPUTED member. Same
4772        // receiver rule as `recv.name?.(…)` above; only the key differs, being
4773        // known at run time rather than compile time. This used to fall through
4774        // to the plain-callee path below and lose `this`, so `o['self']?.()`
4775        // threw where `o.self?.()` worked.
4776        if let Expr::Index {
4777            object,
4778            index,
4779            optional: obj_optional,
4780            ..
4781        } = func
4782        {
4783            self.compile_expr(b, object)?; // [recv]
4784            let jobj = if *obj_optional {
4785                Some(self.emit_optional_guard(b))
4786            } else {
4787                None
4788            };
4789            b.emit(Op::Dup, 0); // [recv, recv]
4790            self.compile_expr(b, index)?; // [recv, recv, key]
4791            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0); // [recv, fn]
4792            b.emit(Op::Dup, 0);
4793            b.emit(Op::CallBuiltin(ops::NULLISH, 1), 0);
4794            let jlive = b.emit(Op::JumpIfFalse(0), 0);
4795            b.emit(Op::Pop, 0);
4796            b.emit(Op::Pop, 0);
4797            b.emit(Op::LoadUndef, 0);
4798            let jend = b.emit(Op::Jump(0), 0);
4799            let live = b.current_pos();
4800            b.patch_jump(jlive, live);
4801            let via = if has_spread { "apply" } else { "call" };
4802            self.name_const(b, via); // [recv, fn, via]
4803            b.emit(Op::Rot, 0); // [fn, via, recv]
4804            let extra = if has_spread {
4805                self.compile_spread_args(b, args)?;
4806                1
4807            } else {
4808                for a in args {
4809                    self.compile_expr(b, a)?;
4810                }
4811                args.len()
4812            };
4813            b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + extra)?), 0);
4814            match self.opt_chain.last_mut() {
4815                Some(frame) => {
4816                    frame.push(jend);
4817                    if let Some(j) = jobj {
4818                        frame.push(j);
4819                    }
4820                }
4821                None => {
4822                    let end = b.current_pos();
4823                    b.patch_jump(jend, end);
4824                    if let Some(j) = jobj {
4825                        b.patch_jump(j, end);
4826                    }
4827                }
4828            }
4829            return Ok(());
4830        }
4831        // Plain callee (`f?.()`): evaluate it, guard, then call with no
4832        // receiver — a bare expression has none to keep.
4833        self.compile_expr(b, func)?;
4834        let jend = self.emit_optional_guard(b);
4835        if has_spread {
4836            self.compile_spread_args(b, args)?;
4837            b.emit(Op::CallBuiltin(ops::APPLY, 2), 0);
4838        } else {
4839            for a in args {
4840                self.compile_expr(b, a)?;
4841            }
4842            b.emit(Op::CallBuiltin(ops::CALL_VALUE, argc(1 + args.len())?), 0);
4843        }
4844        let end = b.current_pos();
4845        b.patch_jump(jend, end);
4846        Ok(())
4847    }
4848
4849    fn compile_call(
4850        &mut self,
4851        b: &mut ChunkBuilder,
4852        func: &Expr,
4853        args: &[Expr],
4854        optional: bool,
4855    ) -> Result<(), String> {
4856        if optional {
4857            return self.compile_optional_call(b, func, args);
4858        }
4859        // `import(specifier[, options])` in a script (13.3.10): the ES module
4860        // loader, resolving against the running file — the `__filename` the
4861        // CommonJS wrapper (or the entry script) binds. Module code never
4862        // reaches here: `esm::lower` passes its own filename instead.
4863        if matches!(func, Expr::Ident(n) if n == "import") {
4864            if args.is_empty()
4865                || args.len() > 2
4866                || args.iter().any(|a| matches!(a, Expr::Spread(_)))
4867            {
4868                return Err("SyntaxError: Unexpected token ')'".to_string());
4869            }
4870            let filename = Expr::Ident("__filename".into());
4871            let referrer = Expr::Conditional {
4872                test: Box::new(Expr::Binary(
4873                    BinOp::EqEqEq,
4874                    Box::new(Expr::Unary(UnOp::TypeOf, Box::new(filename.clone()))),
4875                    Box::new(Expr::Str("string".into())),
4876                )),
4877                cons: Box::new(filename),
4878                alt: Box::new(Expr::Undefined),
4879            };
4880            let mut full = vec![args[0].clone(), referrer];
4881            full.extend(args.get(1).cloned());
4882            return self.compile_call(b, &Expr::Ident(crate::esm::IMPORT_FN.into()), &full, false);
4883        }
4884        let has_spread = args.iter().any(|a| matches!(a, Expr::Spread(_)));
4885        match func {
4886            // `super(...args)` — invoke the parent constructor on the current
4887            // `this` (SUPER_CALL runs the parent ctor + this class's field inits).
4888            Expr::Super => {
4889                // A `...spread` has to be EXPANDED here as it is at every other
4890                // call site: compiling it as an ordinary expression passed the
4891                // spread OBJECT as one argument, so `super(...[1, 2])` gave the
4892                // parent the array and left its second parameter undefined.
4893                if has_spread {
4894                    self.compile_spread_args(b, args)?;
4895                    b.emit(Op::CallBuiltin(ops::SUPER_CALL_SPREAD, 1), 0);
4896                    return Ok(());
4897                }
4898                for a in args {
4899                    self.compile_expr(b, a)?;
4900                }
4901                b.emit(Op::CallBuiltin(ops::SUPER_CALL, argc(args.len())?), 0);
4902                return Ok(());
4903            }
4904            // `super.method(...args)` — resolve the parent method, call it bound to
4905            // the current `this` via `method.call(this, ...args)`.
4906            Expr::Member {
4907                object, property, ..
4908            } if matches!(**object, Expr::Super) => {
4909                self.name_const(b, property);
4910                b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0); // [method]
4911                                                               // With a spread the argument count is not static, so the call
4912                                                               // goes through `apply` with a run-time array rather than `call`
4913                                                               // with a fixed run. Compiling the spread as an ordinary
4914                                                               // argument handed the parent method the array itself.
4915                if has_spread {
4916                    self.name_const(b, "apply"); // [method, "apply"]
4917                    b.emit(Op::CallBuiltin(ops::THIS, 0), 0); // [method, "apply", this]
4918                    self.compile_spread_args(b, args)?; // [..., argsArray]
4919                    b.emit(Op::CallBuiltin(ops::CALL_METHOD, 4), 0);
4920                    return Ok(());
4921                }
4922                self.name_const(b, "call"); // [method, "call"]
4923                b.emit(Op::CallBuiltin(ops::THIS, 0), 0); // [method, "call", this]
4924                                                          // `method.call(this, ...args)`: compile args and dispatch as a
4925                                                          // method call named "call".
4926                for a in args {
4927                    self.compile_expr(b, a)?;
4928                }
4929                b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + args.len())?), 0);
4930                return Ok(());
4931            }
4932            Expr::Member {
4933                object,
4934                property,
4935                optional,
4936                ..
4937            } => {
4938                self.compile_expr(b, object)?;
4939                // `obj?.method(...)`: if `obj` is nullish, short-circuit the whole
4940                // call to `undefined` (skip the method name, args, and dispatch).
4941                let jshort = if *optional {
4942                    Some(self.emit_optional_guard(b))
4943                } else {
4944                    None
4945                };
4946                self.name_const(b, property);
4947                if has_spread {
4948                    self.compile_spread_args(b, args)?; // [recv, name, argsArray]
4949                    b.emit(Op::CallBuiltin(ops::APPLY_METHOD, 3), 0);
4950                } else {
4951                    // Arguments are not on the chain's spine: a `?.` inside one
4952                    // is its own chain and must not jump past this call.
4953                    for a in args {
4954                        self.compile_off_spine(b, a)?;
4955                    }
4956                    let at = b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?), 0);
4957                    self.note_call_site(at, func);
4958                }
4959                if let Some(j) = jshort {
4960                    match self.opt_chain.last_mut() {
4961                        Some(frame) => frame.push(j),
4962                        None => {
4963                            let end = b.current_pos();
4964                            b.patch_jump(j, end);
4965                        }
4966                    }
4967                }
4968            }
4969            // `super[expr](args)` — the computed twin of `super.m(args)` above.
4970            // The dotted form was handled and this was not, so it fell through
4971            // to the ordinary computed-call path, which compiled `super` as a
4972            // value and dispatched on that.
4973            Expr::Index { object, index, .. } if matches!(**object, Expr::Super) => {
4974                self.compile_expr(b, index)?; // [name]
4975                b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0); // [method]
4976                self.name_const(b, "call"); // [method, "call"]
4977                b.emit(Op::CallBuiltin(ops::THIS, 0), 0); // [method, "call", this]
4978                for a in args {
4979                    self.compile_expr(b, a)?;
4980                }
4981                b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + args.len())?), 0);
4982                return Ok(());
4983            }
4984            Expr::Index {
4985                object,
4986                index,
4987                optional,
4988                ..
4989            } => {
4990                // recv[expr](args) — evaluate as a method via computed name.
4991                self.compile_expr(b, object)?; // [recv]
4992                                               // `recv?.[expr](...)`: short-circuit to `undefined` when nullish.
4993                let jshort = if *optional {
4994                    Some(self.emit_optional_guard(b))
4995                } else {
4996                    None
4997                };
4998                // 13.3.6 EvaluateCall: the receiver of `recv[expr](...)` is
4999                // `recv`, exactly as for `recv.name(...)`. This used to read the
5000                // function with GETITEM, DROP the receiver, and call the value
5001                // with no `this` — the comment called it "approximated", and it
5002                // silently produced wrong answers rather than errors:
5003                //
5004                //     const o = {x: 42, f() { return this.x }};
5005                //     o.f()      // 42
5006                //     o['f']()   // undefined      <- was
5007                //     c['m']()   // TypeError      <- on a class instance
5008                //
5009                // CALL_METHOD/APPLY_METHOD take the name off the STACK, so a
5010                // computed key dispatches through the same path a static one
5011                // does and keeps the receiver.
5012                self.compile_expr(b, index)?; // [recv, name]
5013                if has_spread {
5014                    self.compile_spread_args(b, args)?; // [recv, name, argsArray]
5015                    b.emit(Op::CallBuiltin(ops::APPLY_METHOD, 3), 0);
5016                } else {
5017                    for a in args {
5018                        self.compile_off_spine(b, a)?;
5019                    }
5020                    let at = b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?), 0);
5021                    self.note_call_site(at, func);
5022                }
5023                if let Some(j) = jshort {
5024                    let end = b.current_pos();
5025                    b.patch_jump(j, end);
5026                }
5027            }
5028            // Inside `with` the callee may be a method of the object, which is
5029            // then its `this`: resolve `[fn, this]` and call with both.
5030            Expr::Ident(n) if self.with_depth > 0 && n != "eval" => {
5031                self.name_const(b, n);
5032                b.emit(Op::CallBuiltin(ops::WITH_FN, 1), 0); // [fn, this]
5033                if has_spread {
5034                    self.compile_spread_args(b, args)?;
5035                    b.emit(Op::CallBuiltin(ops::APPLY_THIS, 3), 0);
5036                } else {
5037                    for a in args {
5038                        self.compile_expr(b, a)?;
5039                    }
5040                    let at = b.emit(Op::CallBuiltin(ops::CALL_THIS, argc(2 + args.len())?), 0);
5041                    self.note_call_site(at, func);
5042                }
5043            }
5044            // A slotted callee has no name to resolve at run time: it falls
5045            // through to the value path below, which reads the slot and calls
5046            // through `CALL_VALUE`.
5047            Expr::Ident(n) if self.slot_of(n).is_none() => {
5048                self.name_const(b, n);
5049                if has_spread {
5050                    self.compile_spread_args(b, args)?; // [name, argsArray]
5051                                                        // Resolve name to a value, then APPLY.
5052                    b.emit(Op::Swap, 0); // [argsArray, name]
5053                    b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0); // [argsArray, fn]
5054                    b.emit(Op::Swap, 0); // [fn, argsArray]
5055                    b.emit(Op::CallBuiltin(ops::APPLY, 2), 0);
5056                } else {
5057                    for a in args {
5058                        self.compile_expr(b, a)?;
5059                    }
5060                    let at = b.emit(Op::CallBuiltin(ops::CALL, argc(1 + args.len())?), 0);
5061                    self.note_call_site(at, func);
5062                }
5063            }
5064            _ => {
5065                self.compile_expr(b, func)?;
5066                if has_spread {
5067                    self.compile_spread_args(b, args)?;
5068                    b.emit(Op::CallBuiltin(ops::APPLY, 2), 0);
5069                } else {
5070                    for a in args {
5071                        self.compile_expr(b, a)?;
5072                    }
5073                    let at = b.emit(Op::CallBuiltin(ops::CALL_VALUE, argc(1 + args.len())?), 0);
5074                    self.note_call_site(at, func);
5075                }
5076            }
5077        }
5078        Ok(())
5079    }
5080
5081    /// Build a flat args array from a mix of plain args and `...spread` args.
5082    fn compile_spread_args(&mut self, b: &mut ChunkBuilder, args: &[Expr]) -> Result<(), String> {
5083        for a in args {
5084            match a {
5085                // Tag 3, not 1: a spread in a CALL argument list reports a
5086                // non-iterable differently from one in an ARRAY LITERAL, and
5087                // `BUILD_ARGS` serves both. Node names the missing protocol
5088                // here (`Spread syntax requires ...`) and the VALUE there.
5089                Expr::Spread(inner) => {
5090                    b.emit(Op::LoadInt(3), 0);
5091                    self.compile_expr(b, inner)?;
5092                }
5093                _ => {
5094                    b.emit(Op::LoadInt(0), 0);
5095                    self.compile_expr(b, a)?;
5096                }
5097            }
5098        }
5099        b.emit(Op::CallBuiltin(ops::BUILD_ARGS, argc(args.len() * 2)?), 0);
5100        Ok(())
5101    }
5102
5103    fn compile_new(
5104        &mut self,
5105        b: &mut ChunkBuilder,
5106        callee: &Expr,
5107        args: &[Expr],
5108    ) -> Result<(), String> {
5109        self.compile_expr(b, callee)?;
5110        // A `...spread` argument has to be EXPANDED into the argument list. A
5111        // plain `compile_expr` of one yields the spread object itself, so
5112        // `new C(...[1, 2])` passed the array as a single argument.
5113        if args.iter().any(|a| matches!(a, Expr::Spread(_))) {
5114            // `compile_spread_args` emits its own `BUILD_ARGS`, leaving the flat
5115            // argument array on the stack above the constructor.
5116            self.compile_spread_args(b, args)?;
5117            let at = b.emit(Op::CallBuiltin(ops::NEW_SPREAD, 2), 0);
5118            self.note_call_site(at, callee);
5119            return Ok(());
5120        }
5121        for a in args {
5122            self.compile_expr(b, a)?;
5123        }
5124        let at = b.emit(Op::CallBuiltin(ops::NEW, argc(1 + args.len())?), 0);
5125        self.note_call_site(at, callee);
5126        Ok(())
5127    }
5128}
5129
5130/// A prologue statement applying a parameter default: `if (name === undefined)
5131/// name = default;`.
5132fn default_stmt(name: &str, default: &Expr) -> Stmt {
5133    Stmt::from(StmtKind::If {
5134        test: Expr::Binary(
5135            BinOp::EqEqEq,
5136            Box::new(Expr::Ident(name.to_string())),
5137            Box::new(Expr::Undefined),
5138        ),
5139        cons: Box::new(Stmt::from(StmtKind::Expr(Expr::Assign {
5140            target: Box::new(Expr::Ident(name.to_string())),
5141            op: None,
5142            value: Box::new(default.clone()),
5143        }))),
5144        alt: None,
5145    })
5146}
5147
5148/// Every name a `var` binds inside one function scope, in source order.
5149///
5150/// Descends through block-scoped constructs, because `var` is not block-scoped,
5151/// and stops at a nested `function` declaration, whose body is its own scope.
5152/// Function *expressions* and arrows are inside `Expr`, which is not walked at
5153/// all: a `var` can only be introduced by a statement.
5154pub(crate) fn collect_var_names(s: &Stmt, out: &mut Vec<String>) {
5155    walk_var_targets(s, &mut |target, _| pattern_names(target, out));
5156}
5157
5158/// [`collect_var_names`] with where each declaration is written.
5159fn collect_var_bindings(s: &Stmt, out: &mut Vec<Binding>) {
5160    walk_var_targets(s, &mut |target, bound| {
5161        out.extend(bindings_at(target, bound))
5162    });
5163}
5164
5165/// What [`walk_var_targets`] calls per target: the target and its names'
5166/// positions (`ast::Declarator::bound`).
5167type VarTargetFn<'a> = dyn FnMut(&Expr, &[(String, Pos)]) + 'a;
5168
5169/// Each `var` declaration target hoisting out of `s` — through blocks, loops,
5170/// `switch` and `try`, never into a function — with where its names are
5171/// written (nothing for a `for (var … of/in …)` head, which records none).
5172fn walk_var_targets(s: &Stmt, f: &mut VarTargetFn) {
5173    match &s.kind {
5174        StmtKind::Decl {
5175            kind: DeclKind::Var,
5176            decls,
5177        } => {
5178            for d in decls {
5179                f(&d.target, &d.bound);
5180            }
5181        }
5182        StmtKind::Block(body) => body.iter().for_each(|s| walk_var_targets(s, f)),
5183        StmtKind::If { cons, alt, .. } => {
5184            walk_var_targets(cons, f);
5185            if let Some(a) = alt {
5186                walk_var_targets(a, f);
5187            }
5188        }
5189        StmtKind::While { body, .. }
5190        | StmtKind::With { body, .. }
5191        | StmtKind::DoWhile { body, .. }
5192        | StmtKind::Labeled { body, .. } => walk_var_targets(body, f),
5193        StmtKind::For { init, body, .. } => {
5194            if let Some(i) = init {
5195                walk_var_targets(i, f);
5196            }
5197            walk_var_targets(body, f);
5198        }
5199        StmtKind::ForOf {
5200            decl_kind,
5201            target,
5202            body,
5203            ..
5204        }
5205        | StmtKind::ForIn {
5206            decl_kind,
5207            target,
5208            body,
5209            ..
5210        } => {
5211            if *decl_kind == Some(DeclKind::Var) {
5212                f(target, &[]);
5213            }
5214            walk_var_targets(body, f);
5215        }
5216        StmtKind::Switch { cases, .. } => {
5217            for c in cases {
5218                c.body.iter().for_each(|s| walk_var_targets(s, f));
5219            }
5220        }
5221        StmtKind::Try {
5222            block,
5223            handler,
5224            finalizer,
5225        } => {
5226            block.iter().for_each(|s| walk_var_targets(s, f));
5227            if let Some((_, body)) = handler {
5228                // The catch PARAMETER is block-scoped to the handler, so it is
5229                // not collected; a `var` in the handler body still hoists.
5230                body.iter().for_each(|s| walk_var_targets(s, f));
5231            }
5232            if let Some(fin) = finalizer {
5233                fin.iter().for_each(|s| walk_var_targets(s, f));
5234            }
5235        }
5236        _ => {}
5237    }
5238}
5239
5240/// The binding names a declaration target introduces, destructuring included.
5241pub(crate) fn pattern_names(target: &Expr, out: &mut Vec<String>) {
5242    match target {
5243        Expr::Ident(n) => {
5244            if !out.iter().any(|x| x == n) {
5245                out.push(n.clone());
5246            }
5247        }
5248        Expr::Array(items) => items.iter().for_each(|i| pattern_names(i, out)),
5249        Expr::Object(props) => {
5250            for p in props {
5251                match p {
5252                    Prop::KeyValue { value, .. } => pattern_names(value, out),
5253                    Prop::Spread(e) => pattern_names(e, out),
5254                    Prop::Accessor { .. } => {}
5255                }
5256            }
5257        }
5258        // `[a = 1]` / `{a: b = 1}` — the binding is the target, not the default.
5259        Expr::Assign { target, .. } => pattern_names(target, out),
5260        Expr::Spread(inner) => pattern_names(inner, out),
5261        // A member target (`[obj.x] = …`) assigns a property, binding nothing.
5262        _ => {}
5263    }
5264}
5265
5266/// How node renders the SOURCE of a failed object destructuring: `const {w} =
5267/// v` names `v`. Only the forms whose text can be reproduced exactly are
5268/// rendered; anything else answers `None` and the caller falls back to the
5269/// ordinary property-read error rather than inventing a rendering.
5270fn destructure_source_text(e: &Expr) -> Option<String> {
5271    Some(match e {
5272        Expr::Null => "null".into(),
5273        Expr::Undefined => "undefined".into(),
5274        Expr::Ident(n) => n.clone(),
5275        // A LITERAL names itself: `const [x] = 5` is `5 is not iterable`. An
5276        // OBJECT literal is named too, but by shape rather than by text — empty
5277        // renders `{}` and anything else `{(intermediate value)}`, which is
5278        // what V8 calls a value with no source name.
5279        Expr::Number(n) => crate::host::fmt_number(*n),
5280        Expr::True => "true".into(),
5281        Expr::False => "false".into(),
5282        Expr::Object(props) if props.is_empty() => "{}".into(),
5283        Expr::Object(_) => "{(intermediate value)}".into(),
5284        Expr::Member {
5285            object,
5286            property,
5287            optional: false,
5288            ..
5289        } => format!("{}.{property}", destructure_source_text(object)?),
5290        _ => return None,
5291    })
5292}
5293
5294/// Every name a binding pattern introduces, in source order — one for a plain
5295/// identifier, and the leaves of an object or array pattern otherwise.
5296fn binding_names(target: &Expr) -> Vec<String> {
5297    let mut out = Vec::new();
5298    fn walk(e: &Expr, out: &mut Vec<String>) {
5299        match e {
5300            Expr::Ident(n) => out.push(n.clone()),
5301            Expr::Assign { target, .. } => walk(target, out),
5302            Expr::Spread(inner) => walk(inner, out),
5303            Expr::Array(items) => items.iter().for_each(|i| walk(i, out)),
5304            Expr::Object(props) => {
5305                for p in props {
5306                    match p {
5307                        Prop::KeyValue { value, .. } => walk(value, out),
5308                        Prop::Spread(inner) => walk(inner, out),
5309                        Prop::Accessor { .. } => {}
5310                    }
5311                }
5312            }
5313            _ => {}
5314        }
5315    }
5316    walk(target, &mut out);
5317    out
5318}