Skip to main content

quickjs/
interp.rs

1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::{OpFormat, Opcode};
22use js_gc::{Gc, Heap};
23
24use crate::object::{
25    Callable, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars, NativeFn, ObjectKind,
26    Property, PropertyKey, array_index, has_own, lookup_key, same_proto,
27};
28use crate::value::{Cell, Value, number_to_string};
29
30/// Why execution stopped.
31#[derive(Debug, Clone)]
32pub enum Signal {
33    /// A JavaScript exception carrying the thrown value.
34    Throw(Value),
35    /// The runtime ran out of memory.
36    OutOfMemory,
37}
38
39/// What an execution step produced.
40pub type JsResult<T> = std::result::Result<T, Signal>;
41
42/// The result of one instruction.
43enum Step {
44    /// Keep executing the current frame.
45    Continue,
46    /// The current frame returned this value.
47    Return(Value),
48    /// The frame parked at a suspension point, with the yielded value on its stack.
49    ///
50    /// Only a generator or an async function can produce this, and only its own frame —
51    /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
52    /// detached and handed to the generator object, which is what lets it resume later
53    /// with its locals and operand stack intact.
54    Suspend(SuspendKind),
55}
56
57/// Why a frame parked, which decides how the resumption is delivered.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum SuspendKind {
60    /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
61    /// without passing a value, because there is no `yield` expression to receive one.
62    Initial,
63    /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
64    Yield,
65    /// `yield* expr`: like `Yield`, but the value is already an `{value, done}` object
66    /// from the inner iterator and is handed straight back.
67    YieldStar,
68    /// `await expr`: the value is a promise the async machinery has to settle first.
69    Await,
70}
71
72/// Everything one JavaScript realm owns.
73///
74/// A realm is the set of objects a script can reach without naming them: the global
75/// object, the prototype chain roots, and the global binding cells.
76pub struct Realm {
77    /// The global object.
78    pub global: Gc<JsObject>,
79    /// `Object.prototype`.
80    pub object_proto: Gc<JsObject>,
81    /// `Function.prototype`, which is itself callable.
82    pub function_proto: Gc<JsObject>,
83    /// `Array.prototype`.
84    pub array_proto: Gc<JsObject>,
85    /// Reference cells for globals declared by the script.
86    ///
87    /// A declared global is read with `get_var` (by name) but written with
88    /// `put_var_ref` (through the cell), so the cell is what makes a function
89    /// declaration and its uses agree on one binding.
90    pub globals: BTreeMap<String, Gc<Cell>>,
91    /// Names of the globals that came from a *declaration*, which are
92    /// non-configurable properties of the global object.
93    pub declared: Vec<String>,
94    /// Names among the lexical globals that are `const`.
95    ///
96    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
97    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
98    /// path does not carry, so a store through it would look like a plain `let`. The
99    /// realm records it once, at declaration, and answers for every reader.
100    pub lexical_consts: BTreeSet<String>,
101    /// The error constructors by class name, so a runtime error can throw a real
102    /// `TypeError` instance rather than a look-alike object.
103    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
104    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
105    pub string_proto: Option<Gc<JsObject>>,
106    /// `Number.prototype`.
107    pub number_proto: Option<Gc<JsObject>>,
108    /// `Boolean.prototype`.
109    pub boolean_proto: Option<Gc<JsObject>>,
110    /// `BigInt.prototype`.
111    pub bigint_proto: Option<Gc<JsObject>>,
112    /// `Error.prototype`, the prototype of every error instance.
113    pub error_proto: Gc<JsObject>,
114    /// `Date.prototype`, so the constructor can build an instance in the
115    /// function-call form (`Date()` returns a string) without going through `new`.
116    pub date_proto: Gc<JsObject>,
117    /// `%GeneratorPrototype%`, the prototype of every generator object.
118    pub generator_proto: Gc<JsObject>,
119    /// `Promise.prototype`, the prototype of every promise.
120    pub promise_proto: Option<Gc<JsObject>>,
121    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
122    pub async_generator_proto: Option<Gc<JsObject>>,
123    /// `Symbol.prototype`.
124    pub symbol_proto: Option<Gc<JsObject>>,
125    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
126    /// `_date_value`.
127    ///
128    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
129    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
130    /// language does not have and `new Error()` listed `_class` beside `message` and
131    /// `stack` — and a caller that copies every own property (which
132    /// `Object.create(null, props)` effectively does) tried to write an internal name and
133    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
134    /// and `JSON.stringify`, while remaining an ordinary traced property.
135    pub internal_slots: BTreeMap<&'static str, Value>,
136
137    /// The `Symbol.for` registry: `key -> symbol`.
138    ///
139    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
140    /// symbol every time within one script while a fresh realm starts empty.
141    pub symbol_registry: BTreeMap<String, Value>,
142    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
143    pub regexp_proto: Option<Gc<JsObject>>,
144    /// The `RegExp` constructor.
145    pub regexp_ctor: Option<Gc<JsObject>>,
146    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
147    ///
148    /// The prototype rather than the constructor on purpose: a script that replaces
149    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
150    /// error wrapping, which the `using` test suite checks explicitly.
151    pub suppressed_error_proto: Option<Gc<JsObject>>,
152    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
153    pub disposable_stack_proto: Option<Gc<JsObject>>,
154    /// `Map.prototype`.
155    pub map_proto: Option<Gc<JsObject>>,
156    /// `Set.prototype`.
157    pub set_proto: Option<Gc<JsObject>>,
158    /// `ArrayBuffer.prototype`.
159    pub array_buffer_proto: Option<Gc<JsObject>>,
160    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
161    pub typed_array_proto: Option<Gc<JsObject>>,
162    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
163    ///
164    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
165    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
166    /// `"Object"` and `r instanceof Int32Array` is false.
167    pub typed_array_protos: Vec<Gc<JsObject>>,
168    /// `DataView.prototype`.
169    pub data_view_proto: Option<Gc<JsObject>>,
170    /// The `AsyncDisposableStack` prototype.
171    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
172    /// `Iterator.prototype`.
173    pub iterator_proto: Option<Gc<JsObject>>,
174    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
175    ///
176    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
177    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
178    /// `[object Iterator Helper]`).
179    pub iterator_helper_proto: Option<Gc<JsObject>>,
180    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
181    /// that was not already an `Iterator`.
182    ///
183    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
184    /// untouched and does *not* override `@@toStringTag`, so
185    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
186    pub iterator_wrap_proto: Option<Gc<JsObject>>,
187    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
188    pub generator_function_proto: Option<Gc<JsObject>>,
189    /// `%AsyncFunction.prototype%`.
190    pub async_function_proto: Option<Gc<JsObject>>,
191    /// `%AsyncGeneratorFunction.prototype%`.
192    pub async_generator_function_proto: Option<Gc<JsObject>>,
193    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
194    ///
195    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
196    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
197    /// prototype per iterator made every array iterator's prototype distinct.
198    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
199    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
200    ///
201    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
202    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
203    /// both faster and impossible to break from a script.
204    well_known_symbols: WellKnownSymbols,
205}
206
207/// One binding of the frame that called `eval`, so the eval'd code can read and
208/// write it by name.
209struct EvalBinding {
210    /// The name it was declared with.
211    name: String,
212    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
213    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
214    /// a function that declares `a` must find that `a`.
215    frame: usize,
216    /// Which table of that frame it lives in.
217    slot: EvalSlot,
218    /// The slot index within that table.
219    index: usize,
220}
221
222/// Which table of a frame an [`EvalBinding`] indexes.
223#[derive(Clone, Copy)]
224enum EvalSlot {
225    Arg,
226    Local,
227}
228
229/// One activation record.
230struct Frame {
231    /// The bytecode being run.
232    code: Gc<CompiledCode>,
233    /// The cells this closure captured.
234    env: Gc<ClosureEnv>,
235    /// The `this` binding.
236    this: Value,
237    /// Argument slots, sized to the declared parameter count.
238    args: Vec<Value>,
239    /// The values the caller actually passed, which is what `arguments` exposes.
240    passed: Vec<Value>,
241    /// Local slots.
242    locals: Vec<Value>,
243    /// Reference cells for this frame's own captured bindings.
244    cells: Vec<Gc<Cell>>,
245    /// The operand stack.
246    stack: Vec<Value>,
247    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
248    local_vars: Option<Gc<LocalVars>>,
249
250    /// Byte offset of the next instruction.
251    pc: usize,
252    /// Byte offset of the instruction being executed, which is what a stack trace
253    /// reports. `pc` has already moved past it by the time an instruction runs.
254    at: usize,
255    /// The callee, so a native builtin can tell which constructor it is.
256    callee: Value,
257    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
258    new_target: Value,
259    /// Whether this frame's body ended in a `tail_call`.
260    ///
261    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
262    /// with its own frame just like `call` does and only skips storing the result
263    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
264    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
265    /// pushed as usual, and this marker makes its return value the *caller's* return
266    /// value without running the instructions after the call.
267    tail: bool,
268}
269
270impl js_gc::Trace for Frame {
271    fn trace(&self, tracer: &mut js_gc::Tracer) {
272        self.code.trace(tracer);
273        self.env.trace(tracer);
274        self.this.trace(tracer);
275        for value in &self.args {
276            value.trace(tracer);
277        }
278        for value in &self.passed {
279            value.trace(tracer);
280        }
281        for value in &self.locals {
282            value.trace(tracer);
283        }
284        for cell in &self.cells {
285            cell.trace(tracer);
286        }
287        if let Some(local_vars) = &self.local_vars {
288            tracer.visit(local_vars);
289        }
290        for value in &self.stack {
291            value.trace(tracer);
292        }
293        self.callee.trace(tracer);
294        self.new_target.trace(tracer);
295    }
296}
297
298/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
299/// emitted `if_false` treats as "keep going".
300const RESUME_NEXT: i32 = 0;
301/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
302/// generator fall into its `return_async`.
303const RESUME_RETURN: i32 = 1;
304
305/// One microtask.
306///
307/// The queue holds *data* rather than closures because its contents are GC values: a
308/// closure would be invisible to the collector, and a pending reaction is exactly the
309/// kind of thing that must keep its handlers and its promise alive.
310pub enum Job {
311    /// A `then` reaction about to run.
312    Reaction {
313        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
314        handler: Option<Value>,
315        /// The value or reason to call it with.
316        argument: Value,
317        /// Whether the source promise rejected, which decides the pass-through kind.
318        rejected: bool,
319        /// The promise the answer settles.
320        promise: Gc<JsObject>,
321    },
322    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
323    Thenable {
324        /// The `then` that was found on the value.
325        then: Value,
326        /// The thenable itself, which becomes `then`'s `this`.
327        value: Value,
328        /// The promise being resolved.
329        promise: Gc<JsObject>,
330    },
331    /// A pending `import(specifier)`.
332    Import {
333        /// The specifier, already converted to a string.
334        specifier: String,
335        /// The module that asked, which the specifier resolves against.
336        referrer: String,
337        /// The promise `import()` handed back.
338        promise: Gc<JsObject>,
339    },
340    /// An async generator resuming after the value it awaited settled.
341    GeneratorResume {
342        /// The async generator to continue.
343        generator: Gc<JsObject>,
344        /// The promise the pending method returned.
345        promise: Gc<JsObject>,
346        /// Whether this delivers the value or raises the reason.
347        kind: ResumeKind,
348        /// The settled value, or the rejection reason.
349        value: Value,
350    },
351    /// An async function resuming after the value it awaited settled.
352    Resume {
353        /// The body, parked in a coroutine.
354        coroutine: Gc<JsObject>,
355        /// The promise the async function handed its caller.
356        promise: Gc<JsObject>,
357        /// Whether this resumption delivers a value or raises one.
358        kind: ResumeKind,
359        /// The settled value, or the rejection reason.
360        value: Value,
361    },
362}
363
364impl js_gc::Trace for Job {
365    fn trace(&self, tracer: &mut js_gc::Tracer) {
366        match self {
367            Job::Reaction {
368                handler,
369                argument,
370                promise,
371                ..
372            } => {
373                if let Some(handler) = handler {
374                    handler.trace(tracer);
375                }
376                argument.trace(tracer);
377                tracer.visit(promise);
378            }
379            Job::Thenable {
380                then,
381                value,
382                promise,
383            } => {
384                then.trace(tracer);
385                value.trace(tracer);
386                tracer.visit(promise);
387            }
388            Job::Resume {
389                coroutine,
390                promise,
391                value,
392                ..
393            } => {
394                tracer.visit(coroutine);
395                tracer.visit(promise);
396                value.trace(tracer);
397            }
398            Job::Import { promise, .. } => tracer.visit(promise),
399            Job::GeneratorResume {
400                generator,
401                promise,
402                value,
403                ..
404            } => {
405                tracer.visit(generator);
406                tracer.visit(promise);
407                value.trace(tracer);
408            }
409        }
410    }
411}
412
413/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub enum ResumeKind {
416    /// The generator was just created and is being run to its first suspension.
417    Start,
418    /// `next(v)`.
419    Next,
420    /// `return(v)`.
421    Return,
422    /// `throw(e)`.
423    Throw,
424}
425
426/// A generator object's saved execution.
427///
428/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
429/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
430/// separately allocated buffers.
431pub struct GeneratorState {
432    /// The detached frame, or `None` once the generator has finished or while it runs.
433    frame: Option<Frame>,
434    /// How far it got.
435    phase: GeneratorPhase,
436    /// Whether the last suspension was an `await` rather than a `yield`.
437    ///
438    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
439    /// value and a magic number, because the emitted code branches on which method
440    /// resumed it, while an `await` simply continues with its value. Getting this wrong
441    /// leaves an extra value on the operand stack that the next instruction then
442    /// consumes — a wrong answer rather than a crash.
443    parked_on_await: bool,
444}
445
446/// Which of §27.5.3.3's states a generator is in.
447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
448enum GeneratorPhase {
449    /// Created, `initial_yield` reached, body not entered.
450    SuspendedStart,
451    /// Parked at a `yield`.
452    SuspendedYield,
453    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
454    Executing,
455    /// Finished; the frame is gone.
456    Completed,
457}
458
459impl js_gc::Trace for GeneratorState {
460    fn trace(&self, tracer: &mut js_gc::Tracer) {
461        if let Some(frame) = &self.frame {
462            frame.trace(tracer);
463        }
464    }
465}
466
467/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
468/// them in.
469///
470/// Each is a field rather than a map entry because the runtime reads them on hot paths
471/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
472/// failure — reaching a default here means the builtin did not install, and every
473/// accessor panics rather than silently answering `undefined`.
474///
475/// [`builtins::symbol`]: crate::builtins::symbol
476#[derive(Default)]
477pub struct WellKnownSymbols {
478    /// The symbol values, positionally. Empty until `Symbol` installs.
479    symbols: Vec<Value>,
480}
481
482/// Which well-known symbol a caller wants.
483///
484/// A typed accessor beats passing a name around: a typo is a compile error rather than
485/// an `undefined` key that quietly matches nothing.
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum WellKnown {
488    /// `Symbol.toPrimitive`.
489    ToPrimitive,
490    /// `Symbol.iterator`.
491    Iterator,
492    /// `Symbol.match`.
493    Match,
494    /// `Symbol.matchAll`.
495    MatchAll,
496    /// `Symbol.replace`.
497    Replace,
498    /// `Symbol.search`.
499    Search,
500    /// `Symbol.split`.
501    Split,
502    /// `Symbol.toStringTag`.
503    ToStringTag,
504    /// `Symbol.isConcatSpreadable`.
505    IsConcatSpreadable,
506    /// `Symbol.hasInstance`.
507    HasInstance,
508    /// `Symbol.species`.
509    Species,
510    /// `Symbol.unscopables`.
511    Unscopables,
512    /// `Symbol.asyncIterator`.
513    AsyncIterator,
514    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
515    Disposable,
516    /// `Symbol.asyncDispose` — the awaited form.
517    AsyncDisposable,
518}
519
520impl WellKnown {
521    /// The index `Symbol`'s installer creates this symbol at.
522    fn index(self) -> usize {
523        match self {
524            WellKnown::ToPrimitive => 0,
525            WellKnown::Iterator => 1,
526            WellKnown::Match => 2,
527            WellKnown::MatchAll => 3,
528            WellKnown::Replace => 4,
529            WellKnown::Search => 5,
530            WellKnown::Split => 6,
531            WellKnown::ToStringTag => 7,
532            WellKnown::IsConcatSpreadable => 8,
533            WellKnown::HasInstance => 9,
534            WellKnown::Species => 10,
535            WellKnown::Unscopables => 11,
536            WellKnown::AsyncIterator => 12,
537            WellKnown::Disposable => 13,
538            WellKnown::AsyncDisposable => 14,
539        }
540    }
541}
542
543impl Realm {
544    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
545    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
546        self.well_known_symbols.symbols = symbols;
547    }
548
549    /// A well-known symbol.
550    pub fn well_known(&self, which: WellKnown) -> Value {
551        self.well_known_symbols
552            .symbols
553            .get(which.index())
554            .cloned()
555            .unwrap_or(Value::Undefined)
556    }
557
558    /// The well-known symbol as a property key.
559    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
560        match self.well_known(which) {
561            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
562            // Unreachable once `Symbol` has installed; an empty string key matches
563            // nothing, which degrades to "the object has no such method".
564            _ => PropertyKey::from(String::new()),
565        }
566    }
567}
568
569/// The interpreter: a realm plus a frame stack.
570pub struct Interp<'a> {
571    /// The heap everything is allocated on.
572    pub heap: &'a Heap,
573    /// The realm.
574    pub realm: Realm,
575    /// Active frames, outermost first.
576    frames: Vec<Frame>,
577    /// A strict-mode `eval`'s own variable scope, while its script runs.
578    ///
579    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
580    /// become a global. Name lookups still fall through to the realm, which is why
581    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
582    eval_scope: Option<BTreeMap<String, Value>>,
583    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
584    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
585    eval_depth: usize,
586    /// The calling frame's own bindings, which the running `eval` can read and write.
587    ///
588    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
589    /// come from the frame, and a write is applied back to the frame (or to the cell
590    /// the frame captured) when the eval finishes. That is what makes
591    /// `f("a = 3")` visible to the caller as `a === 3`.
592    eval_bindings: Vec<EvalBinding>,
593    /// The calling frame's `arguments`, while an `eval` runs.
594    ///
595    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
596    /// own yet still has to see the caller's `arguments`.
597    eval_arguments: Option<Value>,
598    /// The `with` objects live at the moment the running `eval` started, innermost first.
599    ///
600    /// `None` outside an eval, which is what keeps a finished block's object from
601    /// shadowing ordinary bytecode reads.
602    eval_with: Option<Vec<Gc<JsObject>>>,
603    /// The bindings the running direct `eval` makes visible, as name → cell.
604    ///
605    /// Set for the duration of an eval and then restored, but every closure created
606    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
607    /// `eval("f = () => i")` work after the eval has returned.
608    active_eval_scope: Option<Gc<EvalScope>>,
609    /// The frame that called the direct `eval` currently running, if any.
610    ///
611    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
612    /// on the global object, which is what keeps
613    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
614    /// gives each call its own `x`.
615    eval_caller: Option<Option<usize>>,
616    /// The caller's `new.target`, while an `eval` runs.
617    ///
618    /// The eval'd code is a script with no constructor of its own, so it inherits the
619    /// one the enclosing function was called with.
620    eval_new_target: Option<Value>,
621    /// `new.target` for the frame about to be pushed.
622    ///
623    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
624    /// value reaches the frame without threading a parameter through every call site.
625    pending_new_target: Option<Value>,
626    /// Names of the native functions currently executing, outermost first.
627    ///
628    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
629    /// trace still names it with `(native)` instead of a position, so the names are
630    /// tracked separately and stitched into [`Interp::stack_trace`].
631    native_frames: Vec<(String, Gc<JsObject>)>,
632    /// The native function currently executing, for the ones that have to know *which*
633    /// function they are — a typed-array constructor reads its element type off itself.
634    ///
635    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
636    /// reports whatever the enclosing bytecode frame was called with.
637    current_native: Option<Gc<JsObject>>,
638    /// Text written by `print` and friends, in order.
639    ///
640    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
641    /// once at the end, which is also when upstream's line buffering becomes
642    /// visible for the cases compared here.
643    pub output: String,
644    /// The most frames that may be live at once.
645    pub max_frames: usize,
646    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
647    ///
648    /// Script execution does not return until this has drained, which is what makes
649    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
650    /// than never. Reactions append to it while it drains, so the loop is a `while` and
651    /// not a `for`.
652    pub(crate) jobs: std::collections::VecDeque<Job>,
653    /// The module registry, keyed by canonical name.
654    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
655    /// How the host turns a specifier into bytes.
656    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
657    /// The module the host was asked to run, for `import.meta.main`.
658    pub main_module_name: Option<String>,
659    /// Module bodies currently running, innermost last.
660    ///
661    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
662    /// this is the only place that knows which module that is.
663    pub module_stack: Vec<String>,
664    /// Rejections that no handler has claimed, with the promise they belong to.
665    ///
666    /// A `then` registered later prunes its entry, which is why the promise is kept: the
667    /// reason alone cannot say whether somebody eventually listened.
668    unhandled: Vec<(Gc<JsObject>, Value)>,
669}
670
671impl<'a> Interp<'a> {
672    /// Build an interpreter over `heap`, with a fresh realm.
673    pub fn new(heap: &'a Heap) -> Interp<'a> {
674        let object_proto = JsObject::ordinary(heap, None);
675        let function_proto = JsObject::function(
676            heap,
677            Some(object_proto.clone()),
678            Callable::Native {
679                func: |_, _, _| Ok(Value::Undefined),
680                own_instance: false,
681            },
682        );
683        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
684        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
685        let mut interp = Interp {
686            heap,
687            realm: Realm {
688                global,
689                object_proto,
690                function_proto,
691                array_proto,
692                globals: BTreeMap::new(),
693                declared: Vec::new(),
694                lexical_consts: BTreeSet::new(),
695                errors: BTreeMap::new(),
696                string_proto: None,
697                number_proto: None,
698                boolean_proto: None,
699                bigint_proto: None,
700                error_proto: JsObject::ordinary(heap, None),
701                date_proto: JsObject::ordinary(heap, None),
702                generator_proto: JsObject::ordinary(heap, None),
703                promise_proto: None,
704                async_generator_proto: None,
705                symbol_proto: None,
706                symbol_registry: BTreeMap::new(),
707                internal_slots: BTreeMap::new(),
708                regexp_proto: None,
709                regexp_ctor: None,
710                suppressed_error_proto: None,
711                disposable_stack_proto: None,
712                map_proto: None,
713                set_proto: None,
714                array_buffer_proto: None,
715                typed_array_proto: None,
716                typed_array_protos: Vec::new(),
717                data_view_proto: None,
718                async_disposable_stack_proto: None,
719                iterator_proto: None,
720                iterator_helper_proto: None,
721                iterator_wrap_proto: None,
722                generator_function_proto: None,
723                async_function_proto: None,
724                async_generator_function_proto: None,
725                iterator_protos: std::collections::BTreeMap::new(),
726                well_known_symbols: WellKnownSymbols::default(),
727            },
728            frames: Vec::new(),
729            eval_scope: None,
730            eval_depth: 0,
731            eval_bindings: Vec::new(),
732            eval_arguments: None,
733            eval_with: None,
734            active_eval_scope: None,
735            eval_caller: None,
736            pending_new_target: None,
737            eval_new_target: None,
738            native_frames: Vec::new(),
739            current_native: None,
740            output: String::new(),
741            max_frames: 4096,
742            jobs: std::collections::VecDeque::new(),
743            modules: std::collections::BTreeMap::new(),
744            module_loader: None,
745            main_module_name: None,
746            module_stack: Vec::new(),
747            unhandled: Vec::new(),
748        };
749        crate::builtins::install(&mut interp);
750        interp
751    }
752
753    // -- allocation helpers -------------------------------------------------
754
755    /// A new string value.
756    /// A `BigInt` value from a computed big integer.
757    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
758        Value::BigInt(Gc::new(self.heap, value))
759    }
760
761    /// A string value from bytes that are already WTF-8, which is how a string with an
762    /// unpaired surrogate reaches a `Value`.
763    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
764        Value::string_wtf8(self.heap, text)
765    }
766
767    /// A new string value, from text that is valid UTF-8.
768    pub fn string(&self, text: impl Into<String>) -> Value {
769        Value::string(self.heap, text)
770    }
771
772    /// A new ordinary object with the given prototype.
773    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
774        JsObject::ordinary(self.heap, proto)
775    }
776
777    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
778    ///
779    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
780    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
781    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
782    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
783    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
784    /// said `[object Object]` instead of `[object Array Iterator]`.
785    ///
786    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
787    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
788    /// its own.
789    pub fn new_iterator_prototype(
790        &mut self,
791        tag: &str,
792        next: crate::object::NativeFn,
793    ) -> Gc<JsObject> {
794        if let Some(existing) = self.realm.iterator_protos.get(tag) {
795            return existing.clone();
796        }
797        let parent = self.realm.iterator_proto.clone();
798        let proto = self.new_object(parent);
799        let next = self.new_native("next", 0, next);
800        proto.define(
801            "next",
802            Property::with_attributes(Value::Object(next), true, false),
803        );
804        let key = self.realm.well_known_key(WellKnown::Iterator);
805        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
806        proto.define_key(
807            &key,
808            Property::with_attributes(Value::Object(identity), true, false),
809        );
810        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
811        let tag_value = self.string(tag);
812        proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
813        self.realm
814            .iterator_protos
815            .insert(tag.to_string(), proto.clone());
816        proto
817    }
818
819    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
820    ///
821    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
822    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
823    /// produced. That is why the two branches are not merged.
824    pub fn object_own_property_keys(
825        &mut self,
826        object: &Gc<JsObject>,
827    ) -> JsResult<Vec<PropertyKey>> {
828        if let Some(keys) = self.proxy_own_keys(object)? {
829            return Ok(keys);
830        }
831        // Integer-like keys ascending, then the string keys in insertion order, then the
832        // symbols — the order every schema that walks an object expects.
833        let entries = object.property_entries();
834        let mut numeric: Vec<u32> = Vec::new();
835        let mut strings: Vec<PropertyKey> = Vec::new();
836        let mut symbols: Vec<PropertyKey> = Vec::new();
837        for (key, _) in entries {
838            match &key {
839                PropertyKey::Symbol(_) => symbols.push(key),
840                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
841                    Some(index) => {
842                        if !numeric.contains(&index) {
843                            numeric.push(index);
844                        }
845                    }
846                    None => strings.push(key),
847                },
848            }
849        }
850        numeric.sort_unstable();
851        let mut keys: Vec<PropertyKey> = numeric
852            .into_iter()
853            .map(|index| PropertyKey::from(index.to_string()))
854            .collect();
855        keys.extend(strings);
856        keys.extend(symbols);
857        Ok(keys)
858    }
859
860    /// The state behind a promise object, or `None` when `object` is not one.
861    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
862        object.with(|data| match &data.kind {
863            ObjectKind::Promise(state) => Some(state.clone()),
864            _ => None,
865        })
866    }
867
868    /// A new pending promise.
869    pub fn new_promise(&mut self) -> Gc<JsObject> {
870        let proto = self.realm.promise_proto.clone();
871        let promise = JsObject::ordinary(self.heap, proto);
872        promise.with_mut(|data| {
873            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
874                crate::object::PromiseState::default(),
875            )));
876        });
877        promise
878    }
879
880    /// Fulfil `promise`, unless it has already settled.
881    ///
882    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
883    /// after `reject`, changes nothing.
884    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
885        let Some(state) = self.promise_state(promise) else {
886            return;
887        };
888        let reactions = {
889            let mut state = state.borrow_mut();
890            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
891                return;
892            }
893            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
894            std::mem::take(&mut state.reactions)
895        };
896        self.queue_reactions(reactions, value, false);
897    }
898
899    /// Reject `promise`, unless it has already settled.
900    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
901        let Some(state) = self.promise_state(promise) else {
902            return;
903        };
904        let reactions = {
905            let mut state = state.borrow_mut();
906            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
907                return;
908            }
909            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
910            std::mem::take(&mut state.reactions)
911        };
912        // Remember it only when nothing is listening *now*; a `then` registered later
913        // prunes the entry in `perform_then`.
914        if reactions.is_empty() {
915            self.unhandled.push((promise.clone(), reason.clone()));
916        }
917        self.queue_reactions(reactions, reason, true);
918    }
919
920    /// Queue one job per reaction.
921    ///
922    /// This is what makes `then` asynchronous even on an already-settled promise:
923    /// `p.then(f); g()` calls `g` first.
924    fn queue_reactions(
925        &mut self,
926        reactions: Vec<crate::object::PromiseReaction>,
927        argument: Value,
928        rejected: bool,
929    ) {
930        for reaction in reactions {
931            let handler = if rejected {
932                reaction.on_rejected.clone()
933            } else {
934                reaction.on_fulfilled.clone()
935            };
936            self.jobs.push_back(Job::Reaction {
937                handler,
938                argument: argument.clone(),
939                rejected,
940                promise: reaction.promise,
941            });
942        }
943    }
944
945    /// `NewPromiseCapability` as the executor receives it: the promise plus its
946    /// resolve/reject pair.
947    ///
948    /// The pair are callable objects rather than Rust closures, because the script gets
949    /// them and may stash them for later.
950    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
951        let promise = self.new_promise();
952        let resolve = JsObject::function(
953            self.heap,
954            Some(self.realm.function_proto.clone()),
955            Callable::PromiseResolve(promise.clone()),
956        );
957        let reject = JsObject::function(
958            self.heap,
959            Some(self.realm.function_proto.clone()),
960            Callable::PromiseReject(promise.clone()),
961        );
962        (promise, Value::Object(resolve), Value::Object(reject))
963    }
964
965    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
966    /// new promise resolved with it.
967    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
968        if let Value::Object(object) = &value
969            && self.promise_state(object).is_some()
970        {
971            return Ok(value);
972        }
973        let promise = self.new_promise();
974        self.resolve_promise_with(&promise, value)?;
975        Ok(Value::Object(promise))
976    }
977
978    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
979    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
980        // Resolving a promise with itself is a `TypeError`. The check exists because the
981        // alternative is a chain of self-reactions that never settles.
982        if let Value::Object(object) = &value
983            && object.ptr_eq(promise)
984        {
985            // The spec rejects *and* throws, so both the promise and the caller see it.
986            let thrown = self.type_error("cannot resolve a promise with itself");
987            let Signal::Throw(error) = thrown.clone() else {
988                unreachable!("type_error always throws")
989            };
990            self.reject_promise(promise, error);
991            return Err(thrown);
992        }
993        let then = match &value {
994            Value::Object(object) => self.get_property(object, "then")?,
995            _ => None,
996        };
997        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
998        if !callable_then {
999            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1000            self.fulfill_promise(promise, value);
1001            return Ok(());
1002        }
1003        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1004        // inside `resolve`, so a script cannot make a promise settle synchronously.
1005        self.jobs.push_back(Job::Thenable {
1006            then: then.expect("checked callable"),
1007            value,
1008            promise: promise.clone(),
1009        });
1010        Ok(())
1011    }
1012
1013    /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1014    pub fn perform_then(
1015        &mut self,
1016        promise: &Gc<JsObject>,
1017        on_fulfilled: Option<Value>,
1018        on_rejected: Option<Value>,
1019    ) -> JsResult<Value> {
1020        let Some(state) = self.promise_state(promise) else {
1021            return Err(self.type_error("not a promise"));
1022        };
1023        // Whether a rejection handler is being attached decides whether a recorded
1024        // rejection stops being unhandled, so it is read before the values are moved.
1025        let has_rejection_handler = on_rejected.is_some();
1026        let derived = self.new_promise();
1027        let reaction = crate::object::PromiseReaction {
1028            on_fulfilled,
1029            on_rejected,
1030            promise: derived.clone(),
1031        };
1032        let settled = {
1033            let mut state = state.borrow_mut();
1034            // A rejection somebody reacts to is no longer unhandled.
1035            state.handled = true;
1036            match &state.status {
1037                crate::object::PromiseStatus::Pending => {
1038                    state.reactions.push(reaction.clone());
1039                    None
1040                }
1041                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1042                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1043            }
1044        };
1045        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1046        // later, means somebody is listening after all.
1047        if has_rejection_handler {
1048            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1049        }
1050        if let Some((argument, rejected)) = settled {
1051            let handler = if rejected {
1052                reaction.on_rejected
1053            } else {
1054                reaction.on_fulfilled
1055            };
1056            self.jobs.push_back(Job::Reaction {
1057                handler,
1058                argument,
1059                rejected,
1060                promise: reaction.promise,
1061            });
1062        }
1063        Ok(Value::Object(derived))
1064    }
1065
1066    /// The rejections nobody listened to, formatted the way the reference reports them.
1067    ///
1068    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1069    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1070    /// unhandled at the point the queue drains, because a `then` may still be attached
1071    /// before the host acts on it.
1072    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1073        let entries = std::mem::take(&mut self.unhandled);
1074        // Somebody may have attached a handler after the rejection was recorded, so the
1075        // promise is the authority rather than the list.
1076        let still_unhandled: Vec<Value> = entries
1077            .into_iter()
1078            .filter_map(|(promise, reason)| {
1079                let handled = self
1080                    .promise_state(&promise)
1081                    .map(|state| state.borrow().handled)
1082                    .unwrap_or(true);
1083                (!handled).then_some(reason)
1084            })
1085            .collect();
1086        still_unhandled
1087            .into_iter()
1088            .map(|reason| {
1089                let text = self.describe_exception(&reason);
1090                let stack = match &reason {
1091                    Value::Object(object) => self
1092                        .get_property(object, "stack")
1093                        .ok()
1094                        .flatten()
1095                        .map(|value| value.to_js_string())
1096                        // `stack` carries a trailing newline of its own, which would leave
1097                        // a blank line between two reported rejections.
1098                        .map(|text| text.trim_end().to_string())
1099                        .unwrap_or_default(),
1100                    _ => String::new(),
1101                };
1102                if stack.is_empty() {
1103                    format!("Possibly unhandled promise rejection: {text}")
1104                } else {
1105                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
1106                }
1107            })
1108            .collect()
1109    }
1110
1111    /// Run the microtask queue to exhaustion.
1112    ///
1113    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1114    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1115    pub fn drain_jobs(&mut self) -> JsResult<()> {
1116        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
1117        // would spin forever, so the drain is bounded the way the call stack is.
1118        let mut budget = 1_000_000usize;
1119        while let Some(job) = self.jobs.pop_front() {
1120            if budget == 0 {
1121                return Err(Signal::Throw(
1122                    self.make_error("InternalError", "promise job queue did not drain"),
1123                ));
1124            }
1125            budget -= 1;
1126            self.run_job(job)?;
1127        }
1128        Ok(())
1129    }
1130
1131    /// Run one microtask.
1132    fn run_job(&mut self, job: Job) -> JsResult<()> {
1133        match job {
1134            Job::Reaction {
1135                handler: None,
1136                argument,
1137                rejected,
1138                promise,
1139            } => {
1140                // No handler: the settlement passes straight through to the derived
1141                // promise, which is why `p.catch(f)` ignores fulfilments.
1142                if rejected {
1143                    self.reject_promise(&promise, argument);
1144                } else {
1145                    self.fulfill_promise(&promise, argument);
1146                }
1147                Ok(())
1148            }
1149            Job::Reaction {
1150                handler: Some(handler),
1151                argument,
1152                promise,
1153                ..
1154            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
1155                Ok(answer) => {
1156                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
1157                        self.reject_promise(&promise, error);
1158                    }
1159                    Ok(())
1160                }
1161                Err(Signal::Throw(reason)) => {
1162                    self.reject_promise(&promise, reason);
1163                    Ok(())
1164                }
1165                Err(other) => Err(other),
1166            },
1167            Job::Thenable {
1168                then,
1169                value,
1170                promise,
1171            } => {
1172                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
1173                // the value it produces settles `promise`.
1174                // The thenable's `then` gets this promise's own pair, so whatever it
1175                // produces settles `promise`.
1176                let resolve = JsObject::function(
1177                    self.heap,
1178                    Some(self.realm.function_proto.clone()),
1179                    Callable::PromiseResolve(promise.clone()),
1180                );
1181                let reject = JsObject::function(
1182                    self.heap,
1183                    Some(self.realm.function_proto.clone()),
1184                    Callable::PromiseReject(promise.clone()),
1185                );
1186                match self.call_value(
1187                    then,
1188                    value,
1189                    vec![Value::Object(resolve), Value::Object(reject)],
1190                ) {
1191                    Ok(_) => Ok(()),
1192                    Err(Signal::Throw(reason)) => {
1193                        self.reject_promise(&promise, reason);
1194                        Ok(())
1195                    }
1196                    Err(other) => Err(other),
1197                }
1198            }
1199            Job::Resume {
1200                coroutine,
1201                promise,
1202                kind,
1203                value,
1204            } => self.drive_async(&coroutine, &promise, kind, value),
1205            Job::GeneratorResume {
1206                generator,
1207                promise,
1208                kind,
1209                value,
1210            } => self.step_async_generator(&generator, &promise, kind, value),
1211            Job::Import {
1212                specifier,
1213                referrer,
1214                promise,
1215            } => {
1216                self.run_dynamic_import(&specifier, &referrer, &promise);
1217                Ok(())
1218            }
1219        }
1220    }
1221
1222    /// One element of a `Promise` combinator settled.
1223    ///
1224    /// The shared state object holds the results array, the number still outstanding, and
1225    /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
1226    /// the input order; `race` settles on the first element and ignores the rest, which a
1227    /// one-shot settle gives for free.
1228    fn settle_combinator(
1229        &mut self,
1230        state: &Gc<JsObject>,
1231        index: usize,
1232        fulfilled: bool,
1233        value: Value,
1234    ) -> JsResult<()> {
1235        let kind = state
1236            .own_property("kind")
1237            .and_then(|property| property.value)
1238            .map(|value| value.to_int32())
1239            .unwrap_or(0);
1240        let outcome = state
1241            .own_property("outcome")
1242            .and_then(|property| property.value);
1243        let Some(Value::Object(outcome)) = outcome else {
1244            return Ok(());
1245        };
1246        if kind == 3 {
1247            // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
1248            if fulfilled {
1249                self.resolve_promise_with(&outcome, value)?;
1250            } else {
1251                self.reject_promise(&outcome, value);
1252            }
1253            return Ok(());
1254        }
1255        let results = state
1256            .own_property("results")
1257            .and_then(|property| property.value)
1258            .and_then(|value| value.as_object().cloned());
1259        let remaining = state
1260            .own_property("remaining")
1261            .and_then(|property| property.value)
1262            .map(|value| value.to_int32())
1263            .unwrap_or(0);
1264        match kind {
1265            0 => {
1266                // `all`: the first rejection wins outright.
1267                if !fulfilled {
1268                    self.reject_promise(&outcome, value);
1269                    return Ok(());
1270                }
1271                let Some(results) = &results else {
1272                    return Ok(());
1273                };
1274                results.array_set(index, value);
1275            }
1276            1 => {
1277                // `allSettled`: never rejects; each slot records what happened.
1278                let Some(results) = &results else {
1279                    return Ok(());
1280                };
1281                let record = self.new_object(Some(self.realm.object_proto.clone()));
1282                if fulfilled {
1283                    record.define_data("status", self.string("fulfilled"));
1284                    record.define_data("value", value);
1285                } else {
1286                    record.define_data("status", self.string("rejected"));
1287                    record.define_data("reason", value);
1288                }
1289                results.array_set(index, Value::Object(record));
1290            }
1291            2 => {
1292                // `any`: the first fulfilment wins; a full sweep of rejections does not
1293                // settle here — it is handled by the count below.
1294                if fulfilled {
1295                    self.resolve_promise_with(&outcome, value)?;
1296                    return Ok(());
1297                }
1298            }
1299            _ => {}
1300        }
1301        let left = remaining - 1;
1302        state.define_data("remaining", Value::Int(left));
1303        if left != 0 {
1304            return Ok(());
1305        }
1306        match kind {
1307            0 | 1 => {
1308                let Some(results) = results else {
1309                    return Ok(());
1310                };
1311                self.resolve_promise_with(&outcome, Value::Object(results))?;
1312            }
1313            2 => {
1314                let error = self.make_error("AggregateError", "all promises were rejected");
1315                self.reject_promise(&outcome, error);
1316            }
1317            _ => {}
1318        }
1319        Ok(())
1320    }
1321
1322    /// Build an async function's result: a promise whose body runs as a coroutine.
1323    pub fn new_async_function(
1324        &mut self,
1325        function: Value,
1326        this: Value,
1327        args: Vec<Value>,
1328    ) -> JsResult<Value> {
1329        let promise = self.new_promise();
1330        let coroutine = self.new_coroutine(function, this, args)?;
1331        if let Err(Signal::Throw(reason)) =
1332            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1333        {
1334            self.reject_promise(&promise, reason);
1335        }
1336        Ok(Value::Object(promise))
1337    }
1338
1339    /// The coroutine an async body runs in.
1340    ///
1341    /// Generator-shaped and never exposed to the script: what makes `await` work is the
1342    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
1343    /// than growing a second state machine. The difference is only in the ending — a
1344    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
1345    /// Run `code` as an async function body, answering the promise it settles.
1346    ///
1347    /// Used for a module with top-level `await`: its body is an async function whose
1348    /// caller is the host, so there is no function object to pass through
1349    /// [`Interp::new_async_function`].
1350    pub fn run_async_body(
1351        &mut self,
1352        code: Gc<CompiledCode>,
1353        env: Gc<ClosureEnv>,
1354    ) -> JsResult<Value> {
1355        let promise = self.new_promise();
1356        let coroutine = self.new_coroutine_from(code, env, Value::Undefined, Vec::new())?;
1357        if let Err(Signal::Throw(reason)) =
1358            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1359        {
1360            self.reject_promise(&promise, reason);
1361        }
1362        Ok(Value::Object(promise))
1363    }
1364
1365    fn new_coroutine(
1366        &mut self,
1367        function: Value,
1368        this: Value,
1369        args: Vec<Value>,
1370    ) -> JsResult<Gc<JsObject>> {
1371        let Some(object) = function.as_object().cloned() else {
1372            return Err(self.type_error("not a function"));
1373        };
1374        let Some((code, env)) = bytecode_of(&object) else {
1375            return Err(self.type_error("not a function"));
1376        };
1377        self.new_coroutine_from(code, env, this, args)
1378    }
1379
1380    /// Build a coroutine over an already-resolved body.
1381    fn new_coroutine_from(
1382        &mut self,
1383        code: Gc<CompiledCode>,
1384        env: Gc<ClosureEnv>,
1385        this: Value,
1386        args: Vec<Value>,
1387    ) -> JsResult<Gc<JsObject>> {
1388        let function = Value::Undefined;
1389        self.push_frame(code, env, this, args, function)?;
1390        let frame = self.frames.pop().expect("push_frame just pushed it");
1391        let state = GeneratorState {
1392            frame: Some(frame),
1393            phase: GeneratorPhase::SuspendedStart,
1394            parked_on_await: false,
1395        };
1396        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
1397        coroutine.with_mut(|data| {
1398            data.kind = ObjectKind::Generator(Box::new(state));
1399        });
1400        Ok(coroutine)
1401    }
1402
1403    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
1404    /// `await` and `value` is what it awaited.
1405    fn resume_coroutine(
1406        &mut self,
1407        coroutine: &Gc<JsObject>,
1408        kind: ResumeKind,
1409        value: Value,
1410    ) -> JsResult<(Value, bool)> {
1411        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
1412            ObjectKind::Generator(state) => Some(std::mem::replace(
1413                state.as_mut(),
1414                GeneratorState {
1415                    frame: None,
1416                    phase: GeneratorPhase::Executing,
1417                    parked_on_await: false,
1418                },
1419            )),
1420            _ => None,
1421        }) else {
1422            return Err(self.type_error("not a coroutine"));
1423        };
1424        let result = self.step_generator(&mut state, kind, value);
1425        coroutine.with_mut(|data| {
1426            data.kind = ObjectKind::Generator(Box::new(state));
1427        });
1428        let (value, done, _ready, _reason) = result?;
1429        Ok((value, done))
1430    }
1431
1432    /// Advance an async body and settle its promise with the outcome.
1433    fn drive_async(
1434        &mut self,
1435        coroutine: &Gc<JsObject>,
1436        promise: &Gc<JsObject>,
1437        kind: ResumeKind,
1438        value: Value,
1439    ) -> JsResult<()> {
1440        match self.resume_coroutine(coroutine, kind, value) {
1441            Ok((value, true)) => {
1442                // `Ok` with `done` means the body finished *normally*, even when it was
1443                // resumed by a `throw` — `try { await p } catch {}` completes by
1444                // returning. Only the `Err` arm below is a rejection.
1445                //
1446                // Resolving rather than fulfilling matters: `return promise` in an async
1447                // body adopts the inner promise, so `async function f(){ return
1448                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
1449                // promise.
1450                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
1451                    self.reject_promise(promise, reason);
1452                }
1453                Ok(())
1454            }
1455            Ok((value, false)) => {
1456                // Parked on `await`: follow what it awaited and resume with the outcome.
1457                let awaited = match self.promise_resolve_value(value) {
1458                    Ok(awaited) => awaited,
1459                    Err(Signal::Throw(error)) => {
1460                        self.reject_promise(promise, error);
1461                        return Ok(());
1462                    }
1463                    Err(other) => return Err(other),
1464                };
1465                self.hook_await(awaited, coroutine, promise)
1466            }
1467            Err(Signal::Throw(reason)) => {
1468                self.reject_promise(promise, reason);
1469                Ok(())
1470            }
1471            Err(other) => Err(other),
1472        }
1473    }
1474
1475    /// Arrange for `coroutine` to resume when `awaited` settles.
1476    fn hook_await(
1477        &mut self,
1478        awaited: Value,
1479        coroutine: &Gc<JsObject>,
1480        promise: &Gc<JsObject>,
1481    ) -> JsResult<()> {
1482        let resumed = JsObject::function(
1483            self.heap,
1484            Some(self.realm.function_proto.clone()),
1485            Callable::AwaitResume {
1486                coroutine: coroutine.clone(),
1487                promise: promise.clone(),
1488                kind: ResumeKind::Next,
1489            },
1490        );
1491        let raised = JsObject::function(
1492            self.heap,
1493            Some(self.realm.function_proto.clone()),
1494            Callable::AwaitResume {
1495                coroutine: coroutine.clone(),
1496                promise: promise.clone(),
1497                kind: ResumeKind::Throw,
1498            },
1499        );
1500        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
1501        // guarantees one; the fallback keeps a mis-shaped value from panicking.
1502        let Value::Object(awaited) = &awaited else {
1503            self.jobs.push_back(Job::Resume {
1504                coroutine: coroutine.clone(),
1505                promise: promise.clone(),
1506                kind: ResumeKind::Next,
1507                value: awaited,
1508            });
1509            return Ok(());
1510        };
1511        self.perform_then(
1512            awaited,
1513            Some(Value::Object(resumed)),
1514            Some(Value::Object(raised)),
1515        )?;
1516        Ok(())
1517    }
1518
1519    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
1520    /// things an engine keeps outside it — array elements and an array's `length`.
1521    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
1522        if let Some(property) = object.own_property_key(key) {
1523            return Some(property);
1524        }
1525        // An array's elements live in their own vector rather than the property table, so
1526        // a descriptor for one has to be synthesized — with the attributes an element has.
1527        if let Some(index) = key.as_str().and_then(array_index)
1528            && let Some(value) = object.array_get(index as usize)
1529            && !matches!(value, Value::Hole)
1530        {
1531            return Some(Property::data(value));
1532        }
1533        // `length` is an own property of an array that is not in its property table
1534        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
1535        // and non-enumerable.
1536        if key.as_str() == Some("length")
1537            && let Some(length) = object.array_length()
1538        {
1539            return Some(Property {
1540                value: Some(crate::object::length_value(length)),
1541                writable: object.length_writable(),
1542                enumerable: false,
1543                configurable: false,
1544                getter: None,
1545                setter: None,
1546            });
1547        }
1548        None
1549    }
1550
1551    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
1552    pub fn object_get_own_property(
1553        &mut self,
1554        object: &Gc<JsObject>,
1555        key: &PropertyKey,
1556    ) -> JsResult<Option<Property>> {
1557        if let Some(answer) = self.proxy_get_own_property(object, key)? {
1558            return Ok(answer);
1559        }
1560        Ok(Self::ordinary_own_property(object, key))
1561    }
1562
1563    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
1564    pub fn object_define_own_property(
1565        &mut self,
1566        object: &Gc<JsObject>,
1567        key: &PropertyKey,
1568        property: Property,
1569    ) -> JsResult<bool> {
1570        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
1571            return Ok(accepted);
1572        }
1573        // An array index is stored in the element vector, which can hold a plain value and
1574        // nothing else. An accessor — or a data property with non-default attributes —
1575        // therefore has to live in the property table, and the element slot is blanked so
1576        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
1577        // {get})` stored the accessor where no read ever looked, and the array kept
1578        // answering its old value.
1579        // An array's `length` is not stored in the property table, so defining it has to
1580        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
1581        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
1582        // {value: 1})` reported success and changed nothing.
1583        if key.as_str() == Some("length") && object.is_array() {
1584            // `{writable: false}` on `length` does not change the length, but it does make
1585            // it read-only — after which neither a later `{writable: true}` nor a store
1586            // past the end may succeed.
1587            if property.value.is_none() {
1588                if !object.length_writable() && property.writable {
1589                    return Ok(false);
1590                }
1591                object.set_length_writable(property.writable);
1592                return Ok(true);
1593            }
1594            if !object.length_writable() {
1595                return Ok(false);
1596            }
1597        }
1598        if key.as_str() == Some("length")
1599            && object.is_array()
1600            && let Some(value) = property.value.clone()
1601        {
1602            let requested = value.to_number();
1603            let valid = requested.is_finite()
1604                && requested >= 0.0
1605                && requested.fract() == 0.0
1606                && requested <= u32::MAX as f64;
1607            if !valid {
1608                return Err(self.range_error("invalid array length"));
1609            }
1610            // Truncating deletes the elements above the new length, and a non-configurable
1611            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
1612            // makes `a.length = 2` fail rather than quietly drop it.
1613            let current = object.array_length().unwrap_or(0);
1614            let requested = requested as usize;
1615            if requested < current
1616                && (requested..current).any(|index| object.element_is_undeletable(index as u32))
1617            {
1618                return Ok(false);
1619            }
1620            object.array_set_length(requested);
1621            return Ok(true);
1622        }
1623        let plain = property.writable
1624            && property.enumerable
1625            && property.configurable
1626            && !property.is_accessor();
1627        if let Some(index) = key.as_str().and_then(array_index)
1628            && object.is_array()
1629        {
1630            // Growing the array needs a writable `length`: after
1631            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
1632            // be added.
1633            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
1634                return Ok(false);
1635            }
1636            if plain && let Some(value) = property.value {
1637                // An ordinary element: the vector is where a read looks first, so it has
1638                // to be the vector that changes.
1639                object.delete_key(key);
1640                object.array_set(index as usize, value);
1641                return Ok(true);
1642            }
1643            object.define_key(key, property);
1644            // The slot stays, so `length` does not shrink; a hole is not an element, so
1645            // the table entry is now what a read finds.
1646            object.array_set(index as usize, Value::Hole);
1647            return Ok(true);
1648        }
1649        object.define_key(key, property);
1650        Ok(true)
1651    }
1652
1653    /// Build a proxy object over `target`, with its traps read from `handler`.
1654    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
1655        JsObject::proxy(self.heap, target, handler)
1656    }
1657
1658    /// The `revoke` function for a proxy's slots.
1659    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
1660        JsObject::function(
1661            self.heap,
1662            Some(self.realm.function_proto.clone()),
1663            Callable::Revoker(slots),
1664        )
1665    }
1666
1667    /// A new array.
1668    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
1669        let array = JsObject::array(
1670            self.heap,
1671            Some(self.realm.array_proto.clone()),
1672            elements.len(),
1673        );
1674        for (index, element) in elements.into_iter().enumerate() {
1675            array.array_set(index, element);
1676        }
1677        array
1678    }
1679
1680    /// A new native function object.
1681    ///
1682    /// The observable `name` and `length` are installed as properties here, which is
1683    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
1684    /// so `f.name = "x"` behaves like the writable property it is.
1685    /// A native constructor that builds its own instance after validating its arguments.
1686    ///
1687    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
1688    /// check runs before `new.target.prototype` is read.
1689    pub fn new_native_ctor(
1690        &self,
1691        name: impl Into<String>,
1692        length: u32,
1693        func: NativeFn,
1694    ) -> Gc<JsObject> {
1695        let function = JsObject::function(
1696            self.heap,
1697            Some(self.realm.function_proto.clone()),
1698            Callable::Native {
1699                func,
1700                own_instance: true,
1701            },
1702        );
1703        function.set_constructible(true);
1704        function.define(
1705            "length",
1706            Property::name_or_length(Value::Int(length as i32)),
1707        );
1708        function.define("name", Property::name_or_length(self.string(name)));
1709        function
1710    }
1711
1712    /// A native constructor that lets `new` build the instance first.
1713    ///
1714    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
1715    /// validation that must precede reading `new.target.prototype`, so the object can be
1716    /// created before the implementation runs. Distinct from [`Interp::new_native`],
1717    /// which makes a *method* and therefore not a constructor at all.
1718    pub fn new_native_constructor(
1719        &self,
1720        name: impl Into<String>,
1721        length: u32,
1722        func: NativeFn,
1723    ) -> Gc<JsObject> {
1724        let function = self.new_native(name, length, func);
1725        function.set_constructible(true);
1726        function
1727    }
1728
1729    /// A new native function object.
1730    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
1731        let function = JsObject::function(
1732            self.heap,
1733            Some(self.realm.function_proto.clone()),
1734            Callable::Native {
1735                func,
1736                own_instance: false,
1737            },
1738        );
1739        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
1740        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
1741        // `length,name` and this listed `name,length`. A bytecode function already gets it
1742        // the right way round; only native ones were built backwards.
1743        function.define(
1744            "length",
1745            Property::name_or_length(Value::Int(length as i32)),
1746        );
1747        function.define("name", Property::name_or_length(self.string(name)));
1748        function
1749    }
1750
1751    /// A new bound function.
1752    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
1753        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
1754        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
1755        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
1756        let constructible = target
1757            .as_object()
1758            .is_some_and(|target| target.is_constructor());
1759        let bound = JsObject::function(
1760            self.heap,
1761            Some(self.realm.function_proto.clone()),
1762            Callable::Bound { target, this, args },
1763        );
1764        bound.set_constructible(constructible);
1765        bound
1766    }
1767
1768    /// A new reference cell.
1769    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
1770        Gc::new(self.heap, Cell::new(value))
1771    }
1772
1773    // -- running ------------------------------------------------------------
1774
1775    /// Evaluate `code` as a script body and return its completion value.
1776    /// Compile and run `source` for the engine's own use, returning its completion value.
1777    ///
1778    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
1779    /// needs to be a real async function, and the engine already runs those as coroutines,
1780    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
1781    ///
1782    /// Differences from [`Self::eval_in_global`], both deliberate:
1783    ///
1784    /// * It does **not** drain the microtask queue. Install runs while the realm is still
1785    ///   being built, and the source is an IIFE that only constructs a closure, so there
1786    ///   is nothing to drain — and draining here would run script-queued jobs in the
1787    ///   middle of `install`.
1788    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
1789    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
1790    ///   and it should not look like the user wrote something wrong.
1791    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
1792        let program = match js_parse::parse_script(source) {
1793            Ok(program) => program,
1794            Err(error) => {
1795                let message = format!("builtin source does not parse: {error}");
1796                return Err(Signal::Throw(self.make_error("InternalError", &message)));
1797            }
1798        };
1799        let mut code = match js_compile::compile_script(&program) {
1800            Ok(code) => code,
1801            Err(error) => {
1802                let message = format!("builtin source does not compile: {}", error.message);
1803                return Err(Signal::Throw(self.make_error("InternalError", &message)));
1804            }
1805        };
1806        // The frame has to name something, and `<builtin>` is what a stack trace through
1807        // this code should say.
1808        code.set_filename("<builtin>");
1809        let compiled = Gc::new(self.heap, CompiledCode::new(code));
1810        let closure_vars = compiled.code.closure_vars.clone();
1811        let env = self.global_env(&closure_vars);
1812        let this = Value::Object(self.realm.global.clone());
1813        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
1814    }
1815
1816    /// Run an already-parsed script and drain the microtasks it queued.
1817    ///
1818    /// The drain is what lets an `async` function's body advance past its first `await`
1819    /// before the host sees the result: nothing else pumps the job queue.
1820    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
1821        let compiled = Gc::new(self.heap, CompiledCode::new(code));
1822        let closure_vars = compiled.code.closure_vars.clone();
1823        let env = self.global_env(&closure_vars);
1824        let this = Value::Object(self.realm.global.clone());
1825        let callee = Value::Undefined;
1826        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
1827        // The script is done, so the microtasks it queued run before the host sees the
1828        // result. Without this an `async` function's body would never advance past its
1829        // first `await`, because nothing else drains the queue.
1830        self.drain_jobs()?;
1831        Ok(result)
1832    }
1833
1834    /// Compile and run `source` in global scope, returning its completion value.
1835    ///
1836    /// This is what `eval` and `new Function` use. Running it as a script means it
1837    /// sees the global object and nothing else, which is right for `eval("1+1")` and
1838    /// for a `Function` body; a *direct* eval that reads a local variable would need
1839    /// the compiler to hand its variable environment over, which is not implemented.
1840    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
1841        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
1842        // eval-created global binding — configurable, unlike a script's own `var`.
1843        self.eval_depth += 1;
1844        let result = self.eval_in_global_inner(source);
1845        self.eval_depth -= 1;
1846        result
1847    }
1848
1849    fn eval_in_global_inner(&mut self, source: &str) -> JsResult<Value> {
1850        // The reference names eval'd code `<input>` rather than inheriting the caller's
1851        // file name, and stack traces show it, so `eval("1 + x")` failing reports
1852        // `(<input>:1:5)`.
1853        const EVAL_FILE: &str = "<input>";
1854        // A *direct* eval inherits the strictness of the code that called it, which is
1855        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
1856        // implicit global. The caller's frame is the innermost one here, because a
1857        // native function does not push a frame of its own.
1858        let strict = self.current_strict();
1859        // `eval` runs in the caller's function context, so `new.target` is legal here
1860        // even though the source is a bare script — and so is `super.x` when the caller
1861        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
1862        // caller's, which is what `special_object 4` already does.
1863        let context = js_parse::EvalContext {
1864            in_method: self.enclosing_home_object().is_some(),
1865            // `super()` belongs to a derived constructor, and an eval'd body is not a
1866            // constructor at all: the caller frame's `this` is already built.
1867            in_derived_constructor: false,
1868        };
1869        let parsed = js_parse::parse_eval_script_in(source, strict, context);
1870        let program = match parsed {
1871            Ok(program) => program,
1872            Err(error) => {
1873                return Err(Signal::Throw(self.syntax_error_at(
1874                    EVAL_FILE,
1875                    error.span.start.line,
1876                    error.span.start.column,
1877                    &format!("invalid source: {error}"),
1878                )));
1879            }
1880        };
1881        let mut compiled = match js_compile::compile_script(&program) {
1882            Ok(compiled) => compiled,
1883            // A construct the compiler does not handle yet is reported the same way a
1884            // parse error is: it happens before anything runs, so the trace is the
1885            // position in the source followed by the caller.
1886            Err(error) => {
1887                return Err(Signal::Throw(self.syntax_error_at(
1888                    EVAL_FILE,
1889                    error.span.start.line,
1890                    error.span.start.column,
1891                    &error.message,
1892                )));
1893            }
1894        };
1895        compiled.set_filename(EVAL_FILE);
1896        let strict = compiled.strict;
1897        self.run_eval_script(compiled, strict)
1898    }
1899
1900    /// Run an `eval`'d script in the caller's scope.
1901    ///
1902    /// Three things have to come from the calling frame, because the eval'd code is a
1903    /// script and would otherwise see only the global object:
1904    ///
1905    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
1906    /// * `arguments`, exposed as a binding of the eval's own scope, so
1907    ///   `f("arguments.length", 1)` sees the caller's arguments;
1908    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
1909    ///   `eval("var v = 1")` into the global object.
1910    ///
1911    /// Locals of the calling function are *not* reachable: that needs the compiler to
1912    /// hand its variable environment over, which this milestone does not do.
1913    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
1914        // `this` and `arguments` come from the innermost frame only — those are not
1915        // lexical — while the name bindings come from the whole chain of frames, part
1916        // of it being ordinary scope resolution.
1917        // An arrow has no `this` of its own, so an `eval` inside one inherits the
1918        // enclosing function's receiver — the lexical `this` the arrow was compiled to
1919        // read from its closure.
1920        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
1921        // variable environment is the innermost frame of all: an arrow's own body is where
1922        // `var`s declared by an `eval` inside it belong.
1923        let caller_index = self
1924            .frames
1925            .iter()
1926            .rposition(|frame| !frame.code.code.is_arrow)
1927            .or_else(|| self.frames.len().checked_sub(1));
1928        let env_index = self.frames.len().checked_sub(1);
1929        let caller = caller_index.and_then(|index| self.frames.get(index));
1930        let (this, passed) = match caller {
1931            Some(frame) => (frame.this.clone(), frame.passed.clone()),
1932            // No frame at all: the eval is running at the top level, so there is
1933            // nothing to inherit and the global receiver is right.
1934            None => (Value::Object(self.realm.global.clone()), Vec::new()),
1935        };
1936        // Innermost frame first, so the first binding found for a name is the one that
1937        // shadows the rest. A script frame (`<eval>`) contributes nothing.
1938        let mut bindings: Vec<EvalBinding> = Vec::new();
1939        // The calling function's own bindings, resolved by the compiler at the call
1940        // site. That table is the only reliable answer when a name is declared twice in
1941        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
1942        // body means, and guessing by declaration order picks the wrong one as soon as
1943        // two loops in a row use the same name.
1944        // Only a *direct* eval sees the caller's scope. The compiler records a site for
1945        // every direct call — a bare `eval(...)` callee — so finding one at the current
1946        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
1947        // callee to a value first and leave no site behind.
1948        let mut direct = false;
1949        let mut resolved_here = false;
1950        if let Some(frame) = self.frames.last() {
1951            let (line, column) = frame
1952                .code
1953                .code
1954                .position_at(frame.at as u32)
1955                .unwrap_or_default();
1956            // The nearest site at or before the current position, not an exact match:
1957            // the recorded position of the `call` instruction is the callee's, which
1958            // sits a few columns inside the call expression the compiler recorded. A
1959            // site is unique per call, so "the closest one behind us" identifies it.
1960            if let Some(site) = frame
1961                .code
1962                .code
1963                .eval_sites
1964                .iter()
1965                .filter(|site| (site.line, site.column) <= (line, column))
1966                .max_by_key(|site| (site.line, site.column))
1967            {
1968                direct = true;
1969                resolved_here = true;
1970                for binding in &site.bindings {
1971                    // An enclosing function's frame sits `owner` levels below the one
1972                    // running the call.
1973                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
1974                    else {
1975                        continue;
1976                    };
1977                    bindings.push(EvalBinding {
1978                        name: binding.name.clone(),
1979                        frame,
1980                        slot: if binding.is_arg {
1981                            EvalSlot::Arg
1982                        } else {
1983                            EvalSlot::Local
1984                        },
1985                        index: binding.index as usize,
1986                    });
1987                }
1988            }
1989        }
1990        for frame_index in (0..self.frames.len()).rev() {
1991            // Skip the innermost frame's flat scan when the compiler already answered
1992            // for it; an enclosing frame still needs one, because the eval resolves
1993            // those names dynamically.
1994            if resolved_here && frame_index == self.frames.len() - 1 {
1995                continue;
1996            }
1997            let frame = &self.frames[frame_index];
1998            for (index, arg) in frame.code.code.args.iter().enumerate() {
1999                bindings.push(EvalBinding {
2000                    name: arg.name.clone(),
2001                    frame: frame_index,
2002                    slot: EvalSlot::Arg,
2003                    index,
2004                });
2005            }
2006            for (index, local) in frame.code.code.vars.iter().enumerate() {
2007                bindings.push(EvalBinding {
2008                    name: local.name.clone(),
2009                    frame: frame_index,
2010                    slot: EvalSlot::Local,
2011                    index,
2012                });
2013            }
2014        }
2015        let mut seen = BTreeSet::new();
2016        bindings.retain(|binding| seen.insert(binding.name.clone()));
2017
2018        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
2019        // elements is all the spec's ordinary uses need.
2020        let arguments = Value::Object(self.new_array(passed));
2021
2022        // Only a *strict* eval gets a variable environment of its own. A sloppy one
2023        // declares its `var`s in the caller's — which for a top-level eval is the global
2024        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
2025        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
2026        // vanish into a scope nobody reads back from.
2027        let previous_scope = if code_strict {
2028            self.eval_scope.replace(BTreeMap::new())
2029        } else {
2030            None
2031        };
2032        let previous_arguments = self.eval_arguments.replace(arguments);
2033        let previous_with = self.eval_with.replace(self.with_objects());
2034        let inherited_new_target = self
2035            .frames
2036            .iter()
2037            .rev()
2038            .find(|frame| !frame.code.code.is_arrow)
2039            .map(|frame| frame.new_target.clone());
2040        let previous_new_target = self
2041            .eval_new_target
2042            .replace(inherited_new_target.unwrap_or(Value::Undefined));
2043        let eval_cells = self.eval_cells_for(&bindings);
2044        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
2045        // A sloppy direct eval declares its `var`s in the caller's variable environment;
2046        // `declare_eval_local` needs to know which frame that is.
2047        // An indirect eval gets the global environment, so nothing of the caller's is
2048        // recorded as the place its `var`s belong.
2049        let previous_caller = self
2050            .eval_caller
2051            .replace(if direct { env_index } else { None });
2052        // The cell-based view of the same bindings, which is what a closure created
2053        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
2054        // whose compiler did not put a binding in a cell simply does not appear here —
2055        // reads and writes still work through `eval_bindings`, they just cannot outlive
2056        // the eval.
2057        let previous_eval_scope = self
2058            .active_eval_scope
2059            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
2060        let compiled = Gc::new(self.heap, CompiledCode::new(code));
2061        let closure_vars = compiled.code.closure_vars.clone();
2062        let env = self.global_env(&closure_vars);
2063        let callee = Value::Undefined;
2064        let result = self.execute(compiled, env, this, Vec::new(), callee);
2065        self.eval_scope = previous_scope;
2066        self.eval_arguments = previous_arguments;
2067        self.eval_with = previous_with;
2068        self.eval_new_target = previous_new_target;
2069        self.eval_bindings = previous_bindings;
2070        self.eval_caller = previous_caller;
2071        self.active_eval_scope = previous_eval_scope;
2072        result
2073    }
2074
2075    /// The cell-backed subset of `bindings`, in the same priority order.
2076    ///
2077    /// Both lookup routes have to agree — the eval's own reads go through
2078    /// [`Interp::eval_binding_value`] and the closures it builds go through
2079    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
2080    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
2081    /// is not in a cell simply does not appear: reads and writes still work, they just
2082    /// cannot be handed to a closure that outlives the eval.
2083    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
2084        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
2085        for binding in bindings {
2086            let Some(frame) = self.frames.get(binding.frame) else {
2087                continue;
2088            };
2089            let cell = match binding.slot {
2090                EvalSlot::Arg => frame
2091                    .code
2092                    .arg_cell
2093                    .get(binding.index)
2094                    .copied()
2095                    .unwrap_or(-1),
2096                EvalSlot::Local => frame
2097                    .code
2098                    .loc_cell
2099                    .get(binding.index)
2100                    .copied()
2101                    .unwrap_or(-1),
2102            };
2103            if cell < 0 {
2104                continue;
2105            }
2106            if let Some(cell) = frame.cells.get(cell as usize) {
2107                names.push((binding.name.clone(), cell.clone()));
2108            }
2109        }
2110        names
2111    }
2112
2113    /// A `SyntaxError` that reports where in the source it happened.
2114    ///
2115    /// Compile-time failures never run, so they have no frame of their own; the
2116    /// reference still puts the position first in the trace, with no function name and
2117    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
2118    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
2119    /// reference borrows), which is how a script reads the position without parsing
2120    /// the trace.
2121    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
2122        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
2123        let value = self.make_error("SyntaxError", message);
2124        if let Value::Object(object) = &value {
2125            let text = self.string(blamed);
2126            object.define("stack", Property::with_attributes(text, true, true));
2127            let name = self.string(file);
2128            object.define("fileName", Property::with_attributes(name, true, true));
2129            object.define(
2130                "lineNumber",
2131                Property::with_attributes(Value::Int(line as i32), true, true),
2132            );
2133            object.define(
2134                "columnNumber",
2135                Property::with_attributes(Value::Int(column as i32), true, true),
2136            );
2137        }
2138        value
2139    }
2140
2141    /// Run a compiled script whose completion value is a function, returning it.
2142    ///
2143    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
2144    /// get the closure out, which keeps the constant-pool plumbing in one place.
2145    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
2146        self.run_script(code)
2147    }
2148
2149    /// The environment of a script or of any function compiled at global scope:
2150    /// every entry is a global binding, so each one resolves to the realm's cell.
2151    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
2152        let mut cells = Vec::with_capacity(closure_vars.len());
2153        for closure_var in closure_vars {
2154            let cell = match closure_var.closure_type {
2155                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
2156                    if closure_var.is_lexical =>
2157                {
2158                    // A lexical declaration: the cell is created here holding the
2159                    // dead-zone marker, which is what makes the binding exist and
2160                    // unreadable before its initialiser runs.
2161                    self.declare_global(&closure_var.name, closure_var.is_const);
2162                    self.realm.globals[&closure_var.name].clone()
2163                }
2164                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
2165                    // A `var` or function declaration becomes a property of the global
2166                    // object, and it exists from here on — which is why
2167                    // `print(v); var v = 1` prints `undefined` instead of raising.
2168                    // Declaring it at instantiation time (rather than at the
2169                    // initialiser) is also what makes it non-configurable: the store
2170                    // then lands on an existing property instead of creating one.
2171                    self.declare_var_global(&closure_var.name);
2172                    // The cell is a placeholder that nothing indexes; it cannot be
2173                    // omitted because the slot has to hold something.
2174                    self.new_cell(Value::Undefined)
2175                }
2176                _ => {
2177                    // An undeclared global is read by name; the cell is a
2178                    // placeholder that nothing indexes.
2179                    self.new_cell(Value::Undefined)
2180                }
2181            };
2182            cells.push(cell);
2183        }
2184        Gc::new(
2185            self.heap,
2186            ClosureEnv {
2187                cells,
2188                eval_scope: None,
2189                local_vars: None,
2190                local_phase: 1,
2191            },
2192        )
2193    }
2194
2195    /// Push a frame and run until it returns.
2196    pub(crate) fn execute(
2197        &mut self,
2198        code: Gc<CompiledCode>,
2199        env: Gc<ClosureEnv>,
2200        this: Value,
2201        args: Vec<Value>,
2202        callee: Value,
2203    ) -> JsResult<Value> {
2204        let depth = self.frames.len();
2205        self.push_frame(code, env, this, args, callee)?;
2206        loop {
2207            match self.step() {
2208                Ok(Step::Continue) => {}
2209                Ok(Step::Return(value)) => {
2210                    self.frames.pop();
2211                    // A frame that ended in a `tail_call` hands its value straight to
2212                    // its caller: nothing after the call can run, so every frame above
2213                    // the callee unwinds with the same value. See [`Frame::tail`] —
2214                    // the reference does not reuse frames either, so recursion depth
2215                    // and the stack-overflow limit behave the same way.
2216                    while self.frames.len() > depth && self.frame().tail {
2217                        self.frames.pop();
2218                    }
2219                    if self.frames.len() == depth {
2220                        return Ok(value);
2221                    }
2222                    // The caller resumes with the value on its stack.
2223                    self.frames
2224                        .last_mut()
2225                        .expect("a caller is live")
2226                        .stack
2227                        .push(value);
2228                }
2229                Err(Signal::Throw(value)) => {
2230                    // A handler lives on the stack of the frame that is throwing —
2231                    // `catch` pushed it there — so this frame gets the first chance
2232                    // to catch before it is popped.
2233                    let value = value;
2234                    loop {
2235                        if self.frames.len() <= depth {
2236                            return Err(Signal::Throw(value));
2237                        }
2238                        if self.catch_here(value.clone()).is_some() {
2239                            break;
2240                        }
2241                        self.frames.pop();
2242                    }
2243                }
2244                // A `yield` in a frame that `execute` is running directly means a
2245                // generator body was entered as an ordinary call, which only happens if
2246                // the generator check in `call_or_push` was bypassed.
2247                Ok(Step::Suspend(_)) => {
2248                    return Err(Signal::Throw(self.make_error(
2249                        "InternalError",
2250                        "a generator body ran as an ordinary call",
2251                    )));
2252                }
2253                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2254            }
2255        }
2256    }
2257
2258    /// Install a handler for `value` if this frame has one, resuming at it.
2259    ///
2260    /// The scan is the reference's: walk the frame's stack downwards looking for the
2261    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
2262    /// `0` is an enumerator marker rather than a handler — it exists so that a
2263    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
2264    /// here and the unwinding continues.
2265    fn catch_here(&mut self, value: Value) -> Option<()> {
2266        let frame = self.frames.last_mut()?;
2267        while let Some(top) = frame.stack.pop() {
2268            if let Value::CatchOffset(offset) = top {
2269                if offset == 0 {
2270                    continue;
2271                }
2272                frame.stack.push(value);
2273                frame.pc = offset as usize;
2274                return Some(());
2275            }
2276        }
2277        None
2278    }
2279
2280    fn push_frame(
2281        &mut self,
2282        code: Gc<CompiledCode>,
2283        env: Gc<ClosureEnv>,
2284        this: Value,
2285        mut args: Vec<Value>,
2286        callee: Value,
2287    ) -> JsResult<()> {
2288        if self.frames.len() >= self.max_frames {
2289            return Err(Signal::Throw(
2290                self.string("Maximum call stack size exceeded"),
2291            ));
2292        }
2293        let arg_count = code.code.args.len();
2294        // How many were actually passed, which `arguments.length` reports and
2295        // `assert(x)` depends on: a call with one argument must not look like a call
2296        // with one argument and an explicit `undefined`.
2297        let passed = args.len();
2298        // Missing arguments are `undefined` in their slots; extra ones are dropped
2299        // from the slots but still reachable through `arguments`.
2300        let mut passed_values = args.clone();
2301        args.resize(arg_count, Value::Undefined);
2302        args.truncate(arg_count);
2303        let cell_count = code.code.var_ref_count as usize;
2304        let mut cells = Vec::with_capacity(cell_count);
2305        for _ in 0..cell_count {
2306            cells.push(self.new_cell(Value::Undefined));
2307        }
2308        let locals = vec![Value::Undefined; code.code.vars.len()];
2309        // A captured argument lives in its cell, not in the argument slot, so the
2310        // incoming value has to be moved there before the body runs.
2311        for (slot, cell) in code.arg_cell.iter().enumerate() {
2312            if *cell >= 0
2313                && let Some(value) = args.get(slot).cloned()
2314            {
2315                cells[*cell as usize].set(value);
2316            }
2317        }
2318        // Sloppy mode substitutes the global object for a missing receiver and boxes a
2319        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
2320        // reports `object`. Strict mode passes the value through untouched.
2321        let this = if code.code.strict {
2322            this
2323        } else if this.is_nullish() {
2324            Value::Object(self.realm.global.clone())
2325        } else if matches!(this, Value::Object(_)) {
2326            this
2327        } else {
2328            match crate::builtins::this_object(self, &this) {
2329                Ok(boxed) => Value::Object(boxed),
2330                Err(_) => this,
2331            }
2332        };
2333        self.frames.push(Frame {
2334            code,
2335            env,
2336            this,
2337            args,
2338            passed: passed_values.drain(..passed).collect(),
2339            locals,
2340            cells,
2341            local_vars: None,
2342            stack: Vec::with_capacity(16),
2343            pc: 0,
2344            at: 0,
2345            callee,
2346            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
2347            tail: false,
2348        });
2349        Ok(())
2350    }
2351
2352    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
2353    ///
2354    /// Only names the eval created are here: a name the frame already declared statically
2355    /// is written through to its own slot instead, so this cannot shadow a real local.
2356    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
2357        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
2358        let (local_vars, phase) = self.visible_local_vars()?;
2359        if !local_vars.contains(name) {
2360            return None;
2361        }
2362        local_vars.get(name, phase)
2363    }
2364
2365    /// The variables a direct `eval` declared, as the code currently running sees them.
2366    ///
2367    /// Inside an eval that is the *caller's* set — the eval's own variable environment
2368    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
2369    /// else it is the current frame's, falling back to the frame the closure was created
2370    /// in.
2371    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
2372        // While an `eval` runs, its own frame is on top but its variable environment is
2373        // the *caller's* — so the caller is what the lookup has to start from.
2374        let (index, phase) = match self.eval_caller.flatten() {
2375            Some(caller) => (
2376                caller,
2377                if self.in_parameter_list_at(caller) {
2378                    0
2379                } else {
2380                    1
2381                },
2382            ),
2383            None => (
2384                self.frames.len().checked_sub(1)?,
2385                if self.in_parameter_list() { 0 } else { 1 },
2386            ),
2387        };
2388        let frame = self.frames.get(index)?;
2389        // The frame's own variables, or — for an arrow, which has no variable environment
2390        // of its own — the one it was created in, which `ClosureEnv` carries.
2391        if let Some(local_vars) = frame.local_vars.clone() {
2392            return Some((local_vars, phase));
2393        }
2394        frame
2395            .env
2396            .local_vars
2397            .clone()
2398            .map(|local_vars| (local_vars, frame.env.local_phase))
2399    }
2400
2401    /// Whether the innermost frame is still evaluating its parameter list.
2402    ///
2403    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
2404    /// and a closure created there may only see that much of [`LocalVars`].
2405    fn in_parameter_list(&self) -> bool {
2406        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
2407    }
2408
2409    /// [`Interp::in_parameter_list`] for a specific frame.
2410    fn in_parameter_list_at(&self, frame: usize) -> bool {
2411        let Some(frame) = self.frames.get(frame) else {
2412            return false;
2413        };
2414        let code = &frame.code.code;
2415        if !code.has_parameter_expressions {
2416            return false;
2417        }
2418        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
2419        // function as its body and let a direct `eval` act accordingly.
2420        if code.body_start == (0, 0) {
2421            return false;
2422        }
2423        match code.position_at(frame.at as u32) {
2424            Some(position) => position < code.body_start,
2425            None => false,
2426        }
2427    }
2428
2429    fn frame(&self) -> &Frame {
2430        self.frames.last().expect("a frame is live")
2431    }
2432
2433    fn frame_mut(&mut self) -> &mut Frame {
2434        self.frames.last_mut().expect("a frame is live")
2435    }
2436
2437    // -- slot access --------------------------------------------------------
2438
2439    fn read_slot(&self, cell: i32, value: &Value) -> Value {
2440        match cell {
2441            -1 => value.clone(),
2442            index => self
2443                .frame()
2444                .cells
2445                .get(index as usize)
2446                .expect("a cell index in range")
2447                .get(),
2448        }
2449    }
2450
2451    fn get_arg(&self, slot: usize) -> Value {
2452        let frame = self.frame();
2453        let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
2454        let value = frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
2455        self.read_slot(cell, &value)
2456    }
2457
2458    fn put_arg(&mut self, slot: usize, value: Value) {
2459        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
2460        if cell == -1 {
2461            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
2462                *slot = value;
2463            }
2464        } else {
2465            self.frame().cells[cell as usize].set(value);
2466        }
2467    }
2468
2469    fn get_loc(&self, slot: usize) -> Value {
2470        let frame = self.frame();
2471        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
2472        let value = frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
2473        self.read_slot(cell, &value)
2474    }
2475
2476    fn put_loc(&mut self, slot: usize, value: Value) {
2477        let cell = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
2478        if cell == -1 {
2479            if let Some(slot) = self.frame_mut().locals.get_mut(slot) {
2480                *slot = value;
2481            }
2482        } else {
2483            self.frame().cells[cell as usize].set(value);
2484        }
2485    }
2486
2487    // -- globals ------------------------------------------------------------
2488
2489    /// The name a global-slot operand refers to.
2490    fn global_name(&self, slot: usize) -> String {
2491        self.frame()
2492            .code
2493            .code
2494            .closure_vars
2495            .get(slot)
2496            .map(|c| c.name.clone())
2497            .unwrap_or_default()
2498    }
2499
2500    /// The facts about a global binding that decide where it lives.
2501    ///
2502    /// A script's globals split in two, and the split is observable: `var` and
2503    /// function declarations become properties of the global object (`globalThis.v`
2504    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
2505    /// declarations live in the global *lexical* environment and are invisible there
2506    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
2507    /// `is_lexical` flag means the answer is already in the bytecode.
2508    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
2509        let name = self.global_name(slot);
2510        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
2511        // while forwarding a reference through a nested function is built with the
2512        // flags cleared, so `const c` would look like an ordinary `var` from inside a
2513        // closure. Presence in the realm's lexical table is the same fact, recorded
2514        // once, and every slot sees it.
2515        let lexical = self.realm.globals.contains_key(&name);
2516        let is_const = self.realm.lexical_consts.contains(&name);
2517        (name, lexical, is_const)
2518    }
2519
2520    /// The value of `name` in the innermost active `with` object, if any.
2521    ///
2522    /// The active objects are the [`VarKind::With`] locals of every frame still running,
2523    /// innermost frame first and innermost block first within one. Walking frames rather
2524    /// than keeping a separate stack is what makes a closure called from inside a `with`
2525    /// see it, and what keeps the object alive only as long as the block is.
2526    /// The innermost active `with` object that has `name`, if any.
2527    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
2528        let objects = self.eval_with.clone().unwrap_or_default();
2529        for object in objects {
2530            let key = self.string(name.to_string());
2531            if self
2532                .has_property(&key, &Value::Object(object.clone()))
2533                .ok()?
2534            {
2535                return Some(object);
2536            }
2537        }
2538        None
2539    }
2540
2541    /// Every active `with` object, innermost first.
2542    fn with_objects(&self) -> Vec<Gc<JsObject>> {
2543        let mut objects = Vec::new();
2544        for frame in self.frames.iter().rev() {
2545            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
2546                if var.kind != js_compile::VarKind::With {
2547                    continue;
2548                }
2549                // A captured binding lives in its cell and not in the slot list, so the
2550                // cell is consulted first — a closure created inside the block is exactly
2551                // what makes the object captured. Before the store runs the slot still
2552                // holds `undefined`, and a `with` object is always boxed, so a non-object
2553                // entry is simply not in scope yet.
2554                let value = frame
2555                    .code
2556                    .loc_cell
2557                    .get(index)
2558                    .copied()
2559                    .filter(|cell| *cell >= 0)
2560                    .and_then(|cell| frame.cells.get(cell as usize))
2561                    .map(|cell| cell.get())
2562                    .or_else(|| frame.locals.get(index).cloned());
2563                if let Some(Value::Object(object)) = value {
2564                    objects.push(object);
2565                }
2566            }
2567        }
2568        objects
2569    }
2570
2571    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
2572        for object in self.eval_with.clone().unwrap_or_default() {
2573            let key = self.string(name.to_string());
2574            if self.has_property(&key, &Value::Object(object.clone()))? {
2575                return Ok(Some(self.read_field(&Value::Object(object), name)?));
2576            }
2577        }
2578        Ok(None)
2579    }
2580
2581    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
2582        let (name, lexical, _) = self.global_binding(slot);
2583        if name == "arguments"
2584            && let Some(arguments) = &self.eval_arguments
2585        {
2586            return Ok(arguments.clone());
2587        }
2588        // A `with` block around the *call site* is part of the scope an `eval` sees, so
2589        // the objects live when the eval started are consulted before anything else. The
2590        // snapshot is taken at entry rather than scanning the frames on every read: a
2591        // block that has already finished still leaves its object in the slot, and a
2592        // bytecode read outside the block must not see it.
2593        if let Some(value) = self.with_lookup(&name)? {
2594            return Ok(value);
2595        }
2596        // A variable a direct `eval` declared shadows everything the compiler resolved,
2597        // including an enclosing function's binding: the eval put it in the caller's own
2598        // variable environment, which is nearer than any captured scope.
2599        if let Some((local_vars, phase)) = self.visible_local_vars()
2600            && let Some(cell) = local_vars.get(&name, phase)
2601        {
2602            return Ok(cell.get());
2603        }
2604        // The frame that called `eval` is the innermost scope the eval'd code sees, so
2605        // its local `a` wins over a global `a`.
2606        if let Some(value) = self.eval_binding_value(&name) {
2607            return Ok(value);
2608        }
2609        // A closure created by an `eval` resolves its free names against the bindings
2610        // that eval saw, even after the eval (and its frames) are gone.
2611        if let Some(cell) = self
2612            .frame()
2613            .env
2614            .eval_scope
2615            .as_ref()
2616            .and_then(|scope| scope.get(&name))
2617        {
2618            let value = cell.get();
2619            if matches!(value, Value::Uninitialized) {
2620                return Err(self.throw_reference(&name));
2621            }
2622            return Ok(value);
2623        }
2624        // A binding declared by the strict `eval` currently running shadows anything
2625        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
2626        if let Some(scope) = &self.eval_scope
2627            && let Some(value) = scope.get(&name)
2628        {
2629            return Ok(value.clone());
2630        }
2631        if lexical {
2632            // A lexical global is a binding in a side table, so the dead zone is
2633            // visible and it is nowhere on the global object.
2634            if let Some(cell) = self.realm.globals.get(&name) {
2635                let value = cell.get();
2636                if matches!(value, Value::Uninitialized) {
2637                    return Err(self.throw_reference(&name));
2638                }
2639                return Ok(value);
2640            }
2641            return Err(self.throw_reference(&name));
2642        }
2643        // A `var` global is an ordinary property, so the prototype chain and the
2644        // global object's own builtins are all reachable through it.
2645        match self.get_property(&self.realm.global.clone(), &name)? {
2646            Some(value) => Ok(value),
2647            None => Err(self.throw_reference(&name)),
2648        }
2649    }
2650
2651    /// Store to a global binding.
2652    ///
2653    /// Returns a signal when the store is refused: a `const` global may only be
2654    /// written by its initialiser, and a non-configurable `var` global may not be
2655    /// deleted but is always writable.
2656    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
2657        let (name, lexical, is_const) = self.global_binding(slot);
2658
2659        // An assignment inside a `with` writes through to the object that supplies the
2660        // name, which for an `eval` means consulting the same chain `get_global` does.
2661        if let Some(owner) = self.with_owner(&name) {
2662            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
2663            return Ok(());
2664        }
2665        // A variable the running eval *declared* takes the write before any caller
2666        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
2667        // environment even when an enclosing function has a `var c` of its own.
2668        if self.eval_caller.flatten().is_some()
2669            && let Some((local_vars, phase)) = self.visible_local_vars()
2670            && local_vars.contains(&name)
2671            && let Some(cell) = local_vars.get(&name, phase)
2672        {
2673            cell.set(value);
2674            return Ok(());
2675        }
2676        // A binding of the frame that called `eval` takes the write, which is what
2677        // makes `f("a = 3")` change the caller's `a`.
2678        if self.set_eval_binding(&name, &value)? {
2679            return Ok(());
2680        }
2681        // A closure that outlived its `eval` writes through to the same cell it reads.
2682        if let Some(cell) = self
2683            .frame()
2684            .env
2685            .eval_scope
2686            .as_ref()
2687            .and_then(|scope| scope.get(&name))
2688            .cloned()
2689        {
2690            cell.set(value);
2691            return Ok(());
2692        }
2693        // Inside a strict `eval`, a name it declared itself is stored there. An
2694        // *assignment* to a name nobody declared is not a declaration, so it falls
2695        // through: strict mode raises `ReferenceError` for it, which is what
2696        // `eval("1 + (@not_def = 1)")` has to do.
2697        if let Some(scope) = self.eval_scope.as_mut()
2698            && scope.contains_key(&name)
2699        {
2700            scope.insert(name, value);
2701            return Ok(());
2702        }
2703        if lexical {
2704            if let Some(cell) = self.realm.globals.get(&name).cloned() {
2705                if is_const && !matches!(cell.get(), Value::Uninitialized) {
2706                    return Err(self.read_only_global(&name));
2707                }
2708                cell.set(value);
2709                return Ok(());
2710            }
2711            // Writing an undeclared lexical global is a `ReferenceError` in strict
2712            // mode and a silent global creation otherwise; creating the cell here
2713            // keeps both paths from losing the value.
2714            let cell = self.new_cell(value);
2715            self.realm.globals.insert(name, cell);
2716            return Ok(());
2717        }
2718        // A variable a direct `eval` declared in this call shadows the global object, even
2719        // when the global already has a property of that name — `var c = "global"` at the
2720        // top level must not capture `eval("var c = 1")` inside a function.
2721        if let Some((local_vars, phase)) = self.visible_local_vars()
2722            && local_vars.contains(&name)
2723            && let Some(cell) = local_vars.get(&name, phase)
2724        {
2725            cell.set(value);
2726            return Ok(());
2727        }
2728        let global = self.realm.global.clone();
2729        match global.own_property(&name) {
2730            // A `var` global is writable, so the store goes straight through — but
2731            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
2732            // store (a non-writable or accessor-without-setter global) is a silent
2733            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
2734            // split every other assignment has.
2735            Some(_) => {
2736                let on_failure = if self.current_strict() {
2737                    DeleteFailure::Throw
2738                } else {
2739                    DeleteFailure::Ignore
2740                };
2741                self.set_property_with(&global, &name, value, on_failure)
2742            }
2743            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
2744            // declaration creates a *configurable* property, which is what makes it
2745            // deletable and is the one way a global differs from a declared `var`.
2746            // In strict mode the same store is a `ReferenceError` instead: that is the
2747            // whole point of strict mode, and creating the global silently meant
2748            // `"use strict"; x = 1` looked like it worked.
2749            None => {
2750                if self.current_strict() {
2751                    return Err(self.throw_reference(&name));
2752                }
2753                // A direct eval declares here rather than on the global object: its
2754                // `var`s belong to the caller's variable environment. `declare_eval_local`
2755                // also covers a plain assignment to a variable an earlier eval made.
2756                if let Some(cell) = self.declare_eval_local(&name) {
2757                    cell.set(value);
2758                    return Ok(());
2759                }
2760                global.define_data(&name, value);
2761                Ok(())
2762            }
2763        }
2764    }
2765
2766    /// The value of a binding of the frame that called `eval`, if there is one.
2767    fn eval_binding_value(&self, name: &str) -> Option<Value> {
2768        let binding = self
2769            .eval_bindings
2770            .iter()
2771            .find(|binding| binding.name == name)?;
2772        let owner = self.frames.get(binding.frame)?;
2773        let (slot, index) = (binding.slot, binding.index);
2774        Some(match slot {
2775            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
2776                cell if cell >= 0 => owner
2777                    .cells
2778                    .get(cell as usize)
2779                    .map(|cell| cell.get())
2780                    .unwrap_or(Value::Undefined),
2781                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
2782            },
2783            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
2784                cell if cell >= 0 => owner
2785                    .cells
2786                    .get(cell as usize)
2787                    .map(|cell| cell.get())
2788                    .unwrap_or(Value::Undefined),
2789                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
2790            },
2791        })
2792    }
2793
2794    /// Write to a binding of the frame that called `eval`.
2795    ///
2796    /// `Ok(false)` means no binding matched and the caller should keep looking. A
2797    /// matched binding can still refuse the store, which is why this is fallible: a
2798    /// `const` is read-only everywhere, and a named function expression's own name is
2799    /// read-only in strict mode.
2800    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
2801        let Some(binding) = self
2802            .eval_bindings
2803            .iter()
2804            .find(|binding| binding.name == name)
2805        else {
2806            return Ok(false);
2807        };
2808        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
2809        let strict = self.current_strict();
2810        let Some(owner) = self.frames.get_mut(frame) else {
2811            return Ok(false);
2812        };
2813        match slot {
2814            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
2815                cell if cell >= 0 => {
2816                    if let Some(cell) = owner.cells.get(cell as usize) {
2817                        cell.set(value.clone());
2818                    }
2819                }
2820                _ => {
2821                    if let Some(slot) = owner.args.get_mut(index) {
2822                        *slot = value.clone();
2823                    }
2824                }
2825            },
2826            EvalSlot::Local => {
2827                let declared = owner.code.code.vars.get(index);
2828                // A `const` is read-only even through `eval`. The realm records this for
2829                // globals (see `lexical_consts`), but a local's `const`-ness is only in
2830                // the bytecode, so this is where it has to be enforced.
2831                if declared.is_some_and(|var| var.is_const) {
2832                    return Err(self.read_only_local(name));
2833                }
2834                // The name of a named function expression is read-only too, but only
2835                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
2836                // such a name is ignored, the same as a direct store would be.
2837                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
2838                    return if strict {
2839                        Err(self.read_only_local(name))
2840                    } else {
2841                        Ok(true)
2842                    };
2843                }
2844                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
2845                    cell if cell >= 0 => {
2846                        if let Some(cell) = owner.cells.get(cell as usize) {
2847                            cell.set(value.clone());
2848                        }
2849                    }
2850                    _ => {
2851                        if let Some(slot) = owner.locals.get_mut(index) {
2852                            *slot = value.clone();
2853                        }
2854                    }
2855                }
2856            }
2857        }
2858        Ok(true)
2859    }
2860
2861    /// The `TypeError` an assignment to a read-only binding raises.
2862    fn read_only_local(&self, name: &str) -> Signal {
2863        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
2864    }
2865
2866    /// Declare `name` as a variable of the frame that called the running `eval`.
2867    ///
2868    /// `None` when there is no direct eval in progress, or it was called from the top
2869    /// level — then the caller's variable environment *is* the global one and the
2870    /// existing path is right.
2871    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
2872        let caller = self.eval_caller.flatten()?;
2873        // The bottom frame is the top-level script, whose variable environment *is* the
2874        // global one — so `eval("var x = 1")` at the top level still creates a global.
2875        if caller == 0 {
2876            return None;
2877        }
2878        // A name the eval's *own* variable environment already binds is not a new
2879        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
2880        // `arguments`, and creating a second binding would leave the first — the one
2881        // closures read — untouched. A binding of an *outer* frame does not count: a
2882        // declaration shadows it rather than writing through.
2883        if self
2884            .eval_bindings
2885            .iter()
2886            .any(|binding| binding.name == name && binding.frame == caller)
2887        {
2888            return None;
2889        }
2890        let phase = if self.in_parameter_list_at(caller) {
2891            0
2892        } else {
2893            1
2894        };
2895        self.frame_local_vars(caller)?;
2896        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
2897        if let Some(cell) = local_vars.get(name, 1) {
2898            return Some(cell);
2899        }
2900        let cell = self.new_cell(Value::Undefined);
2901        Some(local_vars.declare(name, phase, cell))
2902    }
2903
2904    /// Make sure `frame` has a `LocalVars`, creating it on demand.
2905    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
2906        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
2907            return Some(local_vars.clone());
2908        }
2909        let local_vars = Gc::new(self.heap, LocalVars::new());
2910        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
2911        Some(local_vars)
2912    }
2913
2914    /// Whether the realm already has a binding for `name`, lexically or as an *own*
2915    /// property of the global object. Used to decide whether a store inside an
2916    /// `eval` writes through to the realm or declares a binding of its own.
2917    ///
2918    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
2919    /// write to `Object.prototype.toString`, and must not shadow it either.
2920    fn global_knows(&mut self, name: &str) -> bool {
2921        if self.realm.globals.contains_key(name) {
2922            return true;
2923        }
2924        self.realm.global.own_property(name).is_some()
2925    }
2926
2927    /// Whether the code currently running is strict.
2928    ///
2929    /// Read off the frame's function, which is where the parser's answer ended up; a
2930    /// native function never runs strict-only checks, and there is no frame at all
2931    /// before the first script.
2932    pub fn current_strict(&self) -> bool {
2933        self.frames
2934            .last()
2935            .is_some_and(|frame| frame.code.code.strict)
2936    }
2937
2938    /// Initialise a declared global, which is what ends its dead zone.
2939    ///
2940    /// A `var` global becomes a property of the global object: writable, so a later
2941    /// assignment goes through, and non-configurable, so `delete` refuses.
2942    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
2943        let (name, lexical, _) = self.global_binding(slot);
2944        // A `var` declared by the strict `eval` currently running belongs to the
2945        // eval's scope, not to the global object: `eval("var v = 1")` must not make
2946        // `typeof v` answer `"number"` afterwards. A name the realm already has is
2947        // initialised in place, which is what a re-declaration inside eval does.
2948        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
2949            self.eval_scope
2950                .as_mut()
2951                .expect("checked above")
2952                .insert(name, value);
2953            return Ok(());
2954        }
2955        if let Some(scope) = self.eval_scope.as_mut()
2956            && scope.contains_key(&name)
2957        {
2958            scope.insert(name, value);
2959            return Ok(());
2960        }
2961        if lexical {
2962            // The cell exists (created at declaration time) holding the dead-zone
2963            // marker; storing the value is what makes the binding readable.
2964            if let Some(cell) = self.realm.globals.get(&name).cloned() {
2965                cell.set(value);
2966                return Ok(());
2967            }
2968            let cell = self.new_cell(value);
2969            self.realm.globals.insert(name, cell);
2970            return Ok(());
2971        }
2972        let global = self.realm.global.clone();
2973        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
2974        // to answer `false` and leave the binding in place. `with_attributes` ties
2975        // `configurable` to `writable`, so the property is built field by field.
2976        global.define(
2977            &name,
2978            Property {
2979                value: Some(value),
2980                writable: true,
2981                enumerable: true,
2982                configurable: false,
2983                ..Property::default()
2984            },
2985        );
2986        Ok(())
2987    }
2988
2989    /// The `TypeError` a store to a `const` global raises.
2990    fn read_only_global(&self, name: &str) -> Signal {
2991        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
2992    }
2993
2994    // -- properties ---------------------------------------------------------
2995
2996    /// Read `object[key]`, following the prototype chain.
2997    ///
2998    /// An inherited accessor runs with the *receiver* as `this`, which is why the
2999    /// lookup returns the owner rather than just the value.
3000    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
3001        self.get_property_key(object, &PropertyKey::from(key))
3002    }
3003
3004    /// [`Interp::get_property`] with a key that may be a symbol.
3005    pub fn get_property_key(
3006        &mut self,
3007        object: &Gc<JsObject>,
3008        key: &PropertyKey,
3009    ) -> JsResult<Option<Value>> {
3010        self.get_property_key_for(object, None, key)
3011    }
3012
3013    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
3014    ///
3015    /// The receiver matters when the property is found on a *prototype*: a getter has to
3016    /// see the object the read started from. For a primitive that is the primitive
3017    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
3018    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
3019    /// the owner.
3020    pub fn get_property_key_for(
3021        &mut self,
3022        object: &Gc<JsObject>,
3023        receiver: Option<&Value>,
3024        key: &PropertyKey,
3025    ) -> JsResult<Option<Value>> {
3026        // A proxy answers for itself, before any of the shortcuts below: `new
3027        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
3028        // have.
3029        if object.proxy_state().is_some() {
3030            let receiver = receiver
3031                .cloned()
3032                .unwrap_or_else(|| Value::Object(object.clone()));
3033            return self.proxy_get(object, &receiver, key);
3034        }
3035        // The element-vector and `length` shortcuts are string-only: an array index
3036        // has no symbol spelling.
3037        if let Some(text) = key.as_str() {
3038            if let Some(value) = self.own_element(object, text) {
3039                return Ok(Some(value));
3040            }
3041            // `length` is not stored as a property: an array's length is its element
3042            // count, and keeping one copy of it is what makes `push`/`pop` and
3043            // `a.length = n` agree.
3044            if let Some(length) = object.array_length()
3045                && text == "length"
3046            {
3047                // Not `Value::Int(length as i32)`: see [`length_value`].
3048                return Ok(Some(crate::object::length_value(length)));
3049            }
3050        }
3051        match lookup_key(object, key) {
3052            Some((_, property)) => {
3053                if property.is_accessor() {
3054                    match &property.getter {
3055                        Some(getter) if !matches!(getter, Value::Undefined) => {
3056                            let receiver = receiver
3057                                .cloned()
3058                                .unwrap_or_else(|| Value::Object(object.clone()));
3059                            self.call_value(getter.clone(), receiver, Vec::new())
3060                                .map(Some)
3061                        }
3062                        // An accessor with no getter reads as `undefined`.
3063                        _ => Ok(Some(Value::Undefined)),
3064                    }
3065                } else {
3066                    Ok(property.value)
3067                }
3068            }
3069            None => Ok(None),
3070        }
3071    }
3072
3073    /// `super.key` — start the search at `proto`, but report to `receiver`.
3074    ///
3075    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
3076    /// found on the prototype of a class has to see the *instance* as `this`, and a
3077    /// plain property read off `proto` would lose that.
3078    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
3079        let start = self.require_object(proto)?;
3080        let key = self.propkey(key);
3081        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
3082        if matches!(proto, Value::Null) {
3083            return Ok(Value::Undefined);
3084        }
3085        match lookup_key(&start, &key) {
3086            Some((_, property)) if property.is_accessor() => match &property.getter {
3087                Some(getter) if !matches!(getter, Value::Undefined) => {
3088                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
3089                }
3090                _ => Ok(Value::Undefined),
3091            },
3092            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
3093            None => Ok(Value::Undefined),
3094        }
3095    }
3096
3097    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
3098    ///
3099    /// A setter found on the prototype runs with `receiver` as `this`; a data property
3100    /// is shadowed by a new own property on the receiver, the same rule an ordinary
3101    /// assignment follows.
3102    fn super_write(
3103        &mut self,
3104        receiver: &Value,
3105        proto: &Value,
3106        key: &Value,
3107        value: Value,
3108    ) -> JsResult<()> {
3109        let target = self.require_object(receiver)?;
3110        let key = self.propkey(key);
3111        if !matches!(proto, Value::Null)
3112            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
3113        {
3114            if property.is_accessor() {
3115                if let Some(setter) = &property.setter
3116                    && !matches!(setter, Value::Undefined)
3117                {
3118                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
3119                }
3120                return Ok(());
3121            }
3122            // A data property on the prototype is writable or not; reading `owner` at
3123            // all is only for the attribute check.
3124            if !property.writable {
3125                return Err(self.type_error(format!("'{key}' is read-only")));
3126            }
3127            let _ = owner;
3128        }
3129        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
3130    }
3131
3132    /// The object a `super` operation needs, or the `TypeError` the spec raises.
3133    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
3134        match value.as_object() {
3135            Some(object) => Ok(object.clone()),
3136            None => Err(Signal::Throw(
3137                self.make_error("TypeError", "value is not an object"),
3138            )),
3139        }
3140    }
3141
3142    /// Build the class object `define_class` produces.
3143    ///
3144    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
3145    /// whose prototype property is a fresh object inheriting from the parent's
3146    /// prototype, and whose own prototype is the parent constructor — which is what makes
3147    /// a static method inherited too.
3148    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
3149        let ctor = self.pop();
3150        let parent = self.pop();
3151        let Value::Object(function) = &ctor else {
3152            return Err(Signal::Throw(
3153                self.make_error("TypeError", "class constructor must be a function"),
3154            ));
3155        };
3156        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
3157        // but gives the instances no prototype at all.
3158        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
3159            match &parent {
3160                Value::Null => (Some(self.realm.function_proto.clone()), None),
3161                Value::Object(parent_class) => {
3162                    if !parent_class.is_callable() {
3163                        return Err(Signal::Throw(
3164                            self.make_error("TypeError", "parent class must be constructor"),
3165                        ));
3166                    }
3167                    let proto = self.get_property(parent_class, "prototype")?;
3168                    match proto {
3169                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
3170                        Some(Value::Null) => (Some(parent_class.clone()), None),
3171                        _ => {
3172                            return Err(Signal::Throw(self.make_error(
3173                                "TypeError",
3174                                "parent prototype must be an object or null",
3175                            )));
3176                        }
3177                    }
3178                }
3179                _ => {
3180                    return Err(Signal::Throw(
3181                        self.make_error("TypeError", "parent class must be constructor"),
3182                    ));
3183                }
3184            }
3185        } else {
3186            (
3187                Some(self.realm.function_proto.clone()),
3188                Some(self.realm.object_proto.clone()),
3189            )
3190        };
3191        let proto = self.new_object(parent_proto);
3192        function.set_proto(parent_ctor);
3193        // A class is not callable without `new`, and its `prototype` is not writable —
3194        // both follow from being a class and are what `class A {}; A()` throws on.
3195        function.set_class_constructor(true);
3196        function.set_home_object(None);
3197        self.set_function_name(&ctor, name);
3198        self.define_class_properties(function, &ctor, &proto)?;
3199        Ok((ctor, proto))
3200    }
3201
3202    /// Give the constructor its `prototype` and `length`, and the prototype its
3203    /// `constructor` back-pointer.
3204    fn define_class_properties(
3205        &mut self,
3206        function: &Gc<JsObject>,
3207        ctor: &Value,
3208        proto: &Gc<JsObject>,
3209    ) -> JsResult<()> {
3210        proto.define(
3211            "constructor",
3212            Property::with_attributes(ctor.clone(), true, false),
3213        );
3214        function.define(
3215            "prototype",
3216            Property::prototype_of(Value::Object(proto.clone()), false),
3217        );
3218        if let Some((code, _)) = bytecode_of(function) {
3219            let length = code.code.defined_args;
3220            function.define(
3221                "length",
3222                Property::name_or_length(Value::Int(length as i32)),
3223            );
3224        }
3225        Ok(())
3226    }
3227
3228    /// The own array element `key` names, if this object has one.
3229    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
3230        let index = array_index(key)?;
3231        // A typed array's elements live in its buffer, not in a property list: reading one
3232        // goes through the view's element type so a bounds check and a detached buffer are
3233        // both handled there.
3234        if object.typed_array_parts().is_some() {
3235            return object.typed_array_element(index as usize);
3236        }
3237        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
3238        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
3239        // search early, which is why `Array.prototype[1] = 9` could not be seen through
3240        // `[1,,3][1]`.
3241        match object.array_get(index as usize) {
3242            Some(Value::Hole) | None => None,
3243            other => other,
3244        }
3245    }
3246
3247    /// Store `object[key] = value`, honouring setters and inherited properties.
3248    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
3249        self.set_property_with(object, key, value, DeleteFailure::Throw)
3250    }
3251
3252    /// Store a property, choosing what to do when the object refuses.
3253    ///
3254    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
3255    /// mode, which is the one place assignment differs by mode. Native code (the array
3256    /// methods, `JSON`) always asks for the throw.
3257    pub fn set_property_with(
3258        &mut self,
3259        object: &Gc<JsObject>,
3260        key: &str,
3261        value: Value,
3262        on_failure: DeleteFailure,
3263    ) -> JsResult<()> {
3264        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
3265    }
3266
3267    /// [`Interp::set_property_with`] with a key that may be a symbol.
3268    pub fn set_property_with_key(
3269        &mut self,
3270        object: &Gc<JsObject>,
3271        key: &PropertyKey,
3272        value: Value,
3273        on_failure: DeleteFailure,
3274    ) -> JsResult<()> {
3275        // A proxy's `set` trap decides, and its `false` means the same thing an
3276        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
3277        if object.proxy_state().is_some() {
3278            let receiver = Value::Object(object.clone());
3279            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
3280                return match (accepted, on_failure) {
3281                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
3282                    (false, DeleteFailure::Throw) => {
3283                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
3284                    }
3285                };
3286            }
3287        }
3288        // The element and `length` shortcuts only exist for string keys: an array
3289        // index has no symbol spelling, and a symbol named `length` is an ordinary
3290        // property.
3291        let text = key.as_str();
3292        // A typed array's elements are a window onto its buffer: the store has to go
3293        // through the view's element type so the value is wrapped (or clamped) and so an
3294        // out-of-range or detached write is a silent no-op, as the spec says.
3295        if let Some(text) = text
3296            && let Some(index) = array_index(text)
3297            && object.typed_array_parts().is_some()
3298        {
3299            // A BigInt view refuses a Number; the spec makes that a `TypeError` rather
3300            // than a silent skip, in strict mode and sloppy alike.
3301            if let Some(Err(reason)) = object.typed_array_set(index as usize, value) {
3302                return Err(self.type_error(reason));
3303            }
3304            return Ok(());
3305        }
3306        if let Some(text) = text
3307            && let Some(index) = array_index(text)
3308            && object.is_array()
3309        {
3310            // An accessor defined on an index lives in the property table while the
3311            // element slot is a hole, so the store has to go through the property first.
3312            // Writing the vector directly skipped the setter entirely.
3313            if let Some(existing) = object.own_property_key(key) {
3314                if existing.is_accessor() {
3315                    return match existing.setter.clone() {
3316                        Some(setter) if !matches!(setter, Value::Undefined) => {
3317                            let receiver = Value::Object(object.clone());
3318                            self.call_value(setter, receiver, vec![value]).map(|_| ())
3319                        }
3320                        _ => match on_failure {
3321                            DeleteFailure::Throw => Err(self.type_error(format!(
3322                                "cannot set property '{text}', it has only a getter"
3323                            ))),
3324                            DeleteFailure::Ignore => Ok(()),
3325                        },
3326                    };
3327                }
3328                if !existing.writable {
3329                    return match on_failure {
3330                        DeleteFailure::Throw => {
3331                            Err(self.type_error(format!("'{text}' is read-only")))
3332                        }
3333                        DeleteFailure::Ignore => Ok(()),
3334                    };
3335                }
3336            }
3337            {
3338                // Growing the array needs a writable `length`.
3339                if (index as usize) >= object.array_length().unwrap_or(0)
3340                    && !object.length_writable()
3341                {
3342                    return match on_failure {
3343                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
3344                        DeleteFailure::Ignore => Ok(()),
3345                    };
3346                }
3347                // Adding an index past the end makes the array longer, which a
3348                // non-extensible array refuses.
3349                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
3350                    return match on_failure {
3351                        DeleteFailure::Throw => Err(self.type_error(format!(
3352                            "cannot add property '{key}', object is not extensible"
3353                        ))),
3354                        DeleteFailure::Ignore => Ok(()),
3355                    };
3356                }
3357                if object.element_is_locked(index) {
3358                    return match on_failure {
3359                        DeleteFailure::Throw => {
3360                            Err(self.type_error(format!("'{key}' is read-only")))
3361                        }
3362                        DeleteFailure::Ignore => Ok(()),
3363                    };
3364                }
3365                object.array_set(index as usize, value);
3366                return Ok(());
3367            }
3368        }
3369        if text == Some("length") && object.is_array() {
3370            if !object.length_writable() {
3371                return match on_failure {
3372                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
3373                    DeleteFailure::Ignore => Ok(()),
3374                };
3375            }
3376            let length = value.to_number();
3377            if length.is_finite() && length >= 0.0 {
3378                let length = length as usize;
3379                // `a.length = n` with `n` below a non-configurable element cannot
3380                // drop that element, so the whole assignment fails. The spec makes
3381                // this a `TypeError` rather than a silent no-op, in any mode.
3382                if let Some(blocked) = (length..object.array_length().unwrap_or(0))
3383                    .find(|index| object.element_is_undeletable(*index as u32))
3384                {
3385                    // Sloppy mode stops the truncation at the blocking element
3386                    // instead of failing; strict mode raises.
3387                    // Both modes stop at the blocking element; they differ in
3388                    // whether that is reported. The reference truncates *then*
3389                    // throws, so the array is left in the shortened state.
3390                    object.array_truncate(blocked + 1);
3391                    return match on_failure {
3392                        DeleteFailure::Throw => {
3393                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
3394                        }
3395                        DeleteFailure::Ignore => Ok(()),
3396                    };
3397                }
3398                object.array_set_length(length);
3399                return Ok(());
3400            }
3401        }
3402        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
3403        {
3404            return match on_failure {
3405                DeleteFailure::Throw => Err(self.type_error(format!(
3406                    "cannot add property {}, object is not extensible",
3407                    key
3408                ))),
3409                DeleteFailure::Ignore => Ok(()),
3410            };
3411        }
3412        if let Some((owner, property)) = lookup_key(object, key) {
3413            if property.is_accessor() {
3414                if let Some(setter) = &property.setter
3415                    && !matches!(setter, Value::Undefined)
3416                {
3417                    let receiver = Value::Object(object.clone());
3418                    self.call_value(setter.clone(), receiver, vec![value])?;
3419                }
3420                return Ok(());
3421            }
3422            // An inherited *data* property is shadowed by an own property on the
3423            // receiver; a non-writable one is not.
3424            if owner.ptr_eq(object) && !property.writable {
3425                return match on_failure {
3426                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
3427                    DeleteFailure::Ignore => Ok(()),
3428                };
3429            }
3430            // An existing writable own property keeps its attributes: only the value
3431            // moves. Redefining instead would reset them, which is how a
3432            // non-configurable global `var` used to become deletable.
3433            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
3434                return Ok(());
3435            }
3436        }
3437        // No own data property: create one, shadowing whatever the prototype holds.
3438        object.define_data_key(key, value);
3439        Ok(())
3440    }
3441
3442    /// Delete `object[key]`.
3443    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
3444        self.delete_property_key(object, &PropertyKey::from(key))
3445    }
3446
3447    /// [`Interp::delete_property`] with a key that may be a symbol.
3448    pub fn delete_property_key(
3449        &mut self,
3450        object: &Gc<JsObject>,
3451        key: &PropertyKey,
3452    ) -> JsResult<bool> {
3453        // A proxy decides for itself, and may even throw; the invariant checks live in
3454        // `proxy_delete`.
3455        if let Some(answer) = self.proxy_delete(object, key)? {
3456            return Ok(answer);
3457        }
3458        if let Some(index) = key.as_str().and_then(array_index)
3459            && let Some(length) = object.array_length()
3460            && (index as usize) < length
3461        {
3462            // An accessor defined on an index lives in the property table rather than the
3463            // element vector, so both have to be cleared: `delete` after
3464            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
3465            object.delete_key(key);
3466            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
3467            // index stops answering `in`.
3468            if object.element_is_undeletable(index) {
3469                return Ok(false);
3470            }
3471            object.array_set(index as usize, Value::Hole);
3472            return Ok(true);
3473        }
3474        Ok(object.delete_key(key))
3475    }
3476
3477    // -- proxy traps --------------------------------------------------------
3478    //
3479    // A proxy's internal methods all look the same: ask the handler for the trap, call it
3480    // with the target and the operation's own arguments, then check the answer against
3481    // the target. The checks are not decoration — they are what stops a proxy from
3482    // reporting a `non-configurable` property as missing, which would let a frozen object
3483    // be rewritten by standing in front of it.
3484
3485    /// The target and handler of `object`, or `None` when it is not a proxy.
3486    ///
3487    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
3488    /// one has to fail: the slots the traps would have been read from are gone.
3489    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
3490        let Some(state) = object.proxy_state() else {
3491            return Ok(None);
3492        };
3493        let state = state.borrow();
3494        match (&state.target, &state.handler) {
3495            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
3496            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
3497        }
3498    }
3499
3500    /// Call `handler[name]`, or answer `None` when the trap is absent.
3501    ///
3502    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
3503    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
3504    /// back to the target.
3505    fn proxy_trap(
3506        &mut self,
3507        handler: &Value,
3508        name: &str,
3509        args: Vec<Value>,
3510    ) -> JsResult<Option<Value>> {
3511        let Value::Object(table) = handler else {
3512            return Err(self.type_error("proxy handler is not an object"));
3513        };
3514        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
3515        match trap {
3516            Value::Undefined => Ok(None),
3517            Value::Object(function) if function.is_callable() => {
3518                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
3519                Ok(Some(answer))
3520            }
3521            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
3522        }
3523    }
3524
3525    /// Whether `object`'s own property `key` is one the target refuses to lose.
3526    ///
3527    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
3528    /// its value behind the target's back. This goes through
3529    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
3530    /// elements and its `length` — both fixed, both outside the table — are covered.
3531    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3532        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
3533    }
3534
3535    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
3536    fn proxy_get(
3537        &mut self,
3538        object: &Gc<JsObject>,
3539        receiver: &Value,
3540        key: &PropertyKey,
3541    ) -> JsResult<Option<Value>> {
3542        let Some((target, handler)) = self.proxy_parts(object)? else {
3543            return Ok(None);
3544        };
3545        let key_value = self.key_value(key);
3546        let Some(result) = self.proxy_trap(
3547            &handler,
3548            "get",
3549            vec![Value::Object(target.clone()), key_value, receiver.clone()],
3550        )?
3551        else {
3552            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
3553            // inherited getter still sees the proxy.
3554            return Ok(Some(
3555                self.get_property_key_for(&target, Some(receiver), key)?
3556                    .unwrap_or(Value::Undefined),
3557            ));
3558        };
3559        if let Some(fixed) = Self::is_fixed_property(&target, key) {
3560            if fixed.is_accessor() {
3561                // A fixed accessor with no getter must read as `undefined`.
3562                let has_getter = fixed
3563                    .getter
3564                    .as_ref()
3565                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
3566                if !has_getter && !matches!(result, Value::Undefined) {
3567                    return Err(self.type_error(format!(
3568                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
3569                    )));
3570                }
3571            } else if !fixed.writable {
3572                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
3573                if !fixed_value.same_value(&result) {
3574                    return Err(self.type_error(format!(
3575                        "proxy 'get' disagrees with the non-configurable property '{key}'"
3576                    )));
3577                }
3578            }
3579        }
3580        Ok(Some(result))
3581    }
3582
3583    /// `[[Set]]` on a proxy.
3584    ///
3585    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
3586    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
3587    /// read-only store has.
3588    fn proxy_set(
3589        &mut self,
3590        object: &Gc<JsObject>,
3591        key: &PropertyKey,
3592        value: Value,
3593        receiver: &Value,
3594    ) -> JsResult<Option<bool>> {
3595        let Some((target, handler)) = self.proxy_parts(object)? else {
3596            return Ok(None);
3597        };
3598        let key_value = self.key_value(key);
3599        let Some(result) = self.proxy_trap(
3600            &handler,
3601            "set",
3602            vec![
3603                Value::Object(target.clone()),
3604                key_value,
3605                value.clone(),
3606                receiver.clone(),
3607            ],
3608        )?
3609        else {
3610            // No trap: store on the target, which is where an ordinary proxy write lands.
3611            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
3612            return Ok(Some(true));
3613        };
3614        if !result.to_boolean() {
3615            return Ok(Some(false));
3616        }
3617        if let Some(fixed) = Self::is_fixed_property(&target, key) {
3618            if fixed.is_accessor() {
3619                let has_setter = fixed
3620                    .setter
3621                    .as_ref()
3622                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
3623                if !has_setter {
3624                    return Err(self.type_error(format!(
3625                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
3626                    )));
3627                }
3628            } else if !fixed.writable {
3629                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
3630                if !fixed_value.same_value(&value) {
3631                    return Err(self.type_error(format!(
3632                        "proxy 'set' changed the non-configurable property '{key}'"
3633                    )));
3634                }
3635            }
3636        }
3637        // A new property cannot appear on a target that refuses new properties.
3638        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
3639            return Err(self.type_error(format!(
3640                "proxy 'set' added '{key}' to a non-extensible target"
3641            )));
3642        }
3643        Ok(Some(true))
3644    }
3645
3646    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
3647    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
3648        let Some((target, handler)) = self.proxy_parts(object)? else {
3649            return Ok(None);
3650        };
3651        let key_value = self.key_value(key);
3652        let Some(result) = self.proxy_trap(
3653            &handler,
3654            "has",
3655            vec![Value::Object(target.clone()), key_value],
3656        )?
3657        else {
3658            return Ok(Some(self.has_own_or_inherited(&target, key)?));
3659        };
3660        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
3661            return Err(self.type_error(format!(
3662                "proxy 'has' denied the non-configurable property '{key}'"
3663            )));
3664        }
3665        // A non-extensible target cannot grow, so every own property it *has* is fixed.
3666        if !result.to_boolean()
3667            && !target.is_extensible()
3668            && Self::ordinary_own_property(&target, key).is_some()
3669        {
3670            return Err(self.type_error(format!(
3671                "proxy 'has' denied the own property '{key}' of a non-extensible target"
3672            )));
3673        }
3674        Ok(Some(result.to_boolean()))
3675    }
3676
3677    /// `[[Delete]]` on a proxy.
3678    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
3679        let Some((target, handler)) = self.proxy_parts(object)? else {
3680            return Ok(None);
3681        };
3682        let key_value = self.key_value(key);
3683        let Some(result) = self.proxy_trap(
3684            &handler,
3685            "deleteProperty",
3686            vec![Value::Object(target.clone()), key_value],
3687        )?
3688        else {
3689            return Ok(Some(self.delete_property_key(&target, key)?));
3690        };
3691        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
3692            return Err(self.type_error(format!(
3693                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
3694            )));
3695        }
3696        if result.to_boolean()
3697            && !target.is_extensible()
3698            && Self::ordinary_own_property(&target, key).is_some()
3699        {
3700            return Err(self.type_error(format!(
3701                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
3702            )));
3703        }
3704        Ok(Some(result.to_boolean()))
3705    }
3706
3707    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
3708    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
3709        let Some((target, handler)) = self.proxy_parts(object)? else {
3710            return Ok(None);
3711        };
3712        let Some(result) =
3713            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
3714        else {
3715            // No trap: the target's own keys, already in the order an object reports.
3716            return Ok(Some(self.object_own_property_keys(&target)?));
3717        };
3718        // `CreateListFromArrayLike` with the string-or-symbol restriction.
3719        let list = self.list_from_array_like(&result, true)?;
3720        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
3721        for value in list {
3722            let key = self.propkey(&value);
3723            if keys.contains(&key) {
3724                return Err(self.type_error(format!(
3725                    "proxy 'ownKeys' returned the duplicate key '{key}'"
3726                )));
3727            }
3728            keys.push(key);
3729        }
3730        for (key, property) in target.property_entries() {
3731            if !property.configurable && !keys.contains(&key) {
3732                return Err(self.type_error(format!(
3733                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
3734                )));
3735            }
3736            if !target.is_extensible() && !keys.contains(&key) {
3737                return Err(self.type_error(format!(
3738                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
3739                )));
3740            }
3741        }
3742        if !target.is_extensible() {
3743            let own = target.property_entries().len();
3744            if keys.len() != own {
3745                return Err(
3746                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
3747                );
3748            }
3749        }
3750        Ok(Some(keys))
3751    }
3752
3753    /// `[[GetOwnProperty]]` on a proxy.
3754    fn proxy_get_own_property(
3755        &mut self,
3756        object: &Gc<JsObject>,
3757        key: &PropertyKey,
3758    ) -> JsResult<Option<Option<Property>>> {
3759        let Some((target, handler)) = self.proxy_parts(object)? else {
3760            return Ok(None);
3761        };
3762        let key_value = self.key_value(key);
3763        let Some(result) = self.proxy_trap(
3764            &handler,
3765            "getOwnPropertyDescriptor",
3766            vec![Value::Object(target.clone()), key_value],
3767        )?
3768        else {
3769            // No trap: the target's own descriptor is the answer. This has to go through
3770            // the same synthesis an ordinary object gets, because a proxy's own property
3771            // table is empty by design — reading it directly reported `undefined` for
3772            // every key, including an array's indices and `length`.
3773            return Ok(Some(Self::ordinary_own_property(&target, key)));
3774        };
3775        let answer = if matches!(result, Value::Undefined) {
3776            None
3777        } else {
3778            Some(self.property_from_descriptor(&result)?)
3779        };
3780        let fixed = Self::is_fixed_property(&target, key);
3781        match (&answer, &fixed) {
3782            // A non-configurable property cannot be reported as absent.
3783            (None, Some(_)) => {
3784                return Err(self.type_error(format!(
3785                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
3786                )));
3787            }
3788            (Some(descriptor), Some(fixed)) => {
3789                if descriptor.configurable {
3790                    return Err(self.type_error(format!(
3791                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
3792                    )));
3793                }
3794                if fixed.is_accessor() != descriptor.is_accessor() {
3795                    return Err(self.type_error(format!(
3796                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
3797                    )));
3798                }
3799                if !fixed.is_accessor() && !fixed.writable {
3800                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
3801                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
3802                    if !fixed_value.same_value(&reported) {
3803                        return Err(self.type_error(format!(
3804                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
3805                        )));
3806                    }
3807                }
3808            }
3809            _ => {}
3810        }
3811        Ok(Some(answer))
3812    }
3813
3814    /// `[[DefineOwnProperty]]` on a proxy.
3815    fn proxy_define_property(
3816        &mut self,
3817        object: &Gc<JsObject>,
3818        key: &PropertyKey,
3819        property: Property,
3820    ) -> JsResult<Option<bool>> {
3821        let Some((target, handler)) = self.proxy_parts(object)? else {
3822            return Ok(None);
3823        };
3824        let key_value = self.key_value(key);
3825        let descriptor = self.descriptor_from_property(&property);
3826        let Some(result) = self.proxy_trap(
3827            &handler,
3828            "defineProperty",
3829            vec![Value::Object(target.clone()), key_value, descriptor],
3830        )?
3831        else {
3832            return Ok(None);
3833        };
3834        if !result.to_boolean() {
3835            return Ok(Some(false));
3836        }
3837        let fixed = Self::is_fixed_property(&target, key);
3838        let creating = Self::ordinary_own_property(&target, key).is_none();
3839        if creating && !target.is_extensible() {
3840            return Err(self.type_error(format!(
3841                "proxy 'defineProperty' added '{key}' to a non-extensible target"
3842            )));
3843        }
3844        if let Some(fixed) = fixed {
3845            if property.configurable {
3846                return Err(self.type_error(format!(
3847                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
3848                )));
3849            }
3850            if !fixed.writable && property.writable && !fixed.is_accessor() {
3851                return Err(self.type_error(format!(
3852                    "proxy 'defineProperty' made the read-only '{key}' writable"
3853                )));
3854            }
3855        }
3856        Ok(Some(true))
3857    }
3858
3859    /// `[[GetPrototypeOf]]` on a proxy.
3860    fn proxy_get_prototype_of(
3861        &mut self,
3862        object: &Gc<JsObject>,
3863    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
3864        let Some((target, handler)) = self.proxy_parts(object)? else {
3865            return Ok(None);
3866        };
3867        let Some(result) = self.proxy_trap(
3868            &handler,
3869            "getPrototypeOf",
3870            vec![Value::Object(target.clone())],
3871        )?
3872        else {
3873            return Ok(Some(target.proto()));
3874        };
3875        let proto = match &result {
3876            Value::Null => None,
3877            Value::Object(proto) => Some(proto.clone()),
3878            _ => {
3879                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
3880            }
3881        };
3882        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
3883            return Err(self.type_error(
3884                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
3885            ));
3886        }
3887        Ok(Some(proto))
3888    }
3889
3890    /// `[[SetPrototypeOf]]` on a proxy.
3891    fn proxy_set_prototype_of(
3892        &mut self,
3893        object: &Gc<JsObject>,
3894        proto: Option<Gc<JsObject>>,
3895    ) -> JsResult<Option<bool>> {
3896        let Some((target, handler)) = self.proxy_parts(object)? else {
3897            return Ok(None);
3898        };
3899        let proto_value = match &proto {
3900            Some(proto) => Value::Object(proto.clone()),
3901            None => Value::Null,
3902        };
3903        let Some(result) = self.proxy_trap(
3904            &handler,
3905            "setPrototypeOf",
3906            vec![Value::Object(target.clone()), proto_value],
3907        )?
3908        else {
3909            target.set_proto(proto);
3910            return Ok(Some(true));
3911        };
3912        if result.to_boolean()
3913            && !target.is_extensible()
3914            && !same_proto(proto.as_ref(), target.proto().as_ref())
3915        {
3916            return Err(self.type_error(
3917                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
3918            ));
3919        }
3920        Ok(Some(result.to_boolean()))
3921    }
3922
3923    /// `[[IsExtensible]]` on a proxy.
3924    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
3925        let Some((target, handler)) = self.proxy_parts(object)? else {
3926            return Ok(None);
3927        };
3928        let Some(result) = self.proxy_trap(
3929            &handler,
3930            "isExtensible",
3931            vec![Value::Object(target.clone())],
3932        )?
3933        else {
3934            return Ok(Some(target.is_extensible()));
3935        };
3936        // The answer is not the proxy's to invent: it must agree with the target, or a
3937        // script could learn `false` while the target keeps accepting new properties.
3938        if result.to_boolean() != target.is_extensible() {
3939            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
3940        }
3941        Ok(Some(result.to_boolean()))
3942    }
3943
3944    /// `[[PreventExtensions]]` on a proxy.
3945    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
3946        let Some((target, handler)) = self.proxy_parts(object)? else {
3947            return Ok(None);
3948        };
3949        let Some(result) = self.proxy_trap(
3950            &handler,
3951            "preventExtensions",
3952            vec![Value::Object(target.clone())],
3953        )?
3954        else {
3955            target.set_extensible(false);
3956            return Ok(Some(true));
3957        };
3958        if result.to_boolean() && target.is_extensible() {
3959            return Err(self.type_error(
3960                "proxy 'preventExtensions' reported success but the target is still extensible",
3961            ));
3962        }
3963        Ok(Some(result.to_boolean()))
3964    }
3965
3966    /// `[[Call]]` on a proxy, through the `apply` trap.
3967    fn proxy_apply(
3968        &mut self,
3969        object: &Gc<JsObject>,
3970        this: Value,
3971        args: Vec<Value>,
3972    ) -> JsResult<Option<Value>> {
3973        let Some((target, handler)) = self.proxy_parts(object)? else {
3974            return Ok(None);
3975        };
3976        // The trap gets the arguments as one array, which is the shape the spec passes
3977        // and the shape `apply` traps are written against (`args[0]` is the first one).
3978        let arguments = self.new_array(args.clone());
3979        let this_for_trap = this.clone();
3980        let Some(result) = self.proxy_trap(
3981            &handler,
3982            "apply",
3983            vec![
3984                Value::Object(target.clone()),
3985                this_for_trap,
3986                Value::Object(arguments),
3987            ],
3988        )?
3989        else {
3990            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
3991        };
3992        Ok(Some(result))
3993    }
3994
3995    /// `[[Construct]]` on a proxy, through the `construct` trap.
3996    fn proxy_construct(
3997        &mut self,
3998        object: &Gc<JsObject>,
3999        args: Vec<Value>,
4000        new_target: &Value,
4001    ) -> JsResult<Option<Value>> {
4002        let Some((target, handler)) = self.proxy_parts(object)? else {
4003            return Ok(None);
4004        };
4005        if !target.is_callable() {
4006            return Err(self.type_error("proxy target is not a constructor"));
4007        }
4008        let arguments = self.new_array(args.clone());
4009        let Some(result) = self.proxy_trap(
4010            &handler,
4011            "construct",
4012            vec![
4013                Value::Object(target.clone()),
4014                Value::Object(arguments),
4015                new_target.clone(),
4016            ],
4017        )?
4018        else {
4019            return Ok(Some(self.construct(
4020                Value::Object(target),
4021                new_target.clone(),
4022                args,
4023            )?));
4024        };
4025        if !matches!(result, Value::Object(_)) {
4026            return Err(self.type_error("proxy 'construct' must return an object"));
4027        }
4028        Ok(Some(result))
4029    }
4030
4031    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
4032    pub(crate) fn has_own_or_inherited(
4033        &mut self,
4034        object: &Gc<JsObject>,
4035        key: &PropertyKey,
4036    ) -> JsResult<bool> {
4037        // The object itself first: it may be a proxy, and then the answer is its trap's.
4038        if let Some(answer) = self.proxy_has(object, key)? {
4039            return Ok(answer);
4040        }
4041        // `has_own` rather than `own_property_key`: an array's elements and its derived
4042        // `length` are invisible to the property table, and `Array.prototype` is an array.
4043        if has_own(object, key) {
4044            return Ok(true);
4045        }
4046        // A hole is *not* the end of the search: the chain may still have the key, which
4047        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
4048        for ancestor in object.chain() {
4049            // A proxy further up the chain answers for itself.
4050            if let Some(answer) = self.proxy_has(&ancestor, key)? {
4051                return Ok(answer);
4052            }
4053            if has_own(&ancestor, key) {
4054                return Ok(true);
4055            }
4056        }
4057        Ok(false)
4058    }
4059
4060    /// `CreateListFromArrayLike`, optionally restricted to property keys.
4061    ///
4062    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
4063    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
4064    /// `TypeError` instead of a property named `"1.5"`.
4065    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
4066        let object = self.object_from(value)?;
4067        let length = self
4068            .get_property(&object, "length")?
4069            .map(|value| value.to_number())
4070            .unwrap_or(0.0);
4071        if !length.is_finite() || length < 0.0 {
4072            return Err(self.type_error("invalid array-like length"));
4073        }
4074        let length = length as usize;
4075        let mut items = Vec::with_capacity(length.min(1024));
4076        for index in 0..length {
4077            let item = self
4078                .get_property(&object, &index.to_string())?
4079                .unwrap_or(Value::Undefined);
4080            if keys_only && matches!(&item, Value::Symbol(_)) {
4081                items.push(item);
4082                continue;
4083            }
4084            if keys_only && !matches!(&item, Value::String(_)) {
4085                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
4086            }
4087            items.push(item);
4088        }
4089        Ok(items)
4090    }
4091
4092    /// A `Property` from the descriptor object a trap returned.
4093    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
4094        let object = self.object_from(value)?;
4095        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
4096            interp.get_property(&object, name)
4097        };
4098        let getter = field(self, "get")?;
4099        let setter = field(self, "set")?;
4100        let accessor = getter.is_some() || setter.is_some();
4101        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
4102            Ok(interp
4103                .get_property(&object, name)?
4104                .is_some_and(|value| value.to_boolean()))
4105        };
4106        let enumerable = boolean(self, "enumerable")?;
4107        let configurable = boolean(self, "configurable")?;
4108        if accessor {
4109            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
4110                return Err(
4111                    self.type_error("a descriptor cannot be both a data property and an accessor")
4112                );
4113            }
4114            Ok(Property {
4115                getter: getter.or(Some(Value::Undefined)),
4116                setter: setter.or(Some(Value::Undefined)),
4117                enumerable,
4118                configurable,
4119                writable: false,
4120                value: None,
4121            })
4122        } else {
4123            Ok(Property {
4124                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
4125                writable: boolean(self, "writable")?,
4126                enumerable,
4127                configurable,
4128                getter: None,
4129                setter: None,
4130            })
4131        }
4132    }
4133
4134    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
4135    fn descriptor_from_property(&mut self, property: &Property) -> Value {
4136        let object = self.new_object(None);
4137        if property.is_accessor() {
4138            let getter = property.getter.clone().unwrap_or(Value::Undefined);
4139            let setter = property.setter.clone().unwrap_or(Value::Undefined);
4140            object.define_data("get", getter);
4141            object.define_data("set", setter);
4142        } else {
4143            let value = property.value.clone().unwrap_or(Value::Undefined);
4144            object.define_data("value", value);
4145            object.define_data("writable", Value::Bool(property.writable));
4146        }
4147        object.define_data("enumerable", Value::Bool(property.enumerable));
4148        object.define_data("configurable", Value::Bool(property.configurable));
4149        Value::Object(object)
4150    }
4151
4152    // -- calling ------------------------------------------------------------
4153
4154    /// Call `callee` with `this` and `args`.
4155    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
4156        let Value::Object(function) = &callee else {
4157            // `typeof x === "function"` is not enough to make `x()` legal: only a
4158            // callable object is. `null` and `undefined` need no special wording
4159            // here — their `ToString` already reads the way the reference's does.
4160            let what = format!("{} is not a function", callee.to_js_string());
4161            return Err(Signal::Throw(self.make_error("TypeError", &what)));
4162        };
4163        // A proxy of a function is called through its `apply` trap. It has no
4164        // `ObjectKind::Function` of its own, so this has to come before the dispatch
4165        // below, and a proxy of a non-function has nothing to forward to.
4166        if function.proxy_state().is_some() {
4167            return match self.proxy_apply(function, this, args)? {
4168                Some(result) => Ok(result),
4169                None => Err(Signal::Throw(
4170                    self.make_error("TypeError", "proxy target is not callable"),
4171                )),
4172            };
4173        }
4174        let callable = function.with(|data| match &data.kind {
4175            ObjectKind::Function(callable) => match callable {
4176                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
4177                Callable::Bound {
4178                    target,
4179                    this,
4180                    args: leading,
4181                } => Some(NativeCall::Bound {
4182                    target: target.clone(),
4183                    this: this.clone(),
4184                    leading: leading.clone(),
4185                }),
4186                Callable::Bytecode { code, env } => {
4187                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
4188                }
4189                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
4190                Callable::PromiseResolve(promise) => {
4191                    Some(NativeCall::PromiseResolve(promise.clone()))
4192                }
4193                Callable::PromiseReject(promise) => {
4194                    Some(NativeCall::PromiseReject(promise.clone()))
4195                }
4196                Callable::AwaitResume {
4197                    coroutine,
4198                    promise,
4199                    kind,
4200                } => Some(NativeCall::AwaitResume {
4201                    coroutine: coroutine.clone(),
4202                    promise: promise.clone(),
4203                    kind: *kind,
4204                }),
4205                Callable::CombinatorSettle {
4206                    state,
4207                    index,
4208                    fulfilled,
4209                } => Some(NativeCall::CombinatorSettle {
4210                    state: state.clone(),
4211                    index: *index,
4212                    fulfilled: *fulfilled,
4213                }),
4214                Callable::FinallyShim {
4215                    callback,
4216                    fulfilled,
4217                } => Some(NativeCall::FinallyShim {
4218                    callback: callback.clone(),
4219                    fulfilled: *fulfilled,
4220                }),
4221                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
4222                Callable::YieldResult { promise, done } => Some(NativeCall::YieldResult {
4223                    promise: promise.clone(),
4224                    done: *done,
4225                }),
4226                Callable::DisposeStep {
4227                    remaining,
4228                    promise,
4229                    error,
4230                    rejected,
4231                } => Some(NativeCall::DisposeStep {
4232                    remaining: remaining.clone(),
4233                    promise: promise.clone(),
4234                    error: error.clone(),
4235                    rejected: *rejected,
4236                }),
4237                Callable::GeneratorResume {
4238                    generator,
4239                    promise,
4240                    kind,
4241                } => Some(NativeCall::GeneratorResume {
4242                    generator: generator.clone(),
4243                    promise: promise.clone(),
4244                    kind: *kind,
4245                }),
4246                Callable::SettlePromise {
4247                    promise,
4248                    value,
4249                    rejected,
4250                } => Some(NativeCall::SettlePromise {
4251                    promise: promise.clone(),
4252                    value: value.clone(),
4253                    rejected: *rejected,
4254                }),
4255            },
4256            _ => None,
4257        });
4258        match callable {
4259            Some(NativeCall::Native(func)) => {
4260                // A function marked `_frame_less` is one the reference implements
4261                // without a call frame — `eval` is the only one so far.
4262                let frame_less = function
4263                    .own_property("_frame_less")
4264                    .and_then(|property| property.value)
4265                    .is_some_and(|value| value.to_boolean());
4266                let name = function
4267                    .own_property("name")
4268                    .and_then(|property| property.value)
4269                    .map(|value| value.to_js_string())
4270                    .unwrap_or_default();
4271                let outer = if frame_less {
4272                    None
4273                } else {
4274                    self.native_frames.push((name, function.clone()));
4275                    Some(self.current_native.replace(function.clone()))
4276                };
4277                let result = func(self, this, &args);
4278                if !frame_less {
4279                    self.native_frames.pop();
4280                    self.current_native = outer.flatten();
4281                }
4282                result
4283            }
4284            Some(NativeCall::Revoker(slots)) => {
4285                // Idempotent: revoking twice answers `undefined` again rather than
4286                // complaining, which is what the spec says and what a `finally` block
4287                // relies on.
4288                let mut state = slots.borrow_mut();
4289                state.target = None;
4290                state.handler = None;
4291                Ok(Value::Undefined)
4292            }
4293            Some(NativeCall::PromiseResolve(promise)) => {
4294                // One-shot: a second call is silently ignored, which
4295                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
4296                let value = args.first().cloned().unwrap_or(Value::Undefined);
4297                self.resolve_promise_with(&promise, value)?;
4298                Ok(Value::Undefined)
4299            }
4300            Some(NativeCall::PromiseReject(promise)) => {
4301                let reason = args.first().cloned().unwrap_or(Value::Undefined);
4302                self.reject_promise(&promise, reason);
4303                Ok(Value::Undefined)
4304            }
4305            Some(NativeCall::CombinatorSettle {
4306                state,
4307                index,
4308                fulfilled,
4309            }) => {
4310                let value = args.first().cloned().unwrap_or(Value::Undefined);
4311                self.settle_combinator(&state, index, fulfilled, value)?;
4312                Ok(Value::Undefined)
4313            }
4314            Some(NativeCall::AwaitResume {
4315                coroutine,
4316                promise,
4317                kind,
4318            }) => {
4319                // Resume *inline*, in the reaction that delivered the value. Deferring it
4320                // by another job inserts a tick between every `await` and its
4321                // continuation, which reorders `await` against unrelated `then` chains —
4322                // `f().then(g)` then runs before `f`'s own next statement.
4323                self.drive_async(
4324                    &coroutine,
4325                    &promise,
4326                    kind,
4327                    args.first().cloned().unwrap_or(Value::Undefined),
4328                )
4329                .map(|()| Value::Undefined)
4330            }
4331            Some(NativeCall::FinallyShim {
4332                callback,
4333                fulfilled,
4334            }) => {
4335                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
4336                // that settles with the *original* outcome once the callback's result has
4337                // settled. The callback's own value is discarded — that is the whole
4338                // difference between `finally` and `then`.
4339                let original = args.first().cloned().unwrap_or(Value::Undefined);
4340                let result = match &callback {
4341                    Some(callback) => {
4342                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
4343                    }
4344                    None => Value::Undefined,
4345                };
4346                let resolved = self.promise_resolve_value(result)?;
4347                let Value::Object(resolved) = resolved else {
4348                    return Ok(original);
4349                };
4350                // The wait is a chained promise rather than a bare return, so a callback
4351                // that returns a slow promise really does delay the continuation.
4352                let waiting = self.new_promise();
4353                let pass = JsObject::function(
4354                    self.heap,
4355                    Some(self.realm.function_proto.clone()),
4356                    Callable::SettlePromise {
4357                        promise: waiting.clone(),
4358                        value: original,
4359                        rejected: !fulfilled,
4360                    },
4361                );
4362                let pass = Value::Object(pass);
4363                // Whichever way the callback's promise settles, the original outcome wins.
4364                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
4365                Ok(Value::Object(waiting))
4366            }
4367            Some(NativeCall::DisposeStep {
4368                remaining,
4369                promise,
4370                error,
4371                rejected,
4372            }) => {
4373                let error = if rejected {
4374                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
4375                    self.merge_dispose_error(reason, error)
4376                } else {
4377                    error
4378                };
4379                self.dispose_step(&remaining, &promise, error)?;
4380                Ok(Value::Undefined)
4381            }
4382            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
4383            Some(NativeCall::YieldResult { promise, done }) => {
4384                let value = args.first().cloned().unwrap_or(Value::Undefined);
4385                let result = self.iterator_result(value, done)?;
4386                self.fulfill_promise(&promise, result);
4387                Ok(Value::Undefined)
4388            }
4389            Some(NativeCall::GeneratorResume {
4390                generator,
4391                promise,
4392                kind,
4393            }) => {
4394                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
4395                // tick and reorders the generator against other chains.
4396                self.step_async_generator(
4397                    &generator,
4398                    &promise,
4399                    kind,
4400                    args.first().cloned().unwrap_or(Value::Undefined),
4401                )
4402                .map(|()| Value::Undefined)
4403            }
4404            Some(NativeCall::SettlePromise {
4405                promise,
4406                value,
4407                rejected,
4408            }) => {
4409                if rejected {
4410                    self.reject_promise(&promise, value);
4411                } else {
4412                    self.fulfill_promise(&promise, value);
4413                }
4414                Ok(Value::Undefined)
4415            }
4416            Some(NativeCall::Bound {
4417                target,
4418                this: bound_this,
4419                leading,
4420            }) => {
4421                let mut all = leading;
4422                all.extend(args);
4423                self.call_value(target, bound_this, all)
4424            }
4425            Some(NativeCall::Bytecode(code, env)) => {
4426                if code.code.kind.is_generator() {
4427                    return self.new_generator(callee, this, args);
4428                }
4429                if code.code.kind.is_async() {
4430                    // Same coroutine machinery as a generator; the difference is only in
4431                    // what the completion does — see `new_async_function`.
4432                    return self.new_async_function(callee, this, args);
4433                }
4434                self.execute(code, env, this, args, callee)
4435            }
4436            None => Err(Signal::Throw(
4437                self.make_error("TypeError", "not a function"),
4438            )),
4439        }
4440    }
4441
4442    /// Give a freshly built function its own `prototype` object.
4443    ///
4444    /// Every function that can be used with `new` carries one, and its
4445    /// `constructor` points back at the function — a reference cycle, which is
4446    /// exactly what the collector's cycle pass exists to reclaim.
4447    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
4448        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
4449        let constructor = Value::Object(function.clone());
4450        prototype.define(
4451            "constructor",
4452            Property::with_attributes(constructor, true, false),
4453        );
4454        let value = Value::Object(prototype);
4455        function.define("prototype", Property::prototype_of(value, true));
4456    }
4457
4458    /// The object `special_object` builds.
4459    ///
4460    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
4461    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
4462    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
4463    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
4464    /// write through `arguments` does not reach the parameter.
4465    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
4466        match magic {
4467            0 | 1 => {
4468                let args = self.frame().passed.clone();
4469                let proto = self.realm.object_proto.clone();
4470                let object = self.new_object(Some(proto));
4471                // The marker `Object.prototype.toString` needs: an arguments object is an
4472                // ordinary object apart from reporting `[object Arguments]`, and that has
4473                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
4474                // show up ahead of them in a key listing anyway — it is non-enumerable.
4475                self.internal_set(&object, "_class", self.string("Arguments"));
4476                // `length` is writable and configurable but neither enumerable nor a
4477                // plain data property: `Object.keys(arguments)` lists the indices only,
4478                // which is how `{...arguments}` copies them without the length.
4479                object.define(
4480                    "length",
4481                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
4482                );
4483                for (index, value) in args.into_iter().enumerate() {
4484                    object.define_data(&index.to_string(), value);
4485                }
4486                // An arguments object is iterable: `[...arguments]` and
4487                // `for (const a of arguments)` both work, through the *array* iterator
4488                // because the object is array-like. Without this the whole spread form
4489                // reported "not iterable".
4490                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
4491                let values = self
4492                    .realm
4493                    .array_proto
4494                    .own_property("values")
4495                    .and_then(|property| property.value);
4496                if let Some(values) = values {
4497                    object.define_key(
4498                        &iterator_key,
4499                        Property::with_attributes(values, true, false),
4500                    );
4501                }
4502                Ok(Value::Object(object))
4503            }
4504            // `this function`: what a named function expression binds its own name to.
4505            2 => Ok(self
4506                .current_callee()
4507                .map_or(Value::Undefined, Value::Object)),
4508            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
4509            // inherited from the caller inside an `eval`.
4510            3 => Ok(self
4511                .eval_new_target
4512                .clone()
4513                .unwrap_or_else(|| self.frame().new_target.clone())),
4514            // `[[HomeObject]]` of the function being run: what `super` is relative to.
4515            // An arrow has none of its own, so the lookup walks out to the enclosing
4516            // method — which is why `super` works inside an arrow inside a method.
4517            4 => Ok(self
4518                .frames
4519                .iter()
4520                .rev()
4521                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
4522                .map_or(Value::Undefined, Value::Object)),
4523            // `import.meta`: the innermost module body's meta object. Outside a module
4524            // the compiler never emits this, so an empty fallback is unreachable rather
4525            // than permissive.
4526            6 => {
4527                let name = self.module_stack.last().cloned();
4528                let meta = name
4529                    .and_then(|name| self.modules.get(&name).cloned())
4530                    .and_then(|module| module.with(|r| r.import_meta.clone()));
4531                Ok(meta.map_or(Value::Undefined, Value::Object))
4532            }
4533            other => Err(Signal::Throw(self.make_error(
4534                "InternalError",
4535                &format!("special_object {other} is not implemented yet"),
4536            ))),
4537        }
4538    }
4539
4540    /// `[[HomeObject]]` of the innermost function that has one, if any.
4541    ///
4542    /// An arrow has none, so the search walks out to the enclosing method — the same
4543    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
4544    /// inside a method.
4545    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
4546        self.frames
4547            .iter()
4548            .rev()
4549            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
4550    }
4551
4552    /// The dispose method a `using` declaration should snapshot, or an error.
4553    ///
4554    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
4555    /// is what makes a resource that only knows the synchronous protocol usable in both
4556    /// forms.
4557    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
4558        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
4559        if value.is_nullish() {
4560            return Ok(Value::Undefined);
4561        }
4562        let Some(object) = value.as_object() else {
4563            return Err(self.type_error("value is not disposable: it is not an object"));
4564        };
4565        let mut method = if await_form {
4566            let found = self.get_property_key(
4567                object,
4568                &self.realm.well_known_key(WellKnown::AsyncDisposable),
4569            )?;
4570            match found {
4571                Some(found) if !found.is_nullish() => Some(found),
4572                _ => self
4573                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
4574            }
4575        } else {
4576            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
4577        };
4578        let Some(found) = method.take() else {
4579            return Err(self.type_error("value is not disposable"));
4580        };
4581        if found.is_nullish() {
4582            return Err(self.type_error("value is not disposable"));
4583        }
4584        let callable = found.as_object().is_some_and(|object| object.is_callable());
4585        if !callable {
4586            return Err(self.type_error("dispose method is not a function"));
4587        }
4588        Ok(found)
4589    }
4590
4591    /// Call one resource's disposer, folding a failure into `error_state`.
4592    ///
4593    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
4594    /// because a captured `using` binding lives in its reference cell and the local slot is
4595    /// stale — a closure over the resource is legal and must not change what is disposed.
4596    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
4597        let value = self.get_loc(slot);
4598        let method = self.get_loc(slot + 1);
4599        // A resource that was never initialised — its declaration threw — or that is
4600        // `null`/`undefined` has nothing to dispose.
4601        if value.is_nullish() || matches!(value, Value::Uninitialized) {
4602            return Ok(error_state);
4603        }
4604        if matches!(method, Value::Undefined | Value::Uninitialized) {
4605            return Ok(error_state);
4606        }
4607        match self.call_value(method, value, Vec::new()) {
4608            Ok(_) => Ok(error_state),
4609            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
4610            Err(other) => Err(other),
4611        }
4612    }
4613
4614    /// Combine a disposal failure with whatever was already going wrong.
4615    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
4616        if matches!(error_state, Value::Uninitialized) {
4617            return new_error;
4618        }
4619        self.new_suppressed_error(new_error, error_state)
4620    }
4621
4622    /// A `SuppressedError` instance built straight from its prototype.
4623    ///
4624    /// Not through the constructor: a script that rewrites
4625    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
4626    /// error wrapping.
4627    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
4628        let proto = self
4629            .realm
4630            .suppressed_error_proto
4631            .clone()
4632            .unwrap_or_else(|| self.realm.error_proto.clone());
4633        let object = self.new_object(Some(proto));
4634        object.define("error", Property::with_attributes(error, true, true));
4635        object.define(
4636            "suppressed",
4637            Property::with_attributes(suppressed, true, true),
4638        );
4639        object.define(
4640            "message",
4641            Property::with_attributes(self.string("SuppressedError"), true, true),
4642        );
4643        self.internal_set(&object, "_class", self.string("Error"));
4644        self.add_stack(&object);
4645        Value::Object(object)
4646    }
4647
4648    /// Call `callee`, or push its frame and let the main loop run it.
4649    ///
4650    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
4651    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
4652    /// continues, so `function f(){ return f() }` costs heap and stops at
4653    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
4654    /// is entered directly, and natives do not re-enter JavaScript in this
4655    /// milestone.
4656    ///
4657    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
4658    /// because the returning frame will.
4659    /// The elements of an array-like value, as a call argument list.
4660    ///
4661    /// `apply` accepts any array-like, not only a real array: the reference reads
4662    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
4663    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
4664        let Some(object) = value.as_object().cloned() else {
4665            if value.is_nullish() {
4666                // `f.apply(this, null)` passes no arguments at all.
4667                return Ok(Vec::new());
4668            }
4669            return Err(self.type_error("createListFromArrayLike called on non-object"));
4670        };
4671        let length = match self.get_property(&object, "length")? {
4672            Some(length) => length.to_number(),
4673            None => 0.0,
4674        };
4675        if !length.is_finite() || length <= 0.0 {
4676            return Ok(Vec::new());
4677        }
4678        let length = (length as usize).min(1_000_000);
4679        let mut args = Vec::with_capacity(length);
4680        for index in 0..length {
4681            let element = self.get_property(&object, &index.to_string())?;
4682            args.push(element.unwrap_or(Value::Undefined));
4683        }
4684        Ok(args)
4685    }
4686
4687    /// Turn a call to a generator function into a generator object.
4688    ///
4689    /// The frame is built exactly as an ordinary call would build it, then detached and
4690    /// stored in the generator before any body instruction runs — which is what makes
4691    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
4692    /// is `initial_yield`, the first instruction of every suspending body.
4693    pub fn new_generator(
4694        &mut self,
4695        function: Value,
4696        this: Value,
4697        args: Vec<Value>,
4698    ) -> JsResult<Value> {
4699        let Some(object) = function.as_object().cloned() else {
4700            return Err(self.type_error("not a generator function"));
4701        };
4702        let Some((code, env)) = bytecode_of(&object) else {
4703            return Err(self.type_error("not a generator function"));
4704        };
4705        let is_async = code.code.kind.is_async();
4706        self.push_frame(code, env, this, args, function)?;
4707        let frame = self.frames.pop().expect("push_frame just pushed it");
4708        // A fresh generator is *suspended at start*: the body has not run, so a
4709        // `return`/`throw` on it finishes without executing anything.
4710        let mut state = GeneratorState {
4711            frame: Some(frame),
4712            phase: GeneratorPhase::SuspendedStart,
4713            parked_on_await: false,
4714        };
4715        // Run to the first suspension. For a generator that is `initial_yield`, so no
4716        // body code runs; for a malformed body it would be the first `yield`.
4717        // An `async function*` answers an async generator: same coroutine, but its
4718        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
4719        let proto = if is_async {
4720            self.realm
4721                .async_generator_proto
4722                .clone()
4723                .unwrap_or_else(|| self.realm.generator_proto.clone())
4724        } else {
4725            self.realm.generator_proto.clone()
4726        };
4727        let generator = self.new_object(Some(proto));
4728        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
4729            Ok(_) => {}
4730            Err(error) => return Err(error),
4731        }
4732        generator.with_mut(|data| {
4733            data.kind = ObjectKind::Generator(Box::new(state));
4734        });
4735        Ok(Value::Object(generator))
4736    }
4737
4738    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
4739    ///
4740    /// Returns the `{value, done}` object itself rather than the pair, because a
4741    /// `yield*` suspension already has one — the inner iterator's own result — and the
4742    /// protocol says to hand that straight through rather than nest it.
4743    /// Advance a generator and report *why* it parked.
4744    ///
4745    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
4746    /// "hand this value to the caller" — but an async generator does: an `await` has to
4747    /// settle before it can answer, while a `yield` is the answer.
4748    fn resume_generator_detailed(
4749        &mut self,
4750        generator: &Gc<JsObject>,
4751        kind: ResumeKind,
4752        value: Value,
4753    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
4754        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
4755            ObjectKind::Generator(state) => Some(std::mem::replace(
4756                state.as_mut(),
4757                GeneratorState {
4758                    frame: None,
4759                    phase: GeneratorPhase::Executing,
4760                    parked_on_await: false,
4761                },
4762            )),
4763            _ => None,
4764        }) else {
4765            return Err(self.type_error("not a generator"));
4766        };
4767        let result = self.step_generator(&mut state, kind, value);
4768        generator.with_mut(|data| {
4769            data.kind = ObjectKind::Generator(Box::new(state));
4770        });
4771        result
4772    }
4773
4774    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
4775    ///
4776    /// Returns the `{value, done}` object itself rather than the pair, because a
4777    /// `yield*` suspension already has one — the inner iterator's own result — and the
4778    /// protocol says to hand that straight through rather than nest it.
4779    pub fn resume_generator(
4780        &mut self,
4781        generator: &Gc<JsObject>,
4782        kind: ResumeKind,
4783        value: Value,
4784    ) -> JsResult<Value> {
4785        let (value, done, ready, _reason) =
4786            self.resume_generator_detailed(generator, kind, value)?;
4787        if ready {
4788            return Ok(value);
4789        }
4790        self.iterator_result(value, done)
4791    }
4792
4793    /// `next`/`return`/`throw` on an async generator, which answer a promise.
4794    ///
4795    /// The body is the same coroutine a sync generator runs; what changes is that an
4796    /// `await` inside it has to settle before the method can answer, so the step is
4797    /// driven off the job queue rather than returning inline.
4798    pub fn resume_async_generator(
4799        &mut self,
4800        generator: &Gc<JsObject>,
4801        kind: ResumeKind,
4802        value: Value,
4803    ) -> JsResult<Value> {
4804        let promise = self.new_promise();
4805        self.step_async_generator(generator, &promise, kind, value)?;
4806        Ok(Value::Object(promise))
4807    }
4808
4809    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
4810    ///
4811    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
4812    /// disposer runs **synchronously** — the reference starts it before returning, which
4813    /// a test can observe by logging after the call — and the rest follow once their
4814    /// predecessor settles.
4815    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
4816        let promise = self.new_promise();
4817        let mut pairs = Vec::with_capacity(resources.len());
4818        for (value, method) in resources {
4819            let pair = self.new_array(vec![value, method]);
4820            pairs.push(Value::Object(pair));
4821        }
4822        let remaining = self.new_array(pairs);
4823        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
4824        Ok(Value::Object(promise))
4825    }
4826
4827    /// One link of the `disposeAsync` chain.
4828    ///
4829    /// Loops while the disposers finish synchronously, and parks on the first thenable it
4830    /// meets — pushing itself back in as the continuation, with the accumulated error
4831    /// carried along so a later failure can still be folded into the `SuppressedError`.
4832    fn dispose_step(
4833        &mut self,
4834        remaining: &Gc<JsObject>,
4835        promise: &Gc<JsObject>,
4836        mut error: Value,
4837    ) -> JsResult<()> {
4838        loop {
4839            let length = remaining.array_length().unwrap_or(0);
4840            if length == 0 {
4841                if matches!(error, Value::Uninitialized) {
4842                    self.fulfill_promise(promise, Value::Undefined);
4843                } else {
4844                    self.reject_promise(promise, error);
4845                }
4846                return Ok(());
4847            }
4848            let Some(Value::Object(pair)) = remaining
4849                .array_get(length - 1)
4850                .filter(|v| !matches!(v, Value::Hole))
4851            else {
4852                remaining.array_truncate(length - 1);
4853                continue;
4854            };
4855            remaining.array_truncate(length - 1);
4856            let value = pair.array_get(0).unwrap_or(Value::Undefined);
4857            let Some(Value::Object(method)) = pair.array_get(1) else {
4858                continue;
4859            };
4860            if !method.is_callable() {
4861                continue;
4862            }
4863            match self.call_value(Value::Object(method), value, Vec::new()) {
4864                Ok(result) => {
4865                    if !self.is_thenable(&result)? {
4866                        // Finished synchronously; the next disposer is the next iteration.
4867                        continue;
4868                    }
4869                    let awaited = match self.promise_resolve_value(result) {
4870                        Ok(awaited) => awaited,
4871                        Err(Signal::Throw(reason)) => {
4872                            self.reject_promise(promise, reason);
4873                            return Ok(());
4874                        }
4875                        Err(other) => return Err(other),
4876                    };
4877                    let Value::Object(awaited) = awaited else {
4878                        continue;
4879                    };
4880                    let ok = JsObject::function(
4881                        self.heap,
4882                        Some(self.realm.function_proto.clone()),
4883                        Callable::DisposeStep {
4884                            remaining: remaining.clone(),
4885                            promise: promise.clone(),
4886                            error: error.clone(),
4887                            rejected: false,
4888                        },
4889                    );
4890                    let failed = JsObject::function(
4891                        self.heap,
4892                        Some(self.realm.function_proto.clone()),
4893                        Callable::DisposeStep {
4894                            remaining: remaining.clone(),
4895                            promise: promise.clone(),
4896                            error,
4897                            rejected: true,
4898                        },
4899                    );
4900                    self.perform_then(
4901                        &awaited,
4902                        Some(Value::Object(ok)),
4903                        Some(Value::Object(failed)),
4904                    )?;
4905                    return Ok(());
4906                }
4907                Err(Signal::Throw(thrown)) => {
4908                    error = self.merge_dispose_error(thrown, error);
4909                }
4910                Err(other) => return Err(other),
4911            }
4912        }
4913    }
4914
4915    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
4916    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
4917        let Value::Object(object) = value else {
4918            return Ok(false);
4919        };
4920        Ok(matches!(
4921            self.get_property(object, "then")?,
4922            Some(Value::Object(then)) if then.is_callable()
4923        ))
4924    }
4925
4926    /// One step of an async generator, settling `promise` with an `{value, done}` result.
4927    fn step_async_generator(
4928        &mut self,
4929        generator: &Gc<JsObject>,
4930        promise: &Gc<JsObject>,
4931        kind: ResumeKind,
4932        value: Value,
4933    ) -> JsResult<()> {
4934        let stepped = self.resume_generator_detailed(generator, kind, value);
4935        let (value, done, ready, reason) = match stepped {
4936            Ok(stepped) => stepped,
4937            Err(Signal::Throw(reason)) => {
4938                self.reject_promise(promise, reason);
4939                return Ok(());
4940            }
4941            Err(other) => return Err(other),
4942        };
4943        // Only an `await` has to wait before the method can answer.
4944        if !done && reason == Some(SuspendKind::Await) {
4945            let awaited = match self.promise_resolve_value(value) {
4946                Ok(awaited) => awaited,
4947                Err(Signal::Throw(reason)) => {
4948                    self.reject_promise(promise, reason);
4949                    return Ok(());
4950                }
4951                Err(other) => return Err(other),
4952            };
4953            let Value::Object(awaited) = awaited else {
4954                return Ok(());
4955            };
4956            let resumed = JsObject::function(
4957                self.heap,
4958                Some(self.realm.function_proto.clone()),
4959                Callable::GeneratorResume {
4960                    generator: generator.clone(),
4961                    promise: promise.clone(),
4962                    kind: ResumeKind::Next,
4963                },
4964            );
4965            let raised = JsObject::function(
4966                self.heap,
4967                Some(self.realm.function_proto.clone()),
4968                Callable::GeneratorResume {
4969                    generator: generator.clone(),
4970                    promise: promise.clone(),
4971                    kind: ResumeKind::Throw,
4972                },
4973            );
4974            self.perform_then(
4975                &awaited,
4976                Some(Value::Object(resumed)),
4977                Some(Value::Object(raised)),
4978            )?;
4979            return Ok(());
4980        }
4981        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
4982        // completes it — both arrive as the settled value rather than as the promise
4983        // object. A plain value skips the round trip, which is also what keeps `yield 1`
4984        // from costing an extra tick.
4985        let awaits_value = self.is_thenable(&value)?;
4986        if awaits_value {
4987            let awaited = match self.promise_resolve_value(value) {
4988                Ok(awaited) => awaited,
4989                Err(Signal::Throw(reason)) => {
4990                    self.reject_promise(promise, reason);
4991                    return Ok(());
4992                }
4993                Err(other) => return Err(other),
4994            };
4995            let Value::Object(awaited) = awaited else {
4996                return Ok(());
4997            };
4998            // A rejected yield throws *at the yield* inside the body, so the rejection
4999            // resumes the generator rather than the method's promise.
5000            let answer = JsObject::function(
5001                self.heap,
5002                Some(self.realm.function_proto.clone()),
5003                Callable::YieldResult {
5004                    promise: promise.clone(),
5005                    done,
5006                },
5007            );
5008            let raise = JsObject::function(
5009                self.heap,
5010                Some(self.realm.function_proto.clone()),
5011                Callable::GeneratorResume {
5012                    generator: generator.clone(),
5013                    promise: promise.clone(),
5014                    kind: ResumeKind::Throw,
5015                },
5016            );
5017            self.perform_then(
5018                &awaited,
5019                Some(Value::Object(answer)),
5020                Some(Value::Object(raise)),
5021            )?;
5022            return Ok(());
5023        }
5024        let result = if ready {
5025            // `yield*` handed back the inner iterator's own result object.
5026            value
5027        } else {
5028            self.iterator_result(value, done)?
5029        };
5030        self.fulfill_promise(promise, result);
5031        Ok(())
5032    }
5033
5034    /// The `{value, done}` object an iterator method answers with.
5035    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
5036        let result = self.new_object(Some(self.realm.object_proto.clone()));
5037        result.define_data("value", value);
5038        result.define_data("done", Value::Bool(done));
5039        Ok(Value::Object(result))
5040    }
5041
5042    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
5043    fn step_generator(
5044        &mut self,
5045        state: &mut GeneratorState,
5046        kind: ResumeKind,
5047        value: Value,
5048    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
5049        match state.phase {
5050            GeneratorPhase::Executing => {
5051                return Err(self.type_error("cannot invoke a running generator"));
5052            }
5053            GeneratorPhase::Completed => {
5054                // A finished generator answers every resumption without running.
5055                return Ok(match kind {
5056                    ResumeKind::Throw => return Err(Signal::Throw(value)),
5057                    ResumeKind::Return => (value, true, false, None),
5058                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
5059                });
5060            }
5061            GeneratorPhase::SuspendedStart => {
5062                if kind != ResumeKind::Next && kind != ResumeKind::Start {
5063                    // The body never started, so there is nothing to unwind or return
5064                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
5065                    state.frame = None;
5066                    state.phase = GeneratorPhase::Completed;
5067                    return Ok(match kind {
5068                        ResumeKind::Throw => return Err(Signal::Throw(value)),
5069                        _ => (value, true, false, None),
5070                    });
5071                }
5072            }
5073            GeneratorPhase::SuspendedYield => {}
5074        }
5075
5076        let Some(mut frame) = state.frame.take() else {
5077            return Ok((Value::Undefined, true, false, None));
5078        };
5079        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
5080        // number that says which method resumed it; the emitted `if_false` branches on
5081        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
5082        let mut raised = None;
5083        match kind {
5084            ResumeKind::Next | ResumeKind::Start => {
5085                if state.phase == GeneratorPhase::SuspendedYield {
5086                    frame.stack.push(value);
5087                    // An `await` resumes with its value alone; only a `yield` gets the
5088                    // magic number that says which of `next`/`return` resumed it.
5089                    if !state.parked_on_await {
5090                        frame.stack.push(Value::Int(RESUME_NEXT));
5091                    }
5092                }
5093            }
5094            ResumeKind::Return => {
5095                // A `return` on a not-yet-started generator is handled above, so this is
5096                // always a real resumption.
5097                frame.stack.push(value);
5098                frame.stack.push(Value::Int(RESUME_RETURN));
5099            }
5100            ResumeKind::Throw => raised = Some(value),
5101        }
5102        state.phase = GeneratorPhase::Executing;
5103
5104        let depth = self.frames.len();
5105        self.frames.push(frame);
5106        // A `throw` unwinds from where the frame parked, exactly as if the exception had
5107        // happened at the `yield`.
5108        if let Some(exception) = raised {
5109            if self.catch_here(exception.clone()).is_none() {
5110                self.frames.pop();
5111                state.phase = GeneratorPhase::Completed;
5112                return Err(Signal::Throw(exception));
5113            }
5114        }
5115
5116        // Only the generator's *own* frame ends the generator. The body may call ordinary
5117        // functions, and those push frames of their own: a `Step::Return` from one of them
5118        // is a nested call finishing, not the generator completing. Miscounting that is
5119        // silent — the generator reports the callee's value as its own result and marks
5120        // itself done — so the depth comparison is load-bearing, not defensive.
5121        let own_frame = depth + 1;
5122        loop {
5123            match self.step() {
5124                Ok(Step::Continue) => {}
5125                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
5126                    let mut frame = self.frames.pop().expect("a frame is live");
5127                    // `yield` left the value on the stack; `initial_yield` left nothing.
5128                    let yielded = if reason == SuspendKind::Initial {
5129                        Value::Undefined
5130                    } else {
5131                        frame.stack.pop().unwrap_or(Value::Undefined)
5132                    };
5133                    state.frame = Some(frame);
5134                    state.parked_on_await = reason == SuspendKind::Await;
5135                    state.phase = if reason == SuspendKind::Initial {
5136                        GeneratorPhase::SuspendedStart
5137                    } else {
5138                        GeneratorPhase::SuspendedYield
5139                    };
5140                    // `yield*` hands the inner iterator's own result object straight
5141                    // back, so the caller sees one `{value, done}` rather than a nested
5142                    // one — which is why the third field says "already a result".
5143                    return Ok((
5144                        yielded,
5145                        false,
5146                        reason == SuspendKind::YieldStar,
5147                        Some(reason),
5148                    ));
5149                }
5150                Ok(Step::Suspend(_)) => {
5151                    // A `yield` in a frame other than the generator's would mean a
5152                    // generator body entered as an ordinary call, which
5153                    // `call_or_push` prevents.
5154                    self.unwind_to(depth);
5155                    state.phase = GeneratorPhase::Completed;
5156                    return Err(Signal::Throw(self.make_error(
5157                        "InternalError",
5158                        "a generator body ran as an ordinary call",
5159                    )));
5160                }
5161                Ok(Step::Return(value)) => {
5162                    self.frames.pop();
5163                    if self.frames.len() > depth {
5164                        // A nested call finished: hand the value back to its caller and
5165                        // keep running the generator body.
5166                        self.frames
5167                            .last_mut()
5168                            .expect("a caller is live")
5169                            .stack
5170                            .push(value);
5171                        continue;
5172                    }
5173                    state.phase = GeneratorPhase::Completed;
5174                    // The reference closes the generator's closure variables here; ours
5175                    // live in cells the frame owned, which the drop below releases.
5176                    return Ok((value, true, false, None));
5177                }
5178                Err(Signal::Throw(exception)) => {
5179                    // The frame that threw gets the first chance to catch, exactly as in
5180                    // the ordinary call loop; a frame above the generator's is popped and
5181                    // the exception carries on down.
5182                    let exception = exception;
5183                    loop {
5184                        if self.frames.len() <= depth {
5185                            // The generator's own frame is gone, so nothing here caught it.
5186                            state.phase = GeneratorPhase::Completed;
5187                            return Err(Signal::Throw(exception));
5188                        }
5189                        if self.catch_here(exception.clone()).is_some() {
5190                            break;
5191                        }
5192                        self.frames.pop();
5193                    }
5194                }
5195                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
5196            }
5197        }
5198    }
5199
5200    /// Pop frames until `depth` are left.
5201    fn unwind_to(&mut self, depth: usize) {
5202        self.frames.truncate(depth);
5203    }
5204    fn call_or_push(
5205        &mut self,
5206        callee: Value,
5207        this: Value,
5208        args: Vec<Value>,
5209    ) -> JsResult<Option<Value>> {
5210        if let Value::Object(function) = &callee
5211            && let Some((code, env)) = bytecode_of(function)
5212        {
5213            // Calling a generator function does not run anything: it captures the
5214            // arguments in a frame and hands back the generator object.
5215            if code.code.kind.is_generator() {
5216                return self.new_generator(callee, this, args).map(Some);
5217            }
5218            // An async function answers a promise and runs its body as a coroutine, so it
5219            // takes the same path as a plain call into it.
5220            if code.code.kind.is_async() {
5221                return self.new_async_function(callee, this, args).map(Some);
5222            }
5223            self.push_frame(code, env, this, args, callee)?;
5224            return Ok(None);
5225        }
5226        self.call_value(callee, this, args).map(Some)
5227    }
5228
5229    /// `new callee(args)`.
5230    ///
5231    /// A constructor differs from a plain call in three ways: it gets a fresh object
5232    /// as `this` whose prototype is the constructor's `prototype` property, its
5233    /// return value is *replaced* by that object unless it returns an object itself,
5234    /// and a native constructor is expected to initialise the object it is given
5235    /// rather than build one.
5236    pub fn construct(
5237        &mut self,
5238        callee: Value,
5239        new_target: Value,
5240        args: Vec<Value>,
5241    ) -> JsResult<Value> {
5242        // `new` on a bound function constructs its *target*, prepending the arguments
5243        // the bind fixed and ignoring the bound `this` — a bound function is a
5244        // constructor only when its target is one, and `new` always makes a fresh
5245        // object of the target's prototype rather than reusing the bound receiver.
5246        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
5247        // ran the body with `this === null` and threw on `this.x = a`.
5248        let mut callee = callee;
5249        let mut new_target = new_target;
5250        let mut args = args;
5251        loop {
5252            let Some(object) = callee.as_object().cloned() else {
5253                return Err(Signal::Throw(
5254                    self.make_error("TypeError", "not a constructor"),
5255                ));
5256            };
5257            // A proxy of a function constructs through its `construct` trap, and the
5258            // trap's answer is the result directly — no fresh object is made here.
5259            if object.proxy_state().is_some() {
5260                return match self.proxy_construct(&object, args, &new_target)? {
5261                    Some(result) => Ok(result),
5262                    None => Err(Signal::Throw(
5263                        self.make_error("TypeError", "proxy target is not a constructor"),
5264                    )),
5265                };
5266            }
5267            // A function can opt out of `[[Construct]]` outright. `Symbol` does: there is
5268            // no wrapper object to build, and `new Symbol()` is a `TypeError` naming it.
5269            if object
5270                .own_property("_not_a_constructor")
5271                .and_then(|property| property.value)
5272                .is_some_and(|value| value.to_boolean())
5273            {
5274                let name = object
5275                    .own_property("name")
5276                    .and_then(|property| property.value)
5277                    .map(|value| value.to_js_string())
5278                    .unwrap_or_default();
5279                return Err(Signal::Throw(
5280                    self.make_error("TypeError", &format!("{name} is not a constructor")),
5281                ));
5282            }
5283            // A generator function has no `[[Construct]]`, and the reference names it in
5284            // the message: `new (function* G(){})()` reports "G is not a constructor".
5285            if object.with(|data| match &data.kind {
5286                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
5287                    code.code.kind.is_generator()
5288                }
5289                _ => false,
5290            }) {
5291                let name = object
5292                    .own_property("name")
5293                    .and_then(|property| property.value)
5294                    .map(|value| value.to_js_string())
5295                    .unwrap_or_default();
5296                return Err(Signal::Throw(
5297                    self.make_error("TypeError", &format!("{name} is not a constructor")),
5298                ));
5299            }
5300            let bound = object.with(|data| match &data.kind {
5301                ObjectKind::Function(Callable::Bound {
5302                    target,
5303                    args: leading,
5304                    ..
5305                }) => Some((target.clone(), leading.clone())),
5306                _ => None,
5307            });
5308            let Some((target, leading)) = bound else {
5309                // Not a bound function, so this object is the callee. §7.2.4
5310                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
5311                // refusals above cover only the built-ins the reference also refuses by
5312                // name. Everything else — a method, an arrow, an async function — has no
5313                // `[[Construct]]` either, and answering "yes" here made
5314                // `new (Array.prototype.map)` build an object instead of throwing.
5315                if !object.is_constructor() {
5316                    let name = object
5317                        .own_property("name")
5318                        .and_then(|property| property.value)
5319                        .map(|value| value.to_js_string())
5320                        .unwrap_or_default();
5321                    return Err(Signal::Throw(
5322                        self.make_error("TypeError", &format!("{name} is not a constructor")),
5323                    ));
5324                }
5325                break;
5326            };
5327            let mut all = leading;
5328            all.extend(args);
5329            args = all;
5330            // A bound function that is its own `new.target` stands in for its target:
5331            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
5332            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
5333            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
5334                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
5335                _ => false,
5336            };
5337            if same_wrapper {
5338                new_target = target.clone();
5339            }
5340            callee = target;
5341        }
5342        let Value::Object(function) = &callee else {
5343            unreachable!("the loop above only breaks on an object");
5344        };
5345        // The fresh object's prototype comes from `new.target`, not from the callee: a
5346        // derived constructor reaches here through `super()`, and the instance must be a
5347        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
5348        // an object inheriting `D.prototype` rather than `C.prototype`.
5349        let prototype_source = match new_target.as_object() {
5350            Some(target) => target.clone(),
5351            None => function.clone(),
5352        };
5353        // A native constructor builds its own instance, through `new_ctor_instance`, once it
5354        // has validated its arguments. Pre-building one here would read
5355        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
5356        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
5357        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
5358        let is_native = function.native_creates_own_instance();
5359        let this = if is_native {
5360            Value::Undefined
5361        } else {
5362            let prototype = self.get_property(&prototype_source, "prototype")?;
5363            let prototype = match prototype {
5364                Some(Value::Object(proto)) => Some(proto),
5365                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
5366                // object, the answer is the realm's *intrinsic* prototype for this
5367                // constructor, not `%Object.prototype%`.
5368                _ => {
5369                    let fallback = self.get_property(function, "prototype")?;
5370                    match fallback {
5371                        Some(Value::Object(proto)) => Some(proto),
5372                        _ => Some(self.realm.object_proto.clone()),
5373                    }
5374                }
5375            };
5376            Value::Object(self.new_object(prototype))
5377        };
5378        // `new.target` inside the body is the constructor that was written, so a bound
5379        // function's target sees itself rather than the bound wrapper.
5380        self.pending_new_target = Some(new_target);
5381        let result = self.call_value(callee, this.clone(), args)?;
5382        self.pending_new_target = None;
5383        // A constructor that returns an object overrides `this`; any other return
5384        // value (including `undefined`) is ignored.
5385        Ok(match result {
5386            Value::Object(_) => result,
5387            _ => this,
5388        })
5389    }
5390
5391    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
5392    ///
5393    /// The error classes themselves arrive with the builtins milestone; what
5394    /// matters here is that the thrown value stringifies the way a script printing
5395    /// the caught value expects.
5396    pub fn make_error(&self, name: &str, message: &str) -> Value {
5397        let proto = self
5398            .realm
5399            .errors
5400            .get(name)
5401            .map(|constructor| self.prototype_of(constructor))
5402            .unwrap_or_else(|| self.realm.error_proto.clone());
5403        let error = self.new_object(Some(proto));
5404        // `name` and `message` are own properties of the instance, which is what
5405        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
5406        // `Error`.
5407        error.define(
5408            "name",
5409            Property::with_attributes(self.string(name), true, false),
5410        );
5411        error.define(
5412            "message",
5413            Property::with_attributes(self.string(message), true, false),
5414        );
5415        // The trace is captured where the error is *made*, which is where the reference
5416        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
5417        // way out, so a caught engine error already has its stack even if the handler
5418        // never rethrows it.
5419        self.add_stack(&error);
5420        Value::Object(error)
5421    }
5422
5423    /// Give an error object its `stack` property, from the current frame stack.
5424    ///
5425    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
5426    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
5427    /// `stack` a script set, is not rewritten.
5428    pub fn add_stack(&self, object: &Gc<JsObject>) {
5429        self.add_stack_skipping(object, 0);
5430    }
5431
5432    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
5433    ///
5434    /// An `Error` constructor passes 1: the reference builds those traces with
5435    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
5436    /// constructor itself, while a `RangeError` raised inside `toISOString` does
5437    /// report `at toISOString (native)`.
5438    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
5439        if object.has_own("stack") {
5440            return;
5441        }
5442        let trace = self.stack_trace_skipping(skip);
5443        let text = self.string(trace);
5444        object.define("stack", Property::with_attributes(text, true, true));
5445    }
5446
5447    /// The function object currently being called, if any.
5448    ///
5449    /// A native function is a bare `fn` pointer, so it cannot capture which class
5450    /// it belongs to; it reads that from the callee instead. This is also what a
5451    /// stack trace would use.
5452    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
5453        match &self.frames.last()?.callee {
5454            Value::Object(object) => Some(object.clone()),
5455            _ => None,
5456        }
5457    }
5458
5459    /// The `prototype` property of a constructor, falling back to
5460    /// `Object.prototype` for anything that is not shaped like one.
5461    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
5462        constructor
5463            .own_property("prototype")
5464            .and_then(|property| property.value)
5465            .and_then(|value| value.as_object().cloned())
5466            .unwrap_or_else(|| self.realm.object_proto.clone())
5467    }
5468
5469    /// Throw a `TypeError` carrying `message`.
5470    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
5471        Signal::Throw(self.make_error("TypeError", message.as_ref()))
5472    }
5473
5474    /// Throw a `RangeError` carrying `message`.
5475    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
5476        Signal::Throw(self.make_error("RangeError", message.as_ref()))
5477    }
5478
5479    /// The `ReferenceError` a read of an uninitialised binding raises.
5480    /// The name of the binding `slot` refers to, for an error message.
5481    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
5482        match kind {
5483            VarSlot::Loc => self
5484                .frame()
5485                .code
5486                .code
5487                .vars
5488                .get(slot)
5489                .map(|v| v.name.clone()),
5490            VarSlot::Closure => self
5491                .frame()
5492                .code
5493                .code
5494                .closure_vars
5495                .get(slot)
5496                .map(|c| c.name.clone()),
5497        }
5498        .unwrap_or_default()
5499    }
5500
5501    /// Whether `slot` names a `const` binding, which rejects every store after its
5502    /// initialiser.
5503    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
5504        match kind {
5505            VarSlot::Loc => self
5506                .frame()
5507                .code
5508                .code
5509                .vars
5510                .get(slot)
5511                .is_some_and(|v| v.is_const),
5512            VarSlot::Closure => self
5513                .frame()
5514                .code
5515                .code
5516                .closure_vars
5517                .get(slot)
5518                .is_some_and(|c| c.is_const),
5519        }
5520    }
5521
5522    /// The `TypeError` a store to a `const` binding raises.
5523    ///
5524    /// `const` is enforced here rather than at compile time because the binding can be
5525    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
5526    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
5527    /// both halves of what "checked store" means: the dead zone is over, and the
5528    /// binding is writable.
5529    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
5530        let name = self.binding_name(slot, kind);
5531        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5532    }
5533
5534    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
5535        let name = match kind {
5536            VarSlot::Loc => self
5537                .frame()
5538                .code
5539                .code
5540                .vars
5541                .get(slot)
5542                .map(|v| v.name.clone()),
5543            VarSlot::Closure => self
5544                .frame()
5545                .code
5546                .code
5547                .closure_vars
5548                .get(slot)
5549                .map(|c| c.name.clone()),
5550        }
5551        .unwrap_or_default();
5552        Signal::Throw(self.make_error(
5553            "ReferenceError",
5554            &format!("cannot access '{name}' before initialization"),
5555        ))
5556    }
5557
5558    fn throw_reference(&self, name: &str) -> Signal {
5559        Signal::Throw(self.make_error("ReferenceError", &format!("{name} is not defined")))
5560    }
5561
5562    // -- the instruction loop -----------------------------------------------
5563
5564    fn step(&mut self) -> JsResult<Step> {
5565        let pc = self.frame().pc;
5566        let code = self.frame().code.clone();
5567        let bytes = &code.code.code;
5568        if pc >= bytes.len() {
5569            return Ok(Step::Return(Value::Undefined));
5570        }
5571        let Some(decoded) = decode(bytes, pc) else {
5572            return Err(Signal::Throw(
5573                self.make_error("InternalError", "undecodable bytecode"),
5574            ));
5575        };
5576        let (op, a, b, next) = decoded;
5577        self.frame_mut().at = pc;
5578        self.frame_mut().pc = next;
5579        self.execute_instruction(op, a, b, next)
5580    }
5581
5582    fn push(&mut self, value: Value) {
5583        self.frame_mut().stack.push(value);
5584    }
5585
5586    fn pop(&mut self) -> Value {
5587        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
5588    }
5589
5590    fn pop_n(&mut self, count: usize) -> Vec<Value> {
5591        let frame = self.frame_mut();
5592        let start = frame.stack.len().saturating_sub(count);
5593        frame.stack.split_off(start)
5594    }
5595
5596    fn peek(&self, back: usize) -> Value {
5597        let frame = self.frame();
5598        frame
5599            .stack
5600            .get(frame.stack.len().wrapping_sub(1 + back))
5601            .cloned()
5602            .unwrap_or(Value::Undefined)
5603    }
5604
5605    #[allow(clippy::too_many_lines)]
5606    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
5607        use Opcode::*;
5608        match op {
5609            // -- constants and stack shuffling -----------------------------
5610            Nop => {}
5611            PushMinus1 => self.push(Value::Int(-1)),
5612            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
5613                let value = match op {
5614                    Push0 => 0,
5615                    Push1 => 1,
5616                    Push2 => 2,
5617                    Push3 => 3,
5618                    Push4 => 4,
5619                    Push5 => 5,
5620                    Push6 => 6,
5621                    _ => 7,
5622                };
5623                self.push(Value::Int(value));
5624            }
5625            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
5626            PushBigintI32 => {
5627                // The immediate form of a `BigInt` literal; the reference has the same
5628                // split between this and a constant-pool entry.
5629                let value = crate::bigint::BigInt::from_i64(a as i64);
5630                self.push(self.bigint(value));
5631            }
5632            PushTrue => self.push(Value::Bool(true)),
5633            PushFalse => self.push(Value::Bool(false)),
5634            PushEmptyString => self.push(self.string("")),
5635            Undefined => self.push(Value::Undefined),
5636            Null => self.push(Value::Null),
5637            Object => {
5638                let proto = self.realm.object_proto.clone();
5639                self.push(Value::Object(self.new_object(Some(proto))));
5640            }
5641            PushThis => {
5642                let this = self.frame().this.clone();
5643                self.push(this);
5644            }
5645            PushConst | PushConst8 => {
5646                let value = self.constant(a as usize)?;
5647                self.push(value);
5648            }
5649            PushAtomValue => {
5650                let text = self.atom_text(a as usize);
5651                self.push(self.string(text));
5652            }
5653            Dup => {
5654                let value = self.peek(0);
5655                self.push(value);
5656            }
5657            Swap => {
5658                // `a b -> b a`
5659                let bottom = self.pop();
5660                let top = self.pop();
5661                self.push(bottom);
5662                self.push(top);
5663            }
5664            Perm3 => {
5665                // `a b c -> b a c`, the reference's reordering for a spread method
5666                // call: `obj func array` becomes the `func this array` that `apply`
5667                // takes.
5668                let c = self.pop();
5669                let b = self.pop();
5670                let a = self.pop();
5671                self.push(b);
5672                self.push(a);
5673                self.push(c);
5674            }
5675            Dup1 => {
5676                let value = self.peek(1);
5677                self.push(value);
5678            }
5679            Drop => {
5680                self.pop();
5681            }
5682            Nip => {
5683                // `a b -> b`
5684                let top = self.pop();
5685                self.pop();
5686                self.push(top);
5687            }
5688            Perm4 => {
5689                // `obj prop a b -> a obj prop b`, the reference's reordering for a
5690                // postfix update of a computed element: it puts the *old* value
5691                // underneath the receiver and key so `put_array_el` can consume them
5692                // and leave the old value as the expression's result.
5693                let d = self.pop();
5694                let c = self.pop();
5695                let b = self.pop();
5696                let a = self.pop();
5697                self.push(c);
5698                self.push(a);
5699                self.push(b);
5700                self.push(d);
5701            }
5702            Insert2 => {
5703                // `obj a -> a obj a`
5704                let value = self.pop();
5705                let object = self.pop();
5706                self.push(value.clone());
5707                self.push(object);
5708                self.push(value);
5709            }
5710            Insert3 => {
5711                // `obj prop a -> a obj prop a`
5712                let value = self.pop();
5713                let key = self.pop();
5714                let object = self.pop();
5715                self.push(value.clone());
5716                self.push(object);
5717                self.push(key);
5718                self.push(value);
5719            }
5720            Swap2 => {
5721                // `a b c d -> c d a b`
5722                let d = self.pop();
5723                let c = self.pop();
5724                let b = self.pop();
5725                let a = self.pop();
5726                self.push(c);
5727                self.push(d);
5728                self.push(a);
5729                self.push(b);
5730            }
5731            Rot3l => {
5732                // `x a b -> a b x`
5733                let b = self.pop();
5734                let a = self.pop();
5735                let x = self.pop();
5736                self.push(a);
5737                self.push(b);
5738                self.push(x);
5739            }
5740            Rot3r => {
5741                // `a b c -> c a b`
5742                let c = self.pop();
5743                let b = self.pop();
5744                let a_value = self.pop();
5745                self.push(c);
5746                self.push(a_value);
5747                self.push(b);
5748            }
5749
5750            Rest => {
5751                // `...rest` in a parameter list: the arguments from index `a` on, as a
5752                // real array. It takes nothing off the stack — the arguments are in the
5753                // frame, not on it.
5754                let frame = self.frame();
5755                let from = a as usize;
5756                let collected: Vec<Value> = frame.passed.iter().skip(from).cloned().collect();
5757                let array = self.new_array(collected);
5758                self.push(Value::Object(array));
5759            }
5760
5761            // -- slots ------------------------------------------------------
5762            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
5763                let slot = self.slot_operand(op, a);
5764                let value = self.get_loc(slot);
5765                self.push(value);
5766            }
5767            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
5768                let slot = self.slot_operand(op, a);
5769                let value = self.pop();
5770                self.put_loc(slot, value);
5771            }
5772            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
5773                let slot = self.slot_operand(op, a);
5774                let value = self.pop();
5775                self.put_loc(slot, value.clone());
5776                self.push(value);
5777            }
5778            // The `_check` forms are the temporal dead zone: they throw when the
5779            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
5780            // *reads*, so only the two writes may pop — mishandling that quietly
5781            // consumes the value the caller pushed just before.
5782            GetLocCheck => {
5783                let slot = self.slot_operand(op, a);
5784                let value = self.get_loc(slot);
5785                if matches!(value, Value::Uninitialized) {
5786                    return Err(self.dead_zone(slot, VarSlot::Loc));
5787                }
5788                self.push(value);
5789            }
5790            PutLocCheck | SetLocCheck => {
5791                let slot = self.slot_operand(op, a);
5792                let value = self.pop();
5793                if matches!(value, Value::Uninitialized) {
5794                    return Err(self.dead_zone(slot, VarSlot::Loc));
5795                }
5796                // The initialiser goes through `put_loc`, not this, so any store that
5797                // reaches here is a later assignment — which a `const` refuses.
5798                if self.is_read_only(slot, VarSlot::Loc) {
5799                    return Err(self.read_only(slot, VarSlot::Loc));
5800                }
5801                if op == SetLocCheck {
5802                    self.put_loc(slot, value.clone());
5803                    self.push(value);
5804                } else {
5805                    self.put_loc(slot, value);
5806                }
5807            }
5808            PutLocCheckInit => {
5809                // The one store that *initialises* a lexical slot: `this` in a derived
5810                // constructor, which only exists after `super()` has run. A second
5811                // initialisation is the error the reference reports as
5812                // "'this' can be initialized only once".
5813                let slot = self.slot_operand(op, a);
5814                let value = self.pop();
5815                if !matches!(self.get_loc(slot), Value::Uninitialized) {
5816                    return Err(Signal::Throw(self.make_error(
5817                        "ReferenceError",
5818                        "'this' can be initialized only once",
5819                    )));
5820                }
5821                self.put_loc(slot, value);
5822            }
5823            CheckCtor => {
5824                // A class constructor may only run under `new`, which is what makes
5825                // `class A {}; A()` a TypeError.
5826                if matches!(self.frame().new_target, Value::Undefined) {
5827                    return Err(Signal::Throw(self.make_error(
5828                        "TypeError",
5829                        "class constructors must be invoked with 'new'",
5830                    )));
5831                }
5832            }
5833            InitCtor => {
5834                // The body a derived class gets when it declares no constructor:
5835                // forward every argument to the parent constructor, keeping `new.target`.
5836                if matches!(self.frame().new_target, Value::Undefined) {
5837                    return Err(Signal::Throw(self.make_error(
5838                        "TypeError",
5839                        "class constructors must be invoked with 'new'",
5840                    )));
5841                }
5842                let Some(callee) = self.current_callee() else {
5843                    return Err(Signal::Throw(
5844                        self.make_error("TypeError", "no constructor to inherit from"),
5845                    ));
5846                };
5847                let parent = callee.proto().map_or(Value::Null, Value::Object);
5848                let new_target = self.frame().new_target.clone();
5849                let args = self.frame().passed.clone();
5850                let result = self.construct(parent, new_target, args)?;
5851                self.push(result);
5852            }
5853            SetLocUninitialized => {
5854                let slot = self.slot_operand(op, a);
5855                self.put_loc(slot, Value::Uninitialized);
5856            }
5857            CloseLoc => {
5858                // "Close" a binding: give it a *fresh* cell holding the current
5859                // value. Closures created before this point keep the old cell and the
5860                // ones created after see the new one, which is what makes every
5861                // iteration of `for (let i ...)` capture its own `i`, and what freezes
5862                // a block-scoped binding when the block ends.
5863                //
5864                // Clearing the slot instead (which this used to do) broke both: a
5865                // closure over a captured block variable read `undefined`, and a loop
5866                // terminated after one iteration.
5867                let slot = self.slot_operand(op, a);
5868                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
5869                if index >= 0 {
5870                    let current = self.frame().cells[index as usize].get();
5871                    let fresh = self.new_cell(current);
5872                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
5873                        *cell = fresh;
5874                    }
5875                }
5876            }
5877            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
5878                let slot = self.slot_operand(op, a);
5879                let value = self.get_arg(slot);
5880                self.push(value);
5881            }
5882            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
5883                let slot = self.slot_operand(op, a);
5884                let value = self.pop();
5885                self.put_arg(slot, value);
5886            }
5887            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
5888                let slot = self.slot_operand(op, a);
5889                let value = self.pop();
5890                self.put_arg(slot, value.clone());
5891                self.push(value);
5892            }
5893
5894            // -- closure variables ------------------------------------------
5895            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
5896                let slot = self.slot_operand(op, a);
5897                // A name a direct `eval` created shadows the binding the compiler chose.
5898                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
5899                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
5900                // and only a runtime lookup can know that.
5901                if let Some(cell) = self.eval_created_local(slot) {
5902                    self.push(cell.get());
5903                    return self.step();
5904                }
5905                let value = self.cell_value(slot)?;
5906                self.push(value);
5907            }
5908            GetVarRefCheck => {
5909                let slot = self.slot_operand(op, a);
5910                let value = self.cell_value(slot)?;
5911                if matches!(value, Value::Uninitialized) {
5912                    return Err(self.dead_zone(slot, VarSlot::Closure));
5913                }
5914                self.push(value);
5915            }
5916            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
5917                let slot = self.slot_operand(op, a);
5918                let value = self.pop();
5919                if let Some(cell) = self.eval_created_local(slot) {
5920                    cell.set(value);
5921                    return self.step();
5922                }
5923                // Same rule as `PutLocCheck`: a checked store to a captured binding
5924                // refuses a `const` once its initialiser has run.
5925                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
5926                    return Err(self.read_only(slot, VarSlot::Closure));
5927                }
5928                self.set_cell(slot, value)?;
5929            }
5930            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
5931                let slot = self.slot_operand(op, a);
5932                let value = self.pop();
5933                if let Some(cell) = self.eval_created_local(slot) {
5934                    cell.set(value.clone());
5935                    self.push(value);
5936                    return self.step();
5937                }
5938                self.set_cell(slot, value.clone())?;
5939                self.push(value);
5940            }
5941
5942            // -- globals ----------------------------------------------------
5943            GetVar => {
5944                let value = self.get_global(a as usize)?;
5945                self.push(value);
5946            }
5947            GetVarUndef => {
5948                let value = self
5949                    .get_global(a as usize)
5950                    .or_else(|_| Ok(Value::Undefined))?;
5951                self.push(value);
5952            }
5953            DeleteVar => {
5954                // `delete name` for a name that is not a declared binding. A lexical
5955                // global lives in the reference table and cannot be deleted; anything
5956                // reachable only as a property of the global object is *implicit* —
5957                // `x = 1` with no declaration — and goes away if it is configurable,
5958                // which is what `delete` on an implicit global answers.
5959                let name = self.atom_text(a as usize);
5960                let global = self.realm.global.clone();
5961                let deleted = if self.realm.globals.contains_key(&name) {
5962                    false
5963                } else if global.own_property(&name).is_some() {
5964                    self.delete_property(&global, &name)?
5965                } else {
5966                    true
5967                };
5968                self.push(Value::Bool(deleted));
5969            }
5970            PutVar => {
5971                let value = self.pop();
5972                self.put_global(a as usize, value)?;
5973            }
5974            PutVarInit => {
5975                let slot = a as usize;
5976                let value = self.pop();
5977                self.init_global(slot, value)?;
5978            }
5979
5980            // -- arithmetic -------------------------------------------------
5981            Add => self.binary_add()?,
5982            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
5983                let raw_right = self.pop();
5984                let raw_left = self.pop();
5985                // BigInt arithmetic is a separate path, and not only for the type of the
5986                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
5987                // rather than a silent conversion.
5988                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
5989                    let left = self.primitive_of(raw_left)?;
5990                    let right = self.primitive_of(raw_right)?;
5991                    let value = self.bigint_arithmetic(op, left, right)?;
5992                    self.push(value);
5993                } else {
5994                    let right = self.numeric(raw_right)?;
5995                    let left = self.numeric(raw_left)?;
5996                    self.push(arithmetic(op, left, right)?);
5997                }
5998            }
5999            Neg => {
6000                let raw = self.pop();
6001                match raw {
6002                    // A bigint negates exactly, however wide it is.
6003                    Value::BigInt(big) => {
6004                        let negated = big.negate();
6005                        self.push(self.bigint(negated));
6006                    }
6007                    other => {
6008                        let value = self.numeric(other)?;
6009                        self.push(negate(value));
6010                    }
6011                }
6012            }
6013            Plus => {
6014                let value = self.pop();
6015                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
6016                // unary plus is defined to produce a *number*, which a bigint cannot
6017                // become without loss. It used to fall through to `NaN`.
6018                if matches!(value, Value::BigInt(_)) {
6019                    return Err(self.type_error("cannot convert bigint to number"));
6020                }
6021                let numeric = self.numeric_of(value)?;
6022                self.push(numeric);
6023            }
6024            Inc => {
6025                let raw = self.pop();
6026                let (_, updated) = self.advance_numeric(raw, true)?;
6027                self.push(updated);
6028            }
6029            Dec => {
6030                let raw = self.pop();
6031                let (_, updated) = self.advance_numeric(raw, false)?;
6032                self.push(updated);
6033            }
6034            PostInc | PostDec => {
6035                // `x -> x x+1`: the *new* value ends up on top, so the store the
6036                // compiler emits right after (`put_var`) writes the incremented
6037                // one, while the old value stays underneath for the expression's
6038                // own result. Getting this backwards makes `i++` a no-op, which
6039                // turns `while (i < 3)` into an infinite loop.
6040                let raw = self.pop();
6041                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
6042                self.push(old);
6043                self.push(updated);
6044            }
6045            Not => {
6046                let raw = self.pop();
6047                match raw {
6048                    // `~x` on a bigint is `-x - 1`, exact at any width.
6049                    Value::BigInt(big) => {
6050                        let inverted = big.bitnot();
6051                        self.push(self.bigint(inverted));
6052                    }
6053                    other => {
6054                        let value = self.numeric(other)?;
6055                        self.push(Value::Int(!value.to_int32()));
6056                    }
6057                }
6058            }
6059            Lnot => {
6060                let value = self.pop();
6061                self.push(Value::Bool(!value.to_boolean()));
6062            }
6063
6064            // -- comparison -------------------------------------------------
6065            Lt | Lte | Gt | Gte => {
6066                let right = self.pop();
6067                let left = self.pop();
6068                let answer = self.relational(op, left, right);
6069                self.push(answer);
6070            }
6071            Eq | Neq => {
6072                let right = self.pop();
6073                let left = self.pop();
6074                let equal = self.abstract_equals(left, right)?;
6075                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
6076            }
6077            StrictEq => {
6078                let right = self.pop();
6079                let left = self.pop();
6080                self.push(Value::Bool(left.strict_equals(&right)));
6081            }
6082            StrictNeq => {
6083                let right = self.pop();
6084                let left = self.pop();
6085                self.push(Value::Bool(!left.strict_equals(&right)));
6086            }
6087            IsUndefined => {
6088                // `=== undefined`, which is what a destructuring default tests. It is
6089                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
6090                let value = self.pop();
6091                self.push(Value::Bool(matches!(value, Value::Undefined)));
6092            }
6093            IsUndefinedOrNull => {
6094                let value = self.pop();
6095                self.push(Value::Bool(value.is_nullish()));
6096            }
6097            Typeof => {
6098                let value = self.pop();
6099                self.push(self.string(value.type_of()));
6100            }
6101            ToObject => {
6102                // A destructuring *object* pattern starts here, which is why
6103                // `var {} = null` throws. Only `undefined` and `null` are refused; a
6104                // primitive is boxed.
6105                let value = self.pop();
6106                let object = self.object_from(&value)?;
6107                self.push(Value::Object(object));
6108            }
6109            Instanceof => {
6110                let constructor = self.pop();
6111                let object = self.pop();
6112                let answer = self.instance_of(&object, &constructor)?;
6113                self.push(Value::Bool(answer));
6114            }
6115            In => {
6116                let object = self.pop();
6117                let key = self.pop();
6118                let answer = self.has_property(&key, &object)?;
6119                self.push(Value::Bool(answer));
6120            }
6121
6122            // -- control flow -----------------------------------------------
6123            Goto | Goto8 | Goto16 => {
6124                self.frame_mut().pc = a as usize;
6125            }
6126            IfTrue | IfTrue8 => {
6127                let value = self.pop();
6128                if value.to_boolean() {
6129                    self.frame_mut().pc = a as usize;
6130                }
6131            }
6132            IfFalse | IfFalse8 => {
6133                let value = self.pop();
6134                if !value.to_boolean() {
6135                    self.frame_mut().pc = a as usize;
6136                }
6137            }
6138            Catch => {
6139                // Pushes the handler target onto the value stack; `unwind` finds it.
6140                self.push(Value::CatchOffset(a));
6141            }
6142            Gosub => {
6143                self.push(Value::ReturnAddress(next as u32));
6144                self.frame_mut().pc = a as usize;
6145            }
6146            Ret => {
6147                let value = self.pop();
6148                match value {
6149                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
6150                    _ => {
6151                        return Err(Signal::Throw(
6152                            self.make_error("InternalError", "invalid return address"),
6153                        ));
6154                    }
6155                }
6156            }
6157            NipCatch => {
6158                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
6159                // including the marker, keeping the top value.
6160                let top = self.pop();
6161                loop {
6162                    match self.pop() {
6163                        Value::CatchOffset(_) | Value::Undefined => break,
6164                        _ => {}
6165                    }
6166                    if self.frame().stack.is_empty() {
6167                        break;
6168                    }
6169                }
6170                self.push(top);
6171            }
6172            Throw => {
6173                let value = self.pop();
6174                return Err(Signal::Throw(value));
6175            }
6176            ThrowError => {
6177                let name = self.atom_text(a as usize);
6178                let (class, message) = match b {
6179                    0 => ("TypeError", format!("'{name}' is read-only")),
6180                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
6181                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
6182                    // `delete super.x` is a syntax-level mistake the reference reports
6183                    // with this wording, not a property-access failure.
6184                    3 => (
6185                        "ReferenceError",
6186                        "unsupported reference to 'super'".to_string(),
6187                    ),
6188                    4 => (
6189                        "TypeError",
6190                        "iterator does not have a throw method".to_string(),
6191                    ),
6192                    5 => (
6193                        "ReferenceError",
6194                        "invalid assignment left-hand side".to_string(),
6195                    ),
6196                    _ => ("TypeError", format!("invalid operation on '{name}'")),
6197                };
6198                return Err(Signal::Throw(self.make_error(class, &message)));
6199            }
6200            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
6201            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
6202            YieldStar | AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
6203            Await => return Ok(Step::Suspend(SuspendKind::Await)),
6204            ReturnAsync => {
6205                // The reference's `return_async` returns `undefined` and lets the resume
6206                // machinery pick the real value off `sp[-1]`, which is how it tells a
6207                // completion from a suspension. Carrying the value explicitly says the
6208                // same thing without the implicit stack slot.
6209                let value = self.pop();
6210                return Ok(Step::Return(value));
6211            }
6212            Return => {
6213                let value = self.pop();
6214                return Ok(Step::Return(value));
6215            }
6216            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
6217
6218            // -- calls ------------------------------------------------------
6219            Call | Call0 | Call1 | Call2 | Call3 => {
6220                let argc = self.argc_operand(op, a);
6221                let args = self.pop_n(argc);
6222                let callee = self.pop();
6223                // A plain call has no receiver; the callee decides what to do with
6224                // `undefined` (a sloppy function substitutes the global object).
6225                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
6226                    self.push(result);
6227                }
6228            }
6229            CallConstructor => {
6230                // `constructor this_obj args… -> object`. The duplicated
6231                // constructor is `new.target`; this milestone does not expose it,
6232                // so the extra copy is simply consumed here.
6233                let argc = a as usize;
6234                let args = self.pop_n(argc);
6235                let new_target = self.pop();
6236                let callee = self.pop();
6237                let result = self.construct(callee, new_target, args)?;
6238                self.push(result);
6239            }
6240            CallMethod => {
6241                let argc = a as usize;
6242                let args = self.pop_n(argc);
6243                let callee = self.pop();
6244                let this = self.pop();
6245                if let Some(result) = self.call_or_push(callee, this, args)? {
6246                    self.push(result);
6247                }
6248            }
6249            Apply => {
6250                // `func this array -> result`, the spread-call form: the compiler
6251                // builds one array of arguments, and all that is left here is to
6252                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
6253                let array = self.pop();
6254                let this = self.pop();
6255                let callee = self.pop();
6256                let args = self.array_like_to_args(&array)?;
6257                if a & 1 != 0 {
6258                    let result = self.construct(callee, this, args)?;
6259                    self.push(result);
6260                } else if let Some(result) = self.call_or_push(callee, this, args)? {
6261                    self.push(result);
6262                }
6263            }
6264            TailCall | TailCallMethod => {
6265                // `tail_call` is `call` whose result is returned immediately — the
6266                // reference jumps straight to `done` instead of storing the value and
6267                // running on. The callee still gets its own frame, so deep tail
6268                // recursion hits the stack limit exactly like plain recursion does;
6269                // marking this frame lets the return path unwind without needing
6270                // instructions after the call.
6271                let argc = if op == TailCallMethod {
6272                    a as usize
6273                } else {
6274                    self.argc_operand(op, a)
6275                };
6276                let args = self.pop_n(argc);
6277                let callee = self.pop();
6278                let this = if op == TailCallMethod {
6279                    self.pop()
6280                } else {
6281                    Value::Undefined
6282                };
6283                if let Value::Object(function) = &callee
6284                    && let Some((code, env)) = bytecode_of(function)
6285                {
6286                    // A generator or async body is not run here at all: calling it only
6287                    // *creates* the generator/coroutine, so it must not inherit this
6288                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
6289                    // onto `f`'s frame, and the first `yield`/`await` then reported
6290                    // "a generator body ran as an ordinary call".
6291                    if code.code.kind.is_generator() || code.code.kind.is_async() {
6292                        let value = self.call_value(callee, this, args)?;
6293                        return Ok(Step::Return(value));
6294                    }
6295                    self.frame_mut().tail = true;
6296                    self.push_frame(code, env, this, args, callee)?;
6297                    return Ok(Step::Continue);
6298                }
6299                // A native callee has no frame to reuse, so its value is simply
6300                // returned.
6301                let value = self.call_value(callee, this, args)?;
6302                return Ok(Step::Return(value));
6303            }
6304
6305            // -- objects ----------------------------------------------------
6306            SpecialObject => {
6307                let value = self.special_object(a)?;
6308                self.push(value);
6309            }
6310            GetLength => {
6311                // `get_length` is the `.length` read; an array and a string answer
6312                // from their own length, anything else from the property.
6313                let target = self.pop();
6314                let value = match &target {
6315                    Value::Object(object) => match object.array_length() {
6316                        Some(length) => crate::object::length_value(length),
6317                        None => self.read_field(&target, "length")?,
6318                    },
6319                    Value::String(text) => Value::Int(text.utf16_len() as i32),
6320                    _ => self.read_field(&target, "length")?,
6321                };
6322                self.push(value);
6323            }
6324            GetField | GetField2 => {
6325                let object = self.pop();
6326                let key = self.atom_text(a as usize);
6327                let value = self.read_field(&object, &key)?;
6328                if op == GetField2 {
6329                    self.push(object);
6330                }
6331                self.push(value);
6332            }
6333            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
6334                let key = self.pop();
6335                let object = self.pop();
6336                let key = self.propkey(&key);
6337                let value = self.read_field_key(&object, &key)?;
6338                if matches!(op, GetArrayEl2 | GetArrayEl3) {
6339                    self.push(object);
6340                }
6341                if op == GetArrayEl3 {
6342                    // The key goes back in its *value* form, which the compiler stores
6343                    // into the target of a destructuring assignment.
6344                    self.push(match &key {
6345                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
6346                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
6347                    });
6348                }
6349                self.push(value);
6350            }
6351            PutField => {
6352                let value = self.pop();
6353                let object = self.pop();
6354                let key = self.atom_text(a as usize);
6355                self.write_field(&object, &key, value)?;
6356            }
6357            PutArrayEl => {
6358                let value = self.pop();
6359                let key = self.pop();
6360                let object = self.pop();
6361                let key = self.propkey(&key);
6362                self.write_field_key(&object, &key, value)?;
6363            }
6364            DefineField => {
6365                let value = self.pop();
6366                let object = self.pop();
6367                let key = self.atom_text(a as usize);
6368                // `{m: function(){}}` names the function `m`, the same way assigning
6369                // it to a property does. Without this the frame is anonymous and a
6370                // stack trace reads `at  (file:1:2)`.
6371                self.set_function_name(&value, &key);
6372                if let Some(target) = object.as_object() {
6373                    // Only an *array* stores into the element vector. A numeric key
6374                    // on an ordinary object is an ordinary property, which is what
6375                    // makes `{1: 'a'}` iterate as a key rather than disappear.
6376                    let stored = target.is_array()
6377                        && array_index(&key)
6378                            .is_some_and(|index| target.array_set(index as usize, value.clone()));
6379                    if !stored {
6380                        target.define_data(&key, value);
6381                    }
6382                }
6383                self.push(object);
6384            }
6385            DefineArrayEl => {
6386                // `obj key value -> obj key`. The *value* form of the key is what goes
6387                // back on the stack — the compiler stores it into the pattern's binding —
6388                // so the symbol is not stringified on the way through.
6389                let value = self.pop();
6390                let key_value = self.pop();
6391                let object = self.peek(0);
6392                let key = self.propkey(&key_value);
6393                self.write_field_key(&object, &key, value)?;
6394                self.push(key_value);
6395            }
6396            SetHomeObject => {
6397                // `obj func -> obj func`: records the object a method was defined on so
6398                // `super` inside it resolves against that object's prototype.
6399                let function = self.peek(0);
6400                let home = self.peek(1);
6401                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
6402                    function.set_home_object(Some(home.clone()));
6403                }
6404            }
6405            Regexp => {
6406                // `pattern flags -> regexp`. A literal compiles here rather than through the
6407                // constructor, which is both what the reference's dedicated opcode is for
6408                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
6409                let flags = self.pop();
6410                let pattern = self.pop();
6411                let pattern = self.to_js_string(&pattern)?;
6412                let flags = self.to_js_string(&flags)?;
6413                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
6414                self.push(Value::Object(object));
6415            }
6416            UsingDisposeInit => {
6417                // The error state a disposal accumulates into. Uninitialised means "no
6418                // failure yet"; anything else is the exception being propagated.
6419                self.push(Value::Uninitialized);
6420            }
6421            UsingCheck => {
6422                // `value -> value, method`: validate and snapshot the disposer now, so a
6423                // later change to `Symbol.dispose` cannot change what gets called, and so a
6424                // value that is not disposable fails before the body runs.
6425                let value = self.pop();
6426                let method = self.using_method_for(&value, a as u8 == 1)?;
6427                self.push(value);
6428                self.push(method);
6429            }
6430            UsingDispose => {
6431                // `error_state -> error_state'`: dispose the variable at `slot` — its value
6432                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
6433                // the pending error.
6434                let slot = self.slot_operand(op, a);
6435                let error_state = self.pop();
6436                let merged = self.using_dispose_once(slot, error_state)?;
6437                self.push(merged);
6438            }
6439            UsingDisposeMerge => {
6440                let new_error = self.pop();
6441                let error_state = self.pop();
6442                let merged = self.merge_dispose_error(new_error, error_state);
6443                self.push(merged);
6444            }
6445            UsingDisposeEnd => {
6446                // A disposal that failed replaces the block's normal completion, so the
6447                // error state becomes a real throw here rather than at the call site.
6448                let error_state = self.pop();
6449                if !matches!(error_state, Value::Uninitialized) {
6450                    return Err(Signal::Throw(error_state));
6451                }
6452            }
6453            UsingDisposeAsync => {
6454                // `await using` needs a promise to await and this runtime has no
6455                // `Promise` builtin, so the disposer is called synchronously and its result
6456                // discarded. That is correct for a disposer that returns nothing and is
6457                // reported as a gap rather than silently skipped.
6458                let slot = self.slot_operand(op, a);
6459                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
6460                self.push(error_state);
6461            }
6462            GetSuper => {
6463                // `obj -> obj's prototype`: the starting point of a `super` lookup.
6464                let object = self.pop();
6465                let proto = match &object {
6466                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
6467                    _ => Value::Null,
6468                };
6469                self.push(proto);
6470            }
6471            GetSuperValue => {
6472                // `receiver proto key -> value`, searching from `proto` but reporting to
6473                // `receiver`, which is what `super.g` must do for a getter to see `this`.
6474                let key = self.pop();
6475                let proto = self.pop();
6476                let receiver = self.peek(0);
6477                let value = self.super_read(&receiver, &proto, &key)?;
6478                self.push(value);
6479            }
6480            PutSuperValue => {
6481                // `receiver proto key value ->`: a store that starts at `proto` but
6482                // assigns to `receiver`.
6483                let value = self.pop();
6484                let key = self.pop();
6485                let proto = self.pop();
6486                let receiver = self.pop();
6487                self.super_write(&receiver, &proto, &key, value)?;
6488            }
6489            DefineClass => {
6490                // `parent ctor -> ctor proto`: the constructor becomes the class and a
6491                // fresh prototype object lands on top for the methods to go on.
6492                let name = self.atom_text(a as usize);
6493                let (ctor, proto) = self.define_class(&name, b)?;
6494                self.push(ctor);
6495                self.push(Value::Object(proto));
6496            }
6497            DefineClassComputed => {
6498                // `parent ctor key -> ctor proto key`: the computed name stays put so
6499                // `define_field`-style consumers can still read it.
6500                let key = self.pop();
6501                let name = self.propkey_of(&key).to_string_lossy().into_owned();
6502                let (ctor, proto) = self.define_class(&name, b)?;
6503                self.push(ctor);
6504                self.push(Value::Object(proto));
6505                self.push(key);
6506            }
6507            DefineMethod => {
6508                let function = self.pop();
6509                let object = self.pop();
6510                let key = self.atom_text(a as usize);
6511                // A method's `[[HomeObject]]` is the object it was defined on, which is
6512                // what `super` inside it resolves against.
6513                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
6514                    function.set_home_object(Some(object.clone()));
6515                }
6516                self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
6517                if let Some(array) = object.as_object() {
6518                    define_function_property(array, &PropertyKey::from(key.as_str()), function, b);
6519                }
6520                self.push(object);
6521            }
6522            DefineMethodComputed => {
6523                let function = self.pop();
6524                let key = self.pop();
6525                let object = self.pop();
6526                let key = self.propkey(&key);
6527                self.set_function_name(&function, &key_with_accessor_prefix(&key.to_string(), a));
6528                if let Some(array) = object.as_object() {
6529                    define_function_property(array, &key, function, a);
6530                }
6531                self.push(object);
6532            }
6533            SetProto => {
6534                let proto = self.pop();
6535                let object = self.pop();
6536                if let Some(target) = object.as_object() {
6537                    target.set_proto(proto.as_object().cloned());
6538                }
6539                self.push(object);
6540            }
6541            CopyDataProperties => {
6542                let exclusion = self.pop();
6543                let source = self.pop();
6544                let target = self.peek(0);
6545                self.copy_properties(&target, &source, &exclusion)?;
6546                self.push(source);
6547                self.push(exclusion);
6548            }
6549            ToPropkey => {
6550                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
6551                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
6552                // ordinary `"Symbol(b)"` property.
6553                let value = self.pop();
6554                let key = match self.propkey(&value) {
6555                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
6556                    PropertyKey::String(text) => self.string_wtf8(text),
6557                };
6558                self.push(key);
6559            }
6560            SetName => {
6561                let function = self.peek(0);
6562                let name = self.atom_text(a as usize);
6563                self.set_function_name(&function, &name);
6564            }
6565            SetNameComputed => {
6566                let key = self.peek(1);
6567                let function = self.peek(0);
6568                let name = self.propkey_of(&key).to_string_lossy().into_owned();
6569                self.set_function_name(&function, &name);
6570            }
6571
6572            // -- arrays -----------------------------------------------------
6573            ArrayFrom => {
6574                let count = a as usize;
6575                let elements = self.pop_n(count);
6576                let array = self.new_array(elements);
6577                self.push(Value::Object(array));
6578            }
6579            Append => {
6580                // `array index iterable -> array new_index`
6581                let iterable = self.pop();
6582                self.pop();
6583                let array = self.peek(0);
6584                let added = self.append_enumerate(&array, &iterable)?;
6585                self.push(Value::Int(added));
6586            }
6587
6588            // -- iteration --------------------------------------------------
6589            ForInStart => {
6590                let value = self.pop();
6591                let record = self.for_in_record(&value)?;
6592                self.push(Value::Object(record));
6593            }
6594            ForInNext => {
6595                // `record -> record key done`. The flag is *done*, not "found":
6596                // the compiler tests it with `if_false` to jump back into the body,
6597                // so reporting `true` while keys remain would end the loop at once.
6598                let record = self.peek(0);
6599                match self.for_in_advance(&record)? {
6600                    Some(key) => {
6601                        let text = self.string(key);
6602                        self.push(text);
6603                        self.push(Value::Bool(false));
6604                    }
6605                    None => {
6606                        self.push(Value::Undefined);
6607                        self.push(Value::Bool(true));
6608                    }
6609                }
6610            }
6611            ForOfStart => {
6612                let value = self.pop();
6613                let iterator = self.get_iterator(&value)?;
6614                self.push(iterator.object);
6615                self.push(iterator.next);
6616                self.push(Value::CatchOffset(0));
6617            }
6618            ForOfNext => {
6619                // `iter next catch_offset -> iter next catch_offset value done`.
6620                //
6621                // The operand is how many values sit *above* the iterator triple: a
6622                // destructuring rest element keeps its target array and running index
6623                // there while draining the iterator, so the triple is not at the top.
6624                let extra = a as usize;
6625                let iterator_slot = 2 + extra;
6626                // An exhausted iterator is replaced by `undefined` (see below), so a
6627                // second step must not call `next` again — `Array.from` and a
6628                // destructuring pattern both keep stepping past the end.
6629                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
6630                    (Value::Undefined, true)
6631                } else {
6632                    let iterator = Iterator {
6633                        object: self.peek(iterator_slot),
6634                        next: self.peek(1 + extra),
6635                    };
6636                    self.iterator_step(&iterator)?
6637                };
6638                if done {
6639                    // The result's `value` is meaningless once the iterator is done:
6640                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
6641                    // rather than binding the generator's return value.
6642                    let top = self.frame().stack.len() - 1 - iterator_slot;
6643                    self.frame_mut().stack[top] = Value::Undefined;
6644                    self.push(Value::Undefined);
6645                    self.push(Value::Bool(true));
6646                } else {
6647                    self.push(value);
6648                    self.push(Value::Bool(false));
6649                }
6650            }
6651            IteratorNext => {
6652                // `iter next catch val -> iter next catch val'`: replace the argument with
6653                // the result of `next(val)`. The triple below stays put, which is why the
6654                // three instructions of the `yield*` loop all address the stack the same way.
6655                let value = self.pop();
6656                let object = self.peek(2);
6657                let next = self.peek(1);
6658                let result = self.call_value(next, object, vec![value])?;
6659                self.push(result);
6660            }
6661            IteratorCall => {
6662                // `iter next catch val -> iter next catch val' flag`.
6663                //
6664                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
6665                // The flag is `true` when the method was missing, which is how the
6666                // caller learns that the inner iterator cannot take part in the
6667                // unwinding.
6668                let value = self.pop();
6669                let object = self.peek(2);
6670                let key = if a & 1 != 0 { "throw" } else { "return" };
6671                let method = self.read_field(&object, key)?;
6672                if matches!(method, Value::Undefined | Value::Null) {
6673                    self.push(value);
6674                    self.push(Value::Bool(true));
6675                } else {
6676                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
6677                    let result = self.call_value(method, object, argument)?;
6678                    self.push(result);
6679                    self.push(Value::Bool(false));
6680                }
6681            }
6682            IteratorCheckObject => {
6683                if !matches!(self.peek(0), Value::Object(_)) {
6684                    return Err(Signal::Throw(
6685                        self.make_error("TypeError", "iterator must return an object"),
6686                    ));
6687                }
6688            }
6689            IteratorClose => {
6690                // `iter next catch_offset ->`
6691                self.pop();
6692                self.pop();
6693                self.pop();
6694            }
6695            Import => {
6696                // `import(specifier)`: the options slot is on top and is not read yet.
6697                let _options = self.pop();
6698                let specifier = self.pop();
6699                let promise = self.dynamic_import(specifier)?;
6700                self.push(promise);
6701            }
6702            ForAwaitOfStart => {
6703                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
6704                // `Symbol.iterator` fallback.
6705                let value = self.pop();
6706                let iterator = self.get_async_iterator(&value)?;
6707                self.push(iterator.object);
6708                self.push(iterator.next);
6709                self.push(Value::CatchOffset(0));
6710            }
6711            ForAwaitOfNext => {
6712                // `for await` steps the iterator and leaves the *result* wrapped in a
6713                // promise, so the `await` the compiler emits right after this can suspend
6714                // on it. Unwrapping happens in `iterator_get_value_done`.
6715                let extra = a as usize;
6716                let iterator_slot = 2 + extra;
6717                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
6718                    Value::Undefined
6719                } else {
6720                    let iterator = Iterator {
6721                        object: self.peek(iterator_slot),
6722                        next: self.peek(1 + extra),
6723                    };
6724                    let next = iterator.next.clone();
6725                    self.call_value(next, iterator.object, Vec::new())?
6726                };
6727                let promise = self.promise_resolve_value(result)?;
6728                self.push(promise);
6729            }
6730            IteratorGetValueDone => {
6731                // `result -> value done`. A missing result object means the iterator was
6732                // already exhausted, which the loop treats as `done`.
6733                let result = self.pop();
6734                let Value::Object(object) = &result else {
6735                    self.push(Value::Undefined);
6736                    self.push(Value::Bool(true));
6737                    return Ok(Step::Continue);
6738                };
6739                let done = self
6740                    .get_property(object, "done")?
6741                    .is_some_and(|value| value.to_boolean());
6742                if done {
6743                    self.push(Value::Undefined);
6744                    self.push(Value::Bool(true));
6745                } else {
6746                    let value = self
6747                        .get_property(object, "value")?
6748                        .unwrap_or(Value::Undefined);
6749                    self.push(value);
6750                    self.push(Value::Bool(false));
6751                }
6752            }
6753
6754            Delete => {
6755                // `delete obj[key]`, where the key was just pushed. Deleting an array
6756                // index leaves a *hole* rather than closing the gap, and a
6757                // non-configurable property answers `false` and stays.
6758                let key = self.pop();
6759                let target = self.pop();
6760                let key = self.propkey(&key);
6761                let text_label = key.as_str().unwrap_or("").to_string();
6762                let deleted = match &target {
6763                    Value::Object(object) => {
6764                        let object = object.clone();
6765                        self.delete_property_key(&object, &key)?
6766                    }
6767                    // A string's `length` and its index properties are
6768                    // non-configurable, so deleting one answers `false`.
6769                    Value::String(text) => {
6770                        !(text_label == "length"
6771                            || array_index(&text_label)
6772                                .is_some_and(|index| (index as usize) < text.utf16_len()))
6773                    }
6774                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
6775                    // object to delete from, and only a *boxable* primitive has one.
6776                    Value::Undefined | Value::Null => {
6777                        return Err(Signal::Throw(
6778                            self.make_error("TypeError", "cannot convert to object"),
6779                        ));
6780                    }
6781                    // Any other primitive has no own properties; deleting nothing
6782                    // succeeds.
6783                    _ => true,
6784                };
6785                self.push(Value::Bool(deleted));
6786            }
6787
6788            // -- exceptions and bookkeeping ---------------------------------
6789            Fclosure | Fclosure8 => {
6790                let value = self.closure(a as usize)?;
6791                self.push(value);
6792            }
6793
6794            other => {
6795                let name = other.info().name;
6796                return Err(Signal::Throw(self.make_error(
6797                    "InternalError",
6798                    &format!("{name} is not implemented yet"),
6799                )));
6800            }
6801        }
6802        Ok(Step::Continue)
6803    }
6804
6805    // -- operand helpers ----------------------------------------------------
6806
6807    /// The slot index an operand names, taking short forms into account.
6808    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
6809        use Opcode::*;
6810        match op {
6811            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
6812            | SetVarRef0 => 0,
6813            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
6814            | SetVarRef1 => 1,
6815            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
6816            | SetVarRef2 => 2,
6817            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
6818            | SetVarRef3 => 3,
6819            _ => a as usize,
6820        }
6821    }
6822
6823    /// The argument count of a call, taking `call0`…`call3` into account.
6824    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
6825        use Opcode::*;
6826        match op {
6827            Call0 => 0,
6828            Call1 => 1,
6829            Call2 => 2,
6830            Call3 => 3,
6831            _ => a as usize,
6832        }
6833    }
6834
6835    fn atom_text(&self, index: usize) -> String {
6836        self.frame()
6837            .code
6838            .code
6839            .atoms
6840            .get(index)
6841            .map(|atom| match atom {
6842                Atom::Str(text) => text.clone(),
6843                Atom::Index(value) => value.to_string(),
6844            })
6845            .unwrap_or_default()
6846    }
6847
6848    fn constant(&mut self, index: usize) -> JsResult<Value> {
6849        let constant = self.frame().code.code.cpool.get(index).cloned();
6850        Ok(match &constant {
6851            Some(Constant::Number(number)) => Value::Float(*number),
6852            Some(Constant::String(text)) => self.string(text.clone()),
6853            Some(Constant::BigInt { digits, radix }) => {
6854                match crate::bigint::BigInt::from_radix(digits, *radix) {
6855                    Some(big) => self.bigint(big),
6856                    // A literal the parser accepted is always parseable; a failure here
6857                    // would be a compiler bug, so it reads as an `InternalError`.
6858                    None => {
6859                        return Err(Signal::Throw(
6860                            self.make_error("InternalError", "unparseable bigint literal"),
6861                        ));
6862                    }
6863                }
6864            }
6865            Some(Constant::Function(_)) => {
6866                return Err(Signal::Throw(
6867                    self.make_error("InternalError", "a bare function constant"),
6868                ));
6869            }
6870            // A tagged template's call site: a frozen array of the cooked chunks with a
6871            // frozen `raw` array beside it, which is what `String.raw` reads back.
6872            Some(Constant::Template { cooked, raw }) => {
6873                let cooked_values: Vec<Value> = cooked
6874                    .iter()
6875                    .map(|chunk| match chunk {
6876                        Some(text) => self.string(text.clone()),
6877                        None => Value::Undefined,
6878                    })
6879                    .collect();
6880                let raw_values: Vec<Value> =
6881                    raw.iter().map(|text| self.string(text.clone())).collect();
6882                let raw_array = self.new_array(raw_values);
6883                raw_array.set_extensible(false);
6884                let template = self.new_array(cooked_values);
6885                template.define(
6886                    "raw",
6887                    Property::with_attributes(Value::Object(raw_array), false, false),
6888                );
6889                template.set_extensible(false);
6890                Value::Object(template)
6891            }
6892            _ => Value::Undefined,
6893        })
6894    }
6895
6896    /// The reference cell a closure-variable slot names.
6897    ///
6898    /// Two kinds of binding share this addressing: a genuine closure variable
6899    /// (captured from an enclosing function) lives in this frame's environment,
6900    /// while a *declared global* lives in the realm so that a script, a function
6901    /// declaration and their uses all see one binding. A plain `Global` — an
6902    /// undeclared name that may be satisfied by the global object — has no cell at
6903    /// all, which is how `typeof x` still works for a name that does not exist.
6904    /// The reference cell a closure-variable slot names.
6905    ///
6906    /// The environment is resolved once, when the closure is built, and this is
6907    /// just the lookup afterwards. A *declared global* is in there too, pointing at
6908    /// the realm's cell, so a script, a hoisted function declaration and their uses
6909    /// all share one binding. A plain `Global` — a name the script never declared —
6910    /// is read and written through `get_var`/`put_var` by name instead, which is
6911    /// what lets the global object satisfy it.
6912    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
6913        self.frame().env.cells.get(slot).cloned()
6914    }
6915
6916    /// Whether `slot` refers to a global binding through the reference table.
6917    ///
6918    /// A global's cell in the closure environment only exists so the slot has
6919    /// something to point at; the binding itself lives on the global object (a `var`)
6920    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
6921    /// be routed, not performed on the placeholder.
6922    fn is_global_slot(&self, slot: usize) -> bool {
6923        self.frame()
6924            .code
6925            .code
6926            .closure_vars
6927            .get(slot)
6928            .is_some_and(|c| {
6929                // A module's declarations and imports are *not* globals: their cells are
6930                // the module environment's, filled by the host, so the placeholder routing
6931                // must not apply to them.
6932                matches!(
6933                    c.closure_type,
6934                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
6935                )
6936            })
6937    }
6938
6939    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
6940        if self.is_global_slot(slot) {
6941            return self.get_global(slot);
6942        }
6943        Ok(self
6944            .var_ref_cell(slot)
6945            .map(|cell| cell.get())
6946            .unwrap_or(Value::Undefined))
6947    }
6948
6949    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
6950        // A function declaration is hoisted by storing into a global reference before
6951        // the body runs, so this path is also what puts it on the global object.
6952        if self.is_global_slot(slot) {
6953            return self.put_global(slot, value);
6954        }
6955        if let Some(cell) = self.var_ref_cell(slot) {
6956            cell.set(value);
6957        }
6958        Ok(())
6959    }
6960
6961    // -- closures -----------------------------------------------------------
6962
6963    /// Build the closure for the function constant `index`.
6964    ///
6965    /// Every entry in the child's closure table names where its binding lives in
6966    /// *this* frame: a local or argument slot that was marked captured, or a cell
6967    /// this frame is itself holding. That is how a variable three functions deep
6968    /// stays one binding.
6969    fn closure(&mut self, index: usize) -> JsResult<Value> {
6970        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
6971        else {
6972            return Err(Signal::Throw(
6973                self.make_error("InternalError", "fclosure of a non-function"),
6974            ));
6975        };
6976        let mut cells = Vec::with_capacity(function.closure_vars.len());
6977        for closure_var in &function.closure_vars {
6978            let cell = match closure_var.closure_type {
6979                ClosureType::Arg => {
6980                    let slot = closure_var.var_idx as usize;
6981                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
6982                }
6983                ClosureType::Local => {
6984                    let slot = closure_var.var_idx as usize;
6985                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
6986                }
6987                ClosureType::Ref | ClosureType::GlobalRef => {
6988                    // A `Ref` names a cell in this frame's own closure table; a
6989                    // `GlobalRef` also starts there, then resolves by name below.
6990                    let slot = closure_var.var_idx as usize;
6991                    if let Some(cell) = self.frame().env.cells.get(slot) {
6992                        cells.push(cell.clone());
6993                        continue;
6994                    }
6995                    -1
6996                }
6997                _ => -1,
6998            };
6999            if cell >= 0 {
7000                let cell = self.frame().cells[cell as usize].clone();
7001                cells.push(cell);
7002                continue;
7003            }
7004            // A global: the cell is created on demand and shared through the realm,
7005            // so every function sees one binding.
7006            let name = closure_var.name.clone();
7007            let cell = match self.realm.globals.get(&name) {
7008                Some(cell) => cell.clone(),
7009                None => {
7010                    let cell = self.new_cell(Value::Undefined);
7011                    self.realm.globals.insert(name.clone(), cell.clone());
7012                    cell
7013                }
7014            };
7015            cells.push(cell);
7016        }
7017        let name = function.name.clone();
7018        // `.length` is the arity before any default or rest parameter, not the number
7019        // of slots a pattern parameter needs.
7020        let length = function.defined_args;
7021        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
7022        // function and an arrow function do not. A *method* also does not, but that is not
7023        // known here — the method is marked when the `[[HomeObject]]` is attached (see
7024        // `set_home_object`), which is the moment it becomes a method.
7025        let function_kind = function.kind;
7026        let constructible =
7027            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
7028        let code = Gc::new(self.heap, CompiledCode::new(*function));
7029        // A closure built inside an `eval` inherits the eval's view of the enclosing
7030        // bindings, so it can still read them once the eval has returned.
7031        let eval_scope = self
7032            .active_eval_scope
7033            .clone()
7034            .or_else(|| self.frame().env.eval_scope.clone());
7035        // A closure sees the variables a direct `eval` declared in the frame it was
7036        // created in — the ones declared before *and after* it, so the same object is
7037        // shared; only the phase bounds which of them are visible.
7038        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
7039        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
7040        let env = Gc::new(
7041            self.heap,
7042            ClosureEnv {
7043                cells,
7044                eval_scope,
7045                local_vars,
7046                local_phase,
7047            },
7048        );
7049        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
7050        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
7051        // the only thing that carries `Symbol.toStringTag`, so without it
7052        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
7053        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
7054        let proto = match function_kind {
7055            js_compile::bytecode::FunctionKind::AsyncGenerator => self
7056                .realm
7057                .async_generator_function_proto
7058                .clone()
7059                .or_else(|| self.realm.function_proto.clone().into()),
7060            js_compile::bytecode::FunctionKind::Generator => self
7061                .realm
7062                .generator_function_proto
7063                .clone()
7064                .or_else(|| self.realm.function_proto.clone().into()),
7065            js_compile::bytecode::FunctionKind::Async => self
7066                .realm
7067                .async_function_proto
7068                .clone()
7069                .or_else(|| self.realm.function_proto.clone().into()),
7070            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
7071        };
7072        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
7073        object.set_constructible(constructible);
7074        object.define(
7075            "length",
7076            Property::name_or_length(Value::Int(length as i32)),
7077        );
7078        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
7079        // that checks the own-property descriptor fails if the property is missing.
7080        object.define("name", Property::name_or_length(self.string(name)));
7081        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
7082        // when `[[Construct]]` is created, so a generator, an async function and an arrow
7083        // function have none of their own. Installing it unconditionally gave
7084        // `Array.fromAsync` (an async function) an own `prototype` property, which
7085        // `builtin.js` checks for absence.
7086        if constructible {
7087            self.install_function_prototype(&object);
7088        }
7089        Ok(Value::Object(object))
7090    }
7091
7092    // -- conversions used by the operators ----------------------------------
7093
7094    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
7095        // `+x` is `ToNumber`, which for a string parses it and for an object runs
7096        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
7097        // string, which then behaves differently in every later comparison.
7098        match value {
7099            Value::Int(_) | Value::Float(_) => Ok(value),
7100            other => Ok(Value::Float(self.to_js_number(&other)?)),
7101        }
7102    }
7103
7104    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
7105    ///
7106    /// Returns the *converted* old value and the new one, because the two callers need
7107    /// different halves: `++x` yields the new value, while `x++` yields the old one and
7108    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
7109    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
7110    /// boolean.
7111    ///
7112    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
7113    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
7114    /// a bigint algorithm then ran exactly once.
7115    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
7116        if let Value::BigInt(big) = &value {
7117            let one = crate::bigint::BigInt::from_i64(1);
7118            let next = if up { big.add(&one) } else { big.sub(&one) };
7119            return Ok((value, self.bigint(next)));
7120        }
7121        let old = self.numeric(value)?;
7122        let new = if up {
7123            increment(old.clone())
7124        } else {
7125            decrement(old.clone())
7126        };
7127        Ok((old, new))
7128    }
7129
7130    fn numeric(&mut self, value: Value) -> JsResult<Value> {
7131        // `ToNumber` on an object runs `ToPrimitive` first, which is how
7132        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
7133        // heard at all. Reading the object's own tag instead (`other.to_number()`)
7134        // turned the whole operand into `NaN` and swallowed the exception.
7135        match value {
7136            Value::Int(_) | Value::Float(_) => Ok(value),
7137            other => Ok(Value::Float(self.to_js_number(&other)?)),
7138        }
7139    }
7140
7141    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
7142    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
7143        match value {
7144            Value::BigInt(big) => Ok((**big).clone()),
7145            // The reference words this the same way for every operator, so a failing
7146            // script reads identically; the operator itself adds nothing a caller can use.
7147            _ => Err(Signal::Throw(
7148                self.make_error("TypeError", "cannot convert bigint to number"),
7149            )),
7150        }
7151    }
7152
7153    /// Arithmetic where at least one operand is a `BigInt`.
7154    ///
7155    /// The two numeric types never mix, so a bigint paired with anything else is an error
7156    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
7157    /// that the relational operators handle it separately.
7158    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
7159        use Opcode::*;
7160        let a = self.bigint_operand(&left)?;
7161        let b = self.bigint_operand(&right)?;
7162        let result = match op {
7163            Add => a.add(&b),
7164            Sub => a.sub(&b),
7165            Mul => a.mul(&b),
7166            Div | Mod => {
7167                let Some((quotient, remainder)) = a.div_rem(&b) else {
7168                    return Err(Signal::Throw(
7169                        self.make_error("RangeError", "division by zero"),
7170                    ));
7171                };
7172                if op == Div { quotient } else { remainder }
7173            }
7174            Pow => {
7175                let Some(value) = a.pow(&b) else {
7176                    return Err(Signal::Throw(self.make_error(
7177                        "RangeError",
7178                        "BigInt exponent must be non-negative and not absurdly large",
7179                    )));
7180                };
7181                value
7182            }
7183            And => a.bitand(&b),
7184            Or => a.bitor(&b),
7185            Xor => a.bitxor(&b),
7186            Shl | Sar => {
7187                // A shift count is a `BigInt` here, and both directions are exact; a
7188                // negative count would be the other direction, which the spec forbids.
7189                let Some(count) = b.to_i64() else {
7190                    return Err(Signal::Throw(
7191                        self.make_error("RangeError", "BigInt shift count is too large"),
7192                    ));
7193                };
7194                if count < 0 {
7195                    return Err(Signal::Throw(self.make_error(
7196                        "RangeError",
7197                        "BigInt shift count must be non-negative",
7198                    )));
7199                }
7200                if op == Shl {
7201                    a.shl(count as u64)
7202                } else {
7203                    a.shr(count as u64)
7204                }
7205            }
7206            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
7207            _ => {
7208                return Err(Signal::Throw(self.make_error(
7209                    "TypeError",
7210                    "BigInts have no unsigned right shift, use >> instead",
7211                )));
7212            }
7213        };
7214        Ok(self.bigint(result))
7215    }
7216
7217    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
7218    ///
7219    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
7220    /// is on the mathematical values, and nothing is rounded first.
7221    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> Value {
7222        use Opcode::*;
7223        let ordering = match (&left, &right) {
7224            (Value::String(a), Value::String(b)) => {
7225                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
7226            }
7227            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
7228            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
7229            // is true even though `2.5` has no bigint form.
7230            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
7231                let b = other.to_number();
7232                if b.is_nan() {
7233                    None
7234                } else {
7235                    compare_bigint_and_f64(a, b)
7236                }
7237            }
7238            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
7239                let a = other.to_number();
7240                if a.is_nan() {
7241                    None
7242                } else {
7243                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
7244                }
7245            }
7246            _ => left.to_number().partial_cmp(&right.to_number()),
7247        };
7248        let _ = self;
7249        let answer = match (op, ordering) {
7250            (_, None) => false,
7251            (Lt, Some(ordering)) => ordering.is_lt(),
7252            (Lte, Some(ordering)) => ordering.is_le(),
7253            (Gt, Some(ordering)) => ordering.is_gt(),
7254            (Gte, Some(ordering)) => ordering.is_ge(),
7255            _ => false,
7256        };
7257        Value::Bool(answer)
7258    }
7259
7260    fn binary_add(&mut self) -> JsResult<()> {
7261        let right = self.pop();
7262        let left = self.pop();
7263        let left = self.primitive_of(left)?;
7264        let right = self.primitive_of(right)?;
7265        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
7266        // that check comes before the bigint one: `"" + 1n` is a string, not a
7267        // mixed-type error.
7268        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
7269            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
7270            // `TypeError`, the one place a symbol and a string do not mix.
7271            let left = self.checked_to_wtf8(&left)?;
7272            let right = self.checked_to_wtf8(&right)?;
7273            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
7274            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
7275            let text = left.concat(&right);
7276            self.push(self.string_wtf8(text));
7277            return Ok(());
7278        }
7279        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
7280        // not a conversion.
7281        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
7282            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
7283            self.push(value);
7284            return Ok(());
7285        }
7286        let left = self.numeric(left)?;
7287        let right = self.numeric(right)?;
7288        self.push(add_numbers(left, right));
7289        Ok(())
7290    }
7291
7292    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
7293        self.to_primitive(value, Hint::Default)
7294    }
7295
7296    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
7297    ///
7298    /// The order depends on the hint: the "number" order tries `valueOf` first and
7299    /// `toString` second, the "string" order the other way round, and the default
7300    /// hint uses the number order. A result that is still an object is a `TypeError`,
7301    /// because no built-in `valueOf`/`toString` returns one.
7302    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
7303        let Value::Object(object) = &value else {
7304            return Ok(value);
7305        };
7306        // A Date overrides the default hint to mean "string", which is what
7307        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
7308        // this, `"" + new Date()` would print the milliseconds, not the date.
7309        let hint = if hint == Hint::Default && is_date_object(self, object) {
7310            Hint::String
7311        } else {
7312            hint
7313        };
7314        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
7315        // handed the hint as a string. This is the hook a Date uses for its default hint
7316        // and a script uses to take over conversion entirely.
7317        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
7318        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
7319            if !function.is_callable() {
7320                return Err(self.type_error("Symbol.toPrimitive is not a function"));
7321            }
7322            let hint = match hint {
7323                Hint::String => "string",
7324                Hint::Number => "number",
7325                Hint::Default => "default",
7326            };
7327            let hint = self.string(hint);
7328            let result = self.call_value(
7329                Value::Object(function),
7330                Value::Object(object.clone()),
7331                vec![hint],
7332            )?;
7333            if matches!(result, Value::Object(_)) {
7334                return Err(self.type_error("cannot convert object to primitive value"));
7335            }
7336            return Ok(result);
7337        }
7338        let order: [&str; 2] = match hint {
7339            Hint::String => ["toString", "valueOf"],
7340            Hint::Number | Hint::Default => ["valueOf", "toString"],
7341        };
7342        let receiver = object.clone();
7343        for method in order {
7344            if let Some(function) = self.get_property(&receiver, method)?
7345                && matches!(&function, Value::Object(object) if object.is_callable())
7346            {
7347                let result =
7348                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
7349                if !matches!(result, Value::Object(_)) {
7350                    return Ok(result);
7351                }
7352            }
7353        }
7354        Err(self.type_error("cannot convert object to primitive value"))
7355    }
7356
7357    /// `ToString` with the object case going through `ToPrimitive`.
7358    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
7359        if matches!(value, Value::Object(_)) {
7360            let primitive = self.to_primitive(value.clone(), Hint::String)?;
7361            return Ok(primitive.to_js_string());
7362        }
7363        Ok(value.to_js_string())
7364    }
7365
7366    /// `ToString` that keeps the string's code units instead of flattening them.
7367    ///
7368    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
7369    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
7370    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
7371        if matches!(value, Value::Symbol(_)) {
7372            return Err(Signal::Throw(
7373                self.make_error("TypeError", "cannot convert symbol to string"),
7374            ));
7375        }
7376        // An object runs `ToPrimitive` first, which may itself produce a symbol.
7377        let value = self.to_primitive(value.clone(), Hint::String)?;
7378        match value {
7379            Value::Symbol(_) => Err(Signal::Throw(
7380                self.make_error("TypeError", "cannot convert symbol to string"),
7381            )),
7382            Value::String(text) => Ok(text.wtf8().clone()),
7383            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
7384        }
7385    }
7386
7387    /// `ToNumber` with the object case going through `ToPrimitive`.
7388    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
7389        let value = if matches!(value, Value::Object(_)) {
7390            self.to_primitive(value.clone(), Hint::Number)?
7391        } else {
7392            value.clone()
7393        };
7394        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
7395        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
7396        // `NaN` to stay total, and the operators check for the bigint themselves — but
7397        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
7398        // refuse, and answering `NaN` made them silently wrong instead.
7399        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
7400        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
7401        match value {
7402            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
7403            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
7404            other => Ok(other.to_number()),
7405        }
7406    }
7407
7408    /// `ToPropertyKey`: what a computed member access uses as its key.
7409    ///
7410    /// A symbol is returned as itself, never stringified — that is what keeps
7411    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
7412    fn propkey(&mut self, value: &Value) -> PropertyKey {
7413        match value {
7414            Value::Symbol(symbol) => PropertyKey::Symbol(symbol.clone()),
7415            _ => PropertyKey::String(self.propkey_of(value)),
7416        }
7417    }
7418
7419    /// `ToPropertyKey` for the callers that can only use a string key.
7420    fn propkey_of(&mut self, value: &Value) -> crate::value::Wtf8 {
7421        use crate::value::Wtf8;
7422        match value {
7423            // A string key keeps its code units. Going through a lossy `String` would make
7424            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
7425            Value::String(text) => text.wtf8().clone(),
7426            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
7427            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
7428            // falling back to its `ToString` would print `[object Object]`.
7429            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String) {
7430                Ok(Value::String(text)) => text.wtf8().clone(),
7431                Ok(other) => Wtf8::new(other.to_js_string()),
7432                Err(_) => Wtf8::new("[object Object]"),
7433            },
7434            other => Wtf8::new(other.to_js_string()),
7435        }
7436    }
7437
7438    // -- object operations used by instructions -----------------------------
7439
7440    /// Read `object[key]`, returning `undefined` when the property is missing.
7441    ///
7442    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
7443    /// primitive (looking through its prototype) as well as an object — which is what
7444    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
7445    /// argument needs too.
7446    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
7447        self.read_field_key(object, &PropertyKey::from(key))
7448    }
7449
7450    /// [`Interp::read_field`] with a key that may be a symbol.
7451    ///
7452    /// A symbol key never reaches the string shortcuts: a string's `length` and its
7453    /// indices are string properties, and a symbol named `length` is a different
7454    /// property that a string primitive cannot have.
7455    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
7456        let text = key.as_str().unwrap_or("");
7457        let Value::Object(object) = object else {
7458            // Reading a property of `undefined`/`null` is the classic TypeError.
7459            if object.is_nullish() {
7460                return Err(Signal::Throw(self.make_error(
7461                    "TypeError",
7462                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
7463                )));
7464            }
7465            // A string has `length` and index access without being boxed.
7466            if let Value::String(value) = object {
7467                if text == "length" {
7468                    return Ok(Value::Int(value.utf16_len() as i32));
7469                }
7470                if let Some(index) = array_index(text) {
7471                    return Ok(match value.wtf8().unit_at(index as usize) {
7472                        Some(unit) => self.string_wtf8(unit),
7473                        None => Value::Undefined,
7474                    });
7475                }
7476            }
7477            // A property of a primitive is looked up on its prototype: this is what
7478            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
7479            let prototype = match object {
7480                Value::String(_) => self.realm.string_proto.clone(),
7481                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
7482                Value::Bool(_) => self.realm.boolean_proto.clone(),
7483                // A symbol's methods live on `Symbol.prototype`, reached the same way —
7484                // `sym.description` reads through the prototype, not off the symbol.
7485                Value::Symbol(_) => self.realm.symbol_proto.clone(),
7486                // …and a bigint's on `BigInt.prototype`, which is how
7487                // `(255n).toString(16)` reaches its method.
7488                Value::BigInt(_) => self.realm.bigint_proto.clone(),
7489                _ => None,
7490            };
7491            if let Some(prototype) = prototype
7492                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
7493            {
7494                return Ok(value);
7495            }
7496            return Ok(Value::Undefined);
7497        };
7498        Ok(self
7499            .get_property_key(object, key)?
7500            .unwrap_or(Value::Undefined))
7501    }
7502
7503    fn write_field(&mut self, object: &Value, key: &str, value: Value) -> JsResult<()> {
7504        self.write_field_key(object, &PropertyKey::from(key), value)
7505    }
7506
7507    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
7508        let Value::Object(object) = object else {
7509            return Err(Signal::Throw(self.make_error(
7510                "TypeError",
7511                &format!("cannot set property '{key}' of {}", object.to_js_string()),
7512            )));
7513        };
7514        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
7515        let on_failure = if self.frame().code.code.strict {
7516            DeleteFailure::Throw
7517        } else {
7518            DeleteFailure::Ignore
7519        };
7520        self.set_property_with_key(object, key, value, on_failure)
7521    }
7522
7523    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
7524    ///
7525    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
7526    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
7527    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
7528    /// `Number.parseInt(sym)` — so those callers use this instead.
7529    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
7530        if matches!(value, Value::Symbol(_)) {
7531            return Err(Signal::Throw(
7532                self.make_error("TypeError", "cannot convert symbol to string"),
7533            ));
7534        }
7535        // An object runs `ToPrimitive` first, which may itself produce a symbol —
7536        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
7537        let value = self.to_primitive(value.clone(), Hint::String)?;
7538        if matches!(value, Value::Symbol(_)) {
7539            return Err(Signal::Throw(
7540                self.make_error("TypeError", "cannot convert symbol to string"),
7541            ));
7542        }
7543        Ok(value.to_js_string())
7544    }
7545
7546    /// `ToPropertyKey` for a builtin that takes a key argument.
7547    ///
7548    /// Distinct from [`Interp::propkey`], which is `fn`-private to the instruction
7549    /// loop; the builtins reach this one.
7550    pub fn property_key(&mut self, value: &Value) -> PropertyKey {
7551        self.propkey(value)
7552    }
7553
7554    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
7555    ///
7556    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
7557    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
7558    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
7559    /// `RangeError` — and why this cannot be a plain `ToNumber`.
7560    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
7561        let number = match value {
7562            Value::Int(number) => *number as f64,
7563            Value::Float(number) => *number,
7564            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
7565            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
7566            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
7567            // reference answers 0.
7568            Value::Null | Value::Bool(_) => value.to_number(),
7569            _ => {
7570                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
7571                match primitive {
7572                    Value::Int(number) => number as f64,
7573                    Value::Float(number) => number,
7574                    other => {
7575                        // `ToString` then `ToNumber`, so a string length goes through the
7576                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
7577                        // `Value::to_number` on the string already implements exactly that.
7578                        let text = self.to_js_string(&other)?;
7579                        crate::value::string_to_number(&text)
7580                    }
7581                }
7582            }
7583        };
7584        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
7585        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
7586        // is a `RangeError`, not `0`.
7587        if !number.is_finite()
7588            || number.fract() != 0.0
7589            || !(0.0..=u32::MAX as f64).contains(&number)
7590        {
7591            return Err(self.range_error("invalid array length"));
7592        }
7593        Ok(number as u32)
7594    }
7595
7596    /// `ToPropertyKey` that can fail.
7597    ///
7598    /// [`Interp::property_key`] swallows a throwing `ToPrimitive` and answers
7599    /// `"[object Object]"`, which is fine for a bytecode operand that has already been
7600    /// coerced but wrong for `Reflect.get`, where a key whose `toString` throws has to
7601    /// propagate that error (`return-abrupt-from-property-key`).
7602    pub fn property_key_checked(&mut self, value: &Value) -> JsResult<PropertyKey> {
7603        use crate::value::Wtf8;
7604        match value {
7605            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
7606            _ => match self.to_primitive(value.clone(), Hint::String)? {
7607                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
7608                // A `ToPrimitive` that lands on a symbol is a symbol key, not `String(sym)`.
7609                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
7610                other => Ok(PropertyKey::String(Wtf8::new(other.to_js_string()))),
7611            },
7612        }
7613    }
7614
7615    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
7616    /// `Object.getOwnPropertySymbols` put in their result array.
7617    pub fn key_value(&self, key: &PropertyKey) -> Value {
7618        match key {
7619            PropertyKey::String(text) => self.string_wtf8(text.clone()),
7620            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
7621        }
7622    }
7623
7624    /// Fill in a String exotic object: `_value`, `length` and the index properties.
7625    ///
7626    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
7627    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
7628    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
7629    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
7630    /// the two paths had drifted; this is the one both now use.
7631    ///
7632    /// The indices are *code units*, so an astral character occupies two of them — the
7633    /// same rule `s.length` and `s[i]` follow.
7634    /// Give an already-created object the internal slot that makes it a wrapper of
7635    /// `value`, so the primitive's prototype methods work on it.
7636    ///
7637    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
7638    /// which are wrappers of their own type holding the empty value.
7639    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
7640        self.internal_set(object, "_value", value);
7641    }
7642
7643    pub(crate) fn init_string_wrapper(
7644        &mut self,
7645        object: &Gc<JsObject>,
7646        text: &Gc<crate::value::JsString>,
7647    ) {
7648        object.define(
7649            "length",
7650            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
7651        );
7652        for index in 0..text.utf16_len() {
7653            if let Some(unit) = text.wtf8().unit_at(index) {
7654                object.define(
7655                    &index.to_string(),
7656                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
7657                    Property::with_attributes(self.string_wtf8(unit), false, true),
7658                );
7659            }
7660        }
7661        object.define_key(
7662            &self.internal_slot("_value"),
7663            Property::with_attributes(Value::String(text.clone()), false, false),
7664        );
7665    }
7666
7667    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
7668    ///
7669    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
7670    /// throws. The wrapper carries its primitive in `_value` — the same slot
7671    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
7672    /// on a boxed value no constructor ever built.
7673    pub(crate) fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
7674        let (prototype, primitive) = match value {
7675            Value::Object(object) => return Ok(object.clone()),
7676            Value::String(text) => {
7677                let object = self.new_object(self.realm.string_proto.clone());
7678                self.init_string_wrapper(&object, text);
7679                return Ok(object);
7680            }
7681            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
7682            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
7683            // A symbol and a bigint box into wrappers whose methods live on
7684            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
7685            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
7686            // branch below instead produced an object with *no* prototype, so those
7687            // methods were unreachable on a box.
7688            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
7689            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
7690            Value::Undefined | Value::Null => {
7691                return Err(Signal::Throw(self.make_error(
7692                    "TypeError",
7693                    &format!("cannot convert {} to object", value.to_js_string()),
7694                )));
7695            }
7696            _ => (None, value.clone()),
7697        };
7698        let object = self.new_object(prototype);
7699        self.internal_set(&object, "_value", primitive);
7700        Ok(object)
7701    }
7702
7703    /// `a == b`, the coercing comparison.
7704    ///
7705    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
7706    /// which is what makes `[] == ""` true: `[]` becomes `""` via
7707    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
7708    /// because the conversion is allowed to call script code, so the two primitive
7709    /// operands are handed back to it.
7710    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
7711        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
7712            return Ok(left.loose_equals(&right));
7713        }
7714        // `null == undefined` holds even though neither is an object.
7715        if matches!(left, Value::Undefined | Value::Null)
7716            && matches!(right, Value::Undefined | Value::Null)
7717        {
7718            return Ok(true);
7719        }
7720        if matches!(left, Value::Undefined | Value::Null)
7721            || matches!(right, Value::Undefined | Value::Null)
7722        {
7723            return Ok(false);
7724        }
7725        // Two objects compare by identity. Only an object *against a primitive* is
7726        // converted, which is why `{} == {}` is false while `[] == ""` is true.
7727        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
7728            return Ok(a.ptr_eq(b));
7729        }
7730        let left = self.to_primitive(left, Hint::Default)?;
7731        let right = self.to_primitive(right, Hint::Default)?;
7732        Ok(left.loose_equals(&right))
7733    }
7734
7735    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
7736        let Value::Object(object) = object else {
7737            return Err(Signal::Throw(
7738                self.make_error("TypeError", "cannot use 'in' on a non-object"),
7739            ));
7740        };
7741        let key = self.propkey(key);
7742        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
7743        // trap. One implementation, so an array's derived `length` and its inherited holes
7744        // cannot be right in one caller and wrong in another.
7745        self.has_own_or_inherited(object, &key)
7746    }
7747
7748    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
7749        let Value::Object(target) = object else {
7750            return Ok(false);
7751        };
7752        let Value::Object(function) = constructor else {
7753            return Err(Signal::Throw(self.make_error(
7754                "TypeError",
7755                "right-hand side of 'instanceof' is not callable",
7756            )));
7757        };
7758        let prototype = self.get_property(function, "prototype")?;
7759        let Some(Value::Object(prototype)) = prototype else {
7760            return Ok(false);
7761        };
7762        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
7763        // which is also what makes `proxyOfInstance instanceof C` work.
7764        let mut current = Some(target.clone());
7765        while let Some(object) = current {
7766            if object.ptr_eq(&prototype) {
7767                return Ok(true);
7768            }
7769            current = self.object_prototype_of(&object)?;
7770        }
7771        Ok(false)
7772    }
7773
7774    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
7775    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
7776        if let Some(proto) = self.proxy_get_prototype_of(object)? {
7777            return Ok(proto);
7778        }
7779        Ok(object.proto())
7780    }
7781
7782    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
7783    pub fn object_set_prototype_of(
7784        &mut self,
7785        object: &Gc<JsObject>,
7786        proto: Option<Gc<JsObject>>,
7787    ) -> JsResult<bool> {
7788        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
7789            return Ok(answer);
7790        }
7791        object.set_proto(proto);
7792        Ok(true)
7793    }
7794
7795    /// `[[IsExtensible]]`, with the proxy trap when there is one.
7796    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
7797        if let Some(answer) = self.proxy_is_extensible(object)? {
7798            return Ok(answer);
7799        }
7800        Ok(object.is_extensible())
7801    }
7802
7803    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
7804    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
7805        if let Some(answer) = self.proxy_prevent_extensions(object)? {
7806            return Ok(answer);
7807        }
7808        object.set_extensible(false);
7809        Ok(true)
7810    }
7811
7812    fn copy_properties(
7813        &mut self,
7814        target: &Value,
7815        source: &Value,
7816        exclusion: &Value,
7817    ) -> JsResult<()> {
7818        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
7819        // does contribute: its index properties are own, enumerable and writable, which
7820        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
7821        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
7822        // is a no-op.
7823        let Some(target) = target.as_object() else {
7824            return Ok(());
7825        };
7826        let source_object = match source {
7827            Value::Object(object) => object.clone(),
7828            Value::String(text) => {
7829                // Untaken keys are the string's indices, which are code units.
7830                for index in 0..text.utf16_len() {
7831                    if let Some(unit) = text.wtf8().unit_at(index) {
7832                        target.define_data(&index.to_string(), self.string_wtf8(unit));
7833                    }
7834                }
7835                return Ok(());
7836            }
7837            _ => return Ok(()),
7838        };
7839        // An object *rest* element passes the keys already taken by the literal part as
7840        // an array of strings; a spread passes `null`, which excludes nothing. Only the
7841        // string keys of the exclusion array are meaningful, so an array is read by its
7842        // elements rather than by its own property names.
7843        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
7844        if let Value::Object(list) = exclusion
7845            && let Some(length) = list.array_length()
7846        {
7847            for index in 0..length {
7848                if let Some(value) = list.array_get(index) {
7849                    excluded.push(self.propkey_of(&value));
7850                }
7851            }
7852        }
7853        let source = &source_object;
7854        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
7855        // Reading the property table directly made every spread of a proxy empty.
7856        let keys = self.object_own_property_keys(source)?;
7857        for as_key in keys {
7858            if as_key.is_symbol() {
7859                // A spread copies string-keyed properties only.
7860                continue;
7861            }
7862            if excluded.contains(&crate::value::Wtf8::new(
7863                as_key.as_str().unwrap_or_default(),
7864            )) {
7865                continue;
7866            }
7867            let enumerable = self
7868                .object_get_own_property(source, &as_key)?
7869                .is_some_and(|property| property.enumerable);
7870            if !enumerable {
7871                continue;
7872            }
7873            let value = self
7874                .get_property_key(source, &as_key)?
7875                .unwrap_or(Value::Undefined);
7876            target.define_data_key(&as_key, value);
7877        }
7878        Ok(())
7879    }
7880
7881    // -- iteration ---------------------------------------------------------
7882
7883    /// One object's own keys in enumeration order: array indices ascending, then the
7884    /// rest in insertion order.
7885    ///
7886    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
7887    /// whether the key is enumerable, which the caller resolves per key because an
7888    /// array's elements are not in the same store as its named properties.
7889    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
7890        // An index can arrive twice, once from the array's element store and once from
7891        // its property map, so the numeric keys go through a map that keeps the
7892        // enumerable answer if either source gave one.
7893        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
7894        for (key, enumerable) in &own {
7895            if let Some(index) = key.as_str().and_then(array_index) {
7896                let entry = numeric.entry(index).or_insert(false);
7897                *entry = *entry || *enumerable;
7898            }
7899        }
7900        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
7901            .into_iter()
7902            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
7903            .collect();
7904        ordered.extend(
7905            own.into_iter()
7906                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
7907        );
7908        ordered
7909    }
7910
7911    /// Build the key list a `for-in` loop walks.
7912    ///
7913    /// The order is the specification's: own properties before inherited ones, and
7914    /// within one object the integer-like keys in ascending numeric order ahead of the
7915    /// string keys in insertion order. A shadowed key only appears once, and a key that
7916    /// is a non-enumerable own property anywhere nearer is skipped entirely.
7917    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
7918        let record = self.new_object(None);
7919        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
7920        // A proxy supplies its own key list, and — the reason this is not just another
7921        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
7922        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
7923        // descriptor there.
7924        if let Value::Object(object) = value
7925            && object.proxy_state().is_some()
7926        {
7927            let own = self
7928                .proxy_own_keys(object)?
7929                .unwrap_or_else(|| object.own_property_keys());
7930            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
7931            let mut numeric: Vec<u32> = Vec::new();
7932            let mut rest: Vec<PropertyKey> = Vec::new();
7933            for key in own {
7934                match key.as_str().and_then(array_index) {
7935                    Some(index) => numeric.push(index),
7936                    None => rest.push(key),
7937                }
7938            }
7939            numeric.sort_unstable();
7940            ordered.extend(
7941                numeric
7942                    .into_iter()
7943                    .map(|index| PropertyKey::from(index.to_string())),
7944            );
7945            ordered.extend(rest);
7946            for (index, key) in ordered.into_iter().enumerate() {
7947                record.define_data(&index.to_string(), self.key_value(&key));
7948            }
7949            record.define_data("__index", Value::Int(0));
7950            // The mark that makes `for_in_advance` re-ask the proxy per key.
7951            record.define_data("__proxy", Value::Object(object.clone()));
7952            return Ok(record);
7953        }
7954        if let Value::Object(object) = value {
7955            let mut chain = vec![object.clone()];
7956            chain.extend(object.chain());
7957            // Every own string key the walk has seen, enumerable or not. A
7958            // non-enumerable own property still hides a same-named enumerable one
7959            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
7960            // keeps `x` out of the loop even when the prototype has one.
7961            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
7962            for object in chain {
7963                let mut own: Vec<(crate::value::Wtf8, bool)> = object
7964                    .own_property_keys()
7965                    .iter()
7966                    .filter_map(|key| key.as_wtf8().cloned())
7967                    .map(|key| {
7968                        let enumerable = object
7969                            .own_property(&key.to_string_lossy())
7970                            .map(|property| property.enumerable)
7971                            .unwrap_or(false);
7972                        (key, enumerable)
7973                    })
7974                    .collect();
7975                if let Some(length) = object.array_length() {
7976                    own.retain(|(key, _)| key.as_str() != Some("length"));
7977                    for index in 0..length {
7978                        if object.array_get(index).is_some() {
7979                            own.push((crate::value::Wtf8::new(index.to_string()), true));
7980                        }
7981                    }
7982                }
7983                // Integer-like keys come first in ascending order, then the rest in
7984                // insertion order — and the ordering is *per object*, not for the chain
7985                // as a whole: one pass over every collected key lifted a prototype's
7986                // `"4"` above the target's own `x`/`y`, which is not the order
7987                // `for…in` reports.
7988                for (key, enumerable) in Self::order_own_keys(own) {
7989                    if visited.contains(&key) {
7990                        continue;
7991                    }
7992                    visited.push(key.clone());
7993                    if enumerable {
7994                        keys.push(key);
7995                    }
7996                }
7997            }
7998        }
7999        for (index, key) in keys.into_iter().enumerate() {
8000            record.define_data(&index.to_string(), self.string_wtf8(key));
8001        }
8002        record.define_data("__index", Value::Int(0));
8003        Ok(record)
8004    }
8005
8006    /// The next key of a `for…in` record, `None` when the loop is done.
8007    ///
8008    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
8009    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
8010    /// the loop reaches it, so a handler that stops reporting a key partway through drops
8011    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
8012    /// key the handler had already withdrawn.
8013    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
8014        let Value::Object(record) = record else {
8015            return Ok(None);
8016        };
8017        let proxy = record
8018            .own_property("__proxy")
8019            .and_then(|property| property.value);
8020        loop {
8021            let index = record
8022                .own_property("__index")
8023                .and_then(|property| property.value)
8024                .map(|value| value.to_int32())
8025                .unwrap_or(0);
8026            let Some(candidate) = record
8027                .own_property(&index.to_string())
8028                .and_then(|property| property.value)
8029            else {
8030                return Ok(None);
8031            };
8032            record.define_data("__index", Value::Int(index + 1));
8033            let text = candidate.to_js_string();
8034            let Some(Value::Object(proxy)) = &proxy else {
8035                return Ok(Some(text));
8036            };
8037            // The candidate is already a key string here, so the lookup does not need a
8038            // second `ToPropertyKey` conversion.
8039            let key = PropertyKey::from(text.as_str());
8040            let live = match self.proxy_get_own_property(proxy, &key)? {
8041                Some(descriptor) => descriptor,
8042                // Not a proxy after all, or it lost its state: fall back to the target.
8043                None => proxy.own_property_key(&key),
8044            };
8045            if live.is_some_and(|property| property.enumerable) {
8046                return Ok(Some(text));
8047            }
8048            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
8049            // next one.
8050        }
8051    }
8052
8053    /// The iterator for `for-of`: the object and its `next` method.
8054    ///
8055    /// An object that already carries a `next` method is used as it is — that is what
8056    /// `arr.values()` returns — and only arrays and strings get the built-in
8057    /// sequence iterator.
8058    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
8059    ///
8060    /// Callers that must choose between the iterable and the array-like protocol — the
8061    /// typed-array constructor is the main one — need to ask *before* committing to one.
8062    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
8063        let key = self.realm.well_known_key(WellKnown::Iterator);
8064        let method = self.read_field_key(value, &key)?;
8065        if matches!(method, Value::Undefined | Value::Null) {
8066            return Ok(false);
8067        }
8068        if !matches!(&method, Value::Object(object) if object.is_callable()) {
8069            return Err(Signal::Throw(
8070                self.make_error("TypeError", "Symbol.iterator is not callable"),
8071            ));
8072        }
8073        Ok(true)
8074    }
8075
8076    /// Collect everything an iterable yields, closing it if the walk is abandoned.
8077    ///
8078    /// The cap is a guard against a generator that never ends: an unbounded collect would
8079    /// be an out-of-memory abort rather than a catchable error.
8080    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8081        const MAX_ITEMS: usize = 1 << 24;
8082        let iterator = self.get_iterator(value)?;
8083        let mut out = Vec::new();
8084        loop {
8085            let (element, done) = self.iterator_step(&iterator)?;
8086            if done {
8087                return Ok(out);
8088            }
8089            out.push(element);
8090            if out.len() > MAX_ITEMS {
8091                return Err(self.range_error("iterable is too long to collect"));
8092            }
8093        }
8094    }
8095
8096    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
8097    ///
8098    /// A native constructor calls this once it has validated its arguments, which is the
8099    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
8100    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
8101    /// never reached. The prototype comes from `new.target` when it is an object, and from
8102    /// `default_proto` otherwise.
8103    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
8104        let Some(target) = self.pending_new_target.clone() else {
8105            return Ok(self.new_object(Some(default_proto)));
8106        };
8107        let Some(target) = target.as_object().cloned() else {
8108            return Ok(self.new_object(Some(default_proto)));
8109        };
8110        let proto = match self.get_property(&target, "prototype")? {
8111            Some(Value::Object(proto)) => proto,
8112            _ => default_proto,
8113        };
8114        Ok(self.new_object(Some(proto)))
8115    }
8116
8117    /// Whether this call is a construction, i.e. `new.target` is defined.
8118    ///
8119    /// A native constructor receives `this = undefined` (it builds its own instance), so it
8120    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
8121    /// The native function currently executing, if any.
8122    pub fn current_native(&self) -> Option<Gc<JsObject>> {
8123        self.current_native.clone()
8124    }
8125
8126    /// Whether this call is a construction, i.e. `new.target` is defined.
8127    pub fn is_constructing(&self) -> bool {
8128        self.pending_new_target.is_some()
8129    }
8130
8131    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
8132    ///
8133    /// True whenever `new.target` is not the callee itself, or when it has no usable
8134    /// `prototype` — the cases where reading the property is observable at all.
8135    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
8136        match &self.pending_new_target {
8137            Some(Value::Object(target)) => !target.ptr_eq(callee),
8138            Some(_) => true,
8139            None => false,
8140        }
8141    }
8142
8143    /// The symbol key for one of the engine's own hidden slots.
8144    ///
8145    /// Cached on the realm, so every object of a kind shares one key and a slot can be
8146    /// read back by name.
8147    pub fn internal_slot(&mut self, name: &'static str) -> PropertyKey {
8148        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.get(name) {
8149            return PropertyKey::Symbol(symbol.clone());
8150        }
8151        let symbol = Gc::new(
8152            self.heap,
8153            crate::value::JsSymbol::new(Some(name.to_string())),
8154        );
8155        self.realm
8156            .internal_slots
8157            .insert(name, Value::Symbol(symbol.clone()));
8158        PropertyKey::Symbol(symbol)
8159    }
8160
8161    /// Read a hidden slot, or `None` when the object has none of that name.
8162    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
8163        let Value::Symbol(symbol) = self.realm.internal_slots.get(name)? else {
8164            return None;
8165        };
8166        object
8167            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
8168            .and_then(|property| property.value)
8169    }
8170
8171    /// Define a hidden slot.
8172    pub fn internal_set(&mut self, object: &Gc<JsObject>, name: &'static str, value: Value) {
8173        let key = self.internal_slot(name);
8174        object.define_key(&key, Property::with_attributes(value, false, false));
8175    }
8176
8177    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
8178    ///
8179    /// The method is looked up on the value (through its prototype), called with no
8180    /// arguments, and its result becomes the iterator. A generator gets here through
8181    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
8182    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
8183    ///
8184    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
8185    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
8186    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
8187    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
8188    /// does, and a user-defined iterable works without a special case.
8189    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
8190    /// `Symbol.iterator`.
8191    ///
8192    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
8193    /// iterable is legal there, and each value it produces is simply already settled by
8194    /// the time the `await` around it runs.
8195    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
8196        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
8197        let method = self.read_field_key(value, &async_key)?;
8198        let has_async = matches!(&method, Value::Object(object) if object.is_callable());
8199        if !has_async {
8200            return self.get_iterator(value);
8201        }
8202        let iterator = self.call_value(method, value.clone(), Vec::new())?;
8203        if !matches!(iterator, Value::Object(_)) {
8204            return Err(Signal::Throw(
8205                self.make_error("TypeError", "iterator is not an object"),
8206            ));
8207        }
8208        let next = self.read_field(&iterator, "next")?;
8209        Ok(Iterator {
8210            object: iterator,
8211            next,
8212        })
8213    }
8214
8215    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
8216        let key = self.realm.well_known_key(WellKnown::Iterator);
8217        let method = self.read_field_key(value, &key)?;
8218        let Value::Object(function) = &method else {
8219            return Err(Signal::Throw(self.make_error(
8220                "TypeError",
8221                &format!("{} is not iterable", value.to_js_string()),
8222            )));
8223        };
8224        if !function.is_callable() {
8225            return Err(Signal::Throw(self.make_error(
8226                "TypeError",
8227                &format!("{} is not iterable", value.to_js_string()),
8228            )));
8229        }
8230        let iterator = self.call_value(method, value.clone(), Vec::new())?;
8231        // The spec requires an object here; a primitive iterator has no `next` to call
8232        // and would fail one step later with a confusing message.
8233        if !matches!(iterator, Value::Object(_)) {
8234            return Err(Signal::Throw(
8235                self.make_error("TypeError", "iterator is not an object"),
8236            ));
8237        }
8238        let next = self.read_field(&iterator, "next")?;
8239        Ok(Iterator {
8240            object: iterator,
8241            next,
8242        })
8243    }
8244
8245    /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
8246    /// not iterable.
8247    ///
8248    /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
8249    /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
8250    /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
8251    /// was `[]`.
8252    pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
8253        let key = self.realm.well_known_key(WellKnown::Iterator);
8254        let method = self.read_field_key(value, &key)?;
8255        if !matches!(&method, Value::Object(object) if object.is_callable()) {
8256            return Ok(None);
8257        }
8258        let iterator = self.get_iterator(value)?;
8259        let mut out = Vec::new();
8260        loop {
8261            let (element, done) = self.iterator_step(&iterator)?;
8262            if done {
8263                return Ok(Some(out));
8264            }
8265            out.push(element);
8266        }
8267    }
8268
8269    /// One step of an internal iterator: the value and whether it is exhausted.
8270    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
8271        // A real iterator (`next` is a function) answers with a result object.
8272        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
8273            let result =
8274                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
8275            let Some(result) = result.as_object().cloned() else {
8276                return Err(self.type_error("iterator result is not an object"));
8277            };
8278            let done = self
8279                .get_property(&result, "done")?
8280                .is_some_and(|value| value.to_boolean());
8281            let value = self
8282                .get_property(&result, "value")?
8283                .unwrap_or(Value::Undefined);
8284            return Ok((value, done));
8285        }
8286        // An iterator whose `next` is not callable is treated as exhausted, which is
8287        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
8288        // that are not iterable at all.
8289        Ok((Value::Undefined, true))
8290    }
8291
8292    /// `[...iterable]`: append everything the iterator yields, and answer the next
8293    /// index.
8294    ///
8295    /// This goes through the same iterator machinery `for-of` uses rather than copying
8296    /// an array's elements, because a spread source is any iterable: a string spreads
8297    /// into its characters and an array iterator spreads into its results. Handling
8298    /// only arrays made `[..."ab"]` come out empty with no error at all.
8299    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
8300        let Some(target) = array.as_object().cloned() else {
8301            return Ok(0);
8302        };
8303        let start = target.array_length().unwrap_or(0);
8304        let mut added = 0;
8305        let iterator = self.get_iterator(iterable)?;
8306        loop {
8307            let (value, done) = self.iterator_step(&iterator)?;
8308            if done {
8309                break;
8310            }
8311            target.array_set(start + added, value);
8312            added += 1;
8313        }
8314        Ok((start + added) as i32)
8315    }
8316
8317    /// How an uncaught exception is reported.
8318    ///
8319    /// The reference reports a pending exception through `JS_PrintValue`, which ends
8320    /// up calling the thrown value's `toString`, so `throw new TypeError("x")` prints
8321    /// `TypeError: x`. Reading `name`/`message` off the object directly got this wrong
8322    /// two ways: `name` usually lives on the prototype rather than on the instance, and
8323    /// a thrown non-error object was not consulted at all, coming out as
8324    /// `[object Object]`. Routing through `ToString` keeps every case on one path and
8325    /// honours a user-defined `toString`, as the reference does.
8326    ///
8327    /// A `toString` that throws must not take the reporter down with it, so that case
8328    /// falls back to the type-level rendering. The reference's printer also walks into
8329    /// plain objects (`throw 1, {a:1}` prints `{ a: 1 }`); that formatting is a gap
8330    /// shared with `console.log`.
8331    pub fn describe_exception(&mut self, value: &Value) -> String {
8332        self.to_js_string(value).unwrap_or_else(|_| display(value))
8333    }
8334
8335    /// The current call stack, formatted the way `qjs` prints `error.stack`.
8336    ///
8337    /// One `    at name (file:line:col)` line per active frame, innermost first. The
8338    /// position is the one recorded for the instruction each frame is stopped on, which
8339    /// is why the compiler builds a pc-to-position table per function: without it a
8340    /// trace could only name the function, not the line inside it.
8341    ///
8342    /// A frame whose code has no positions prints just `(file)`, matching the
8343    /// reference's output for stripped bytecode.
8344    pub fn stack_trace(&self) -> String {
8345        self.stack_trace_skipping(0)
8346    }
8347
8348    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
8349    fn stack_trace_skipping(&self, skip: usize) -> String {
8350        let mut out = String::new();
8351        let mut skip = skip;
8352        // Natives run on the Rust stack, so they sit innermost. They never re-enter
8353        // JavaScript, which is what makes it correct to emit them all before the
8354        // bytecode frames rather than interleaved.
8355        for (name, _) in self.native_frames.iter().rev() {
8356            if skip > 0 {
8357                skip -= 1;
8358                continue;
8359            }
8360            out.push_str("    at ");
8361            out.push_str(name);
8362            out.push_str(" (native)\n");
8363        }
8364        for frame in self.frames.iter().rev() {
8365            if skip > 0 {
8366                skip -= 1;
8367                continue;
8368            }
8369            let code = &frame.code.code;
8370            let file = code.filename.as_deref().unwrap_or("<input>");
8371            // The name comes from the function *object*, not from the compiled code:
8372            // an anonymous function expression is named by the property it is stored
8373            // in (`{valueOf: function(){}}`), which only the object knows.
8374            let bound_name = match &frame.callee {
8375                Value::Object(object) => {
8376                    object
8377                        .own_property("name")
8378                        .and_then(|property| match property.value {
8379                            Some(Value::String(text)) if !text.wtf8().is_empty() => {
8380                                Some(text.to_string_lossy().into_owned())
8381                            }
8382                            _ => None,
8383                        })
8384                }
8385                _ => None,
8386            };
8387            out.push_str("    at ");
8388            out.push_str(bound_name.as_deref().unwrap_or(&code.name));
8389            match code.position_at(frame.at as u32) {
8390                Some((line, column)) => {
8391                    out.push_str(&format!(" ({file}:{line}:{column})\n"));
8392                }
8393                None => out.push_str(&format!(" ({file})\n")),
8394            }
8395        }
8396        out
8397    }
8398
8399    /// Give an anonymous function the name of the property it is stored in.
8400    ///
8401    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
8402    /// enumerable and not configurable, and a function that already has a real name
8403    /// keeps it.
8404    ///
8405    /// "Already named" means a *non-empty* name: every function object is created with
8406    /// a `name` of `""` so the property exists on all of them, and treating that empty
8407    /// string as a name left every anonymous function nameless — which is how a stack
8408    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
8409    fn set_function_name(&mut self, function: &Value, name: &str) {
8410        let Value::Object(object) = function else {
8411            return;
8412        };
8413        // `SetFunctionName` applies to *functions* and classes only, and only when they are
8414        // anonymous. Without the callability guard, `{value: someObject}` renamed
8415        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
8416        // on the right-hand side of a property. That is how a `zipKeyed` result object
8417        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
8418        // has no `NamedEvaluation` at all.
8419        if !object.is_callable() {
8420            return;
8421        }
8422        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
8423            && !existing.wtf8().is_empty()
8424        {
8425            return;
8426        }
8427        let text = self.string(name);
8428        object.define("name", Property::name_or_length(text));
8429    }
8430
8431    // -- global declarations -----------------------------------------------
8432
8433    /// Declare a global binding, creating its reference cell.
8434    /// Declare a `var` or function global, whose home is the global object.
8435    ///
8436    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
8437    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
8438    /// such as `print`, or a redeclaration — is left alone.
8439    pub fn declare_var_global(&mut self, name: &str) {
8440        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
8441        // global object is exactly the leak `typeof my_var === "undefined"` after
8442        // `eval("var my_var=2")` rules out.
8443        if let Some(scope) = self.eval_scope.as_mut() {
8444            scope.entry(name.to_string()).or_insert(Value::Undefined);
8445            return;
8446        }
8447        // A sloppy direct eval declares into its *caller's* variable environment. Doing
8448        // this on the global object instead made `eval("var c = 1")` inside a parameter
8449        // list overwrite a global `c`, and made two calls to the same function share one
8450        // binding.
8451        if let Some(cell) = self.declare_eval_local(name) {
8452            cell.set(Value::Undefined);
8453            return;
8454        }
8455        let global = self.realm.global.clone();
8456        if global.own_property(name).is_some() {
8457            return;
8458        }
8459        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
8460        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
8461        // whole point of that trick and what lets `Object.defineProperty` reshape it
8462        // afterwards. `eval_scope` is `Some` while an eval is running.
8463        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
8464        global.define(
8465            name,
8466            Property {
8467                value: Some(Value::Undefined),
8468                writable: true,
8469                enumerable: true,
8470                configurable: from_eval,
8471                ..Property::default()
8472            },
8473        );
8474    }
8475
8476    /// Declare a *lexical* global binding, which starts in its dead zone.
8477    ///
8478    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
8479    /// global object and is created when its initialiser runs.
8480    pub fn declare_global(&mut self, name: &str, is_const: bool) {
8481        if is_const {
8482            self.realm.lexical_consts.insert(name.to_string());
8483        }
8484        if !self.realm.globals.contains_key(name) {
8485            // `Uninitialized` rather than `Undefined`: the binding exists but is not
8486            // readable until its initialiser runs, and that is what `let x` before
8487            // `x = 1` has to observe.
8488            let cell = self.new_cell(Value::Uninitialized);
8489            self.realm.globals.insert(name.to_string(), cell);
8490            self.realm.declared.push(name.to_string());
8491        }
8492    }
8493}
8494
8495/// The bytecode and environment of a function object, if it is a bytecode function.
8496///
8497/// Extracted before a call so no borrow of the object is held across it.
8498fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
8499    function.with(|data| match &data.kind {
8500        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
8501        _ => None,
8502    })
8503}
8504
8505/// A native call target, extracted before the call so no borrow is held.
8506enum NativeCall {
8507    Native(NativeFn),
8508    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
8509    Bound {
8510        target: Value,
8511        this: Value,
8512        leading: Vec<Value>,
8513    },
8514    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
8515    Revoker(crate::object::ProxyRef),
8516    /// A promise's `resolve`.
8517    PromiseResolve(Gc<JsObject>),
8518    /// A promise's `reject`.
8519    PromiseReject(Gc<JsObject>),
8520    /// One continuation of an `await`.
8521    AwaitResume {
8522        coroutine: Gc<JsObject>,
8523        promise: Gc<JsObject>,
8524        kind: ResumeKind,
8525    },
8526    /// One element of a `Promise` combinator settling.
8527    CombinatorSettle {
8528        state: Gc<JsObject>,
8529        index: usize,
8530        fulfilled: bool,
8531    },
8532    /// One of `Promise.prototype.finally`'s two shims.
8533    FinallyShim {
8534        callback: Option<Value>,
8535        fulfilled: bool,
8536    },
8537    /// Settle a promise with a fixed outcome.
8538    SettlePromise {
8539        promise: Gc<JsObject>,
8540        value: Value,
8541        rejected: bool,
8542    },
8543    /// Continue an async generator after its `await` settled.
8544    GeneratorResume {
8545        generator: Gc<JsObject>,
8546        promise: Gc<JsObject>,
8547        kind: ResumeKind,
8548    },
8549    /// Read a module namespace's binding out of its cell.
8550    ModuleBinding(Gc<Cell>),
8551    /// Answer a pending async-generator method with `{value, done}`.
8552    YieldResult {
8553        promise: Gc<JsObject>,
8554        done: bool,
8555    },
8556    /// One step of `AsyncDisposableStack.disposeAsync`.
8557    DisposeStep {
8558        remaining: Gc<JsObject>,
8559        promise: Gc<JsObject>,
8560        error: Value,
8561        rejected: bool,
8562    },
8563}
8564
8565/// What a store does when the object refuses the write.
8566#[derive(Clone, Copy, PartialEq, Eq)]
8567pub enum DeleteFailure {
8568    /// Raise a `TypeError`, which is what strict mode and every built-in does.
8569    Throw,
8570    /// Ignore the write, which is what a sloppy-mode assignment does.
8571    Ignore,
8572}
8573
8574/// Whether `object` is a `Date` instance, by the class tag it carries.
8575///
8576/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
8577/// builtins module depending on the interpreter's conversion order.
8578fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
8579    interp
8580        .internal_get(object, "_class")
8581        .is_some_and(|value| value.to_js_string() == "Date")
8582}
8583
8584/// Which type `ToPrimitive` prefers when it converts an object.
8585#[derive(Clone, Copy, PartialEq, Eq)]
8586pub enum Hint {
8587    /// The default hint, which behaves like [`Hint::Number`].
8588    Default,
8589    /// `Number(obj)` and the arithmetic operators.
8590    Number,
8591    /// `String(obj)` and `ToPropertyKey`.
8592    String,
8593}
8594
8595/// Which table a binding slot indexes, for the messages that name it.
8596#[derive(Clone, Copy)]
8597enum VarSlot {
8598    Loc,
8599    Closure,
8600}
8601
8602/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
8603fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
8604    Ok(this)
8605}
8606
8607/// An internal iterator: the sequence plus a cursor.
8608pub(crate) struct Iterator {
8609    pub(crate) object: Value,
8610    pub(crate) next: Value,
8611}
8612
8613/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
8614/// and plain `a` for a method.
8615///
8616/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
8617/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
8618/// reads `at get a (file:1:2)`.
8619fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
8620    match flags & 3 {
8621        1 => format!("get {key}"),
8622        2 => format!("set {key}"),
8623        _ => key.to_string(),
8624    }
8625}
8626
8627/// Define a method or accessor property, per the `define_method` flag byte.
8628///
8629/// The low two bits pick value/getter/setter and bit 2 marks the property
8630/// enumerable.
8631///
8632/// A getter and a setter arrive as two separate `define_method` instructions, and the
8633/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
8634/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
8635/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
8636/// `JS_DefineProperty`, which leaves the other half alone.
8637fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
8638    let enumerable = flags & 4 != 0;
8639    let kind = flags & 3;
8640    let existing = object.own_property_key(key);
8641    let property = match kind {
8642        1 => Property {
8643            getter: Some(function),
8644            // The setter half, if this literal already defined one.
8645            setter: existing
8646                .filter(Property::is_accessor)
8647                .and_then(|p| p.setter),
8648            enumerable,
8649            configurable: true,
8650            ..Property::default()
8651        },
8652        2 => Property {
8653            getter: existing
8654                .filter(Property::is_accessor)
8655                .and_then(|p| p.getter),
8656            setter: Some(function),
8657            enumerable,
8658            configurable: true,
8659            ..Property::default()
8660        },
8661        _ => Property {
8662            value: Some(function),
8663            writable: true,
8664            enumerable,
8665            configurable: true,
8666            ..Property::default()
8667        },
8668    };
8669    object.define_key(key, property);
8670}
8671
8672// ---------------------------------------------------------------------------
8673// Operand decoding
8674// ---------------------------------------------------------------------------
8675
8676/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
8677///
8678/// Jump operands are resolved to absolute byte offsets here, because the encoding
8679/// stores them relative to the byte after the opcode and every use site would
8680/// otherwise repeat that arithmetic.
8681fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
8682    let op = Opcode::from_u8(*code.get(pc)?)?;
8683    let info = op.info();
8684    let base = pc + 1;
8685    let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
8686    let read_u16 = |offset: usize| -> u32 {
8687        let mut value = 0u32;
8688        for index in 0..2 {
8689            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
8690        }
8691        value
8692    };
8693    let read_u32 = |offset: usize| -> u32 {
8694        let mut value = 0u32;
8695        for index in 0..4 {
8696            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
8697        }
8698        value
8699    };
8700    let jump = |offset: usize, width: usize| -> u32 {
8701        let raw = match width {
8702            1 => read_u8(offset) as u8 as i8 as i64,
8703            2 => read_u16(offset) as u16 as i16 as i64,
8704            _ => read_u32(offset) as i32 as i64,
8705        };
8706        (base as i64 + raw) as u32
8707    };
8708    let (a, b) = match info.format {
8709        OpFormat::None
8710        | OpFormat::NoneInt
8711        | OpFormat::NoneLoc
8712        | OpFormat::NoneArg
8713        | OpFormat::NoneVarRef
8714        | OpFormat::Npopx => (0, 0),
8715        OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
8716        OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
8717        OpFormat::Label8 => (jump(0, 1), 0),
8718        OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
8719            (read_u16(0), 0)
8720        }
8721        OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
8722        OpFormat::Label16 => (jump(0, 2), 0),
8723        OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
8724        OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
8725        OpFormat::I32 | OpFormat::Label => (
8726            if info.format == OpFormat::Label {
8727                jump(0, 4)
8728            } else {
8729                read_u32(0) as i32 as u32
8730            },
8731            0,
8732        ),
8733        OpFormat::AtomU8 | OpFormat::AtomLabelU8 => (read_u32(0), read_u8(4)),
8734        OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
8735            (read_u32(0), read_u16(4))
8736        }
8737    };
8738    Some((op, a, b, pc + info.size as usize))
8739}
8740
8741/// How `print` renders a value: the reference's `JS_PrintValue`.
8742///
8743/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
8744/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
8745/// The format is reproduced closely because the test suite compares output text:
8746///
8747/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
8748/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
8749/// * a cycle prints `[circular N]` with `N` the stack index of the object;
8750/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
8751///   end print as `<N empty item(s)>`;
8752/// * a string is quoted inside a container but raw at the top level, which is why
8753///   `print("x")` and `print(["x"])` differ.
8754pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
8755    // A string argument is printed raw: `js_print` converts it with `ToString`
8756    // instead of dumping it, and the quoting only appears inside a container.
8757    if let Value::String(text) = value {
8758        return text.to_string_lossy().into_owned();
8759    }
8760    let mut printer = Printer {
8761        interp,
8762        out: String::new(),
8763        stack: Vec::new(),
8764    };
8765    printer.value(value, 0);
8766    printer.out
8767}
8768
8769/// The internal class name an object carries, when it has one.
8770fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
8771    interp
8772        .internal_get(object, "_class")
8773        .map(|value| value.to_js_string())
8774}
8775
8776/// A string property, looked up the way `GetProperty` does: own first, then the
8777/// prototype chain. Needed because the print formatter holds the interpreter
8778/// immutably and so cannot run getters.
8779fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
8780    let mut current = Some(object.clone());
8781    // Bounded, because a prototype cycle would otherwise loop forever.
8782    for _ in 0..100 {
8783        let node = current?;
8784        if let Some(property) = node.own_property(name)
8785            && let Some(value) = property.value
8786        {
8787            return Some(value.to_js_string());
8788        }
8789        current = node.with(|data| data.proto.clone());
8790    }
8791    None
8792}
8793
8794/// The `JS_PrintValue` state: output, and the objects currently being printed.
8795struct Printer<'a, 'rt> {
8796    /// Kept for the class-name lookups that typed arrays and `Date` will need.
8797    #[allow(dead_code)]
8798    interp: &'a Interp<'rt>,
8799    out: String,
8800    stack: Vec<Gc<JsObject>>,
8801}
8802
8803impl Printer<'_, '_> {
8804    /// Depth past which a container is summarised by its class name.
8805    const MAX_DEPTH: usize = 2;
8806
8807    fn value(&mut self, value: &Value, level: usize) {
8808        match value {
8809            Value::Undefined
8810            | Value::Uninitialized
8811            | Value::Hole
8812            | Value::CatchOffset(_)
8813            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
8814            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
8815            // The printer writes a bigint the way the language spells one, so a dump is
8816            // unambiguous about which kind of number it is showing.
8817            Value::BigInt(big) => {
8818                self.out.push_str(&big.to_decimal_string());
8819                self.out.push('n');
8820            }
8821            Value::Null => self.out.push_str("null"),
8822            Value::Bool(true) => self.out.push_str("true"),
8823            Value::Bool(false) => self.out.push_str("false"),
8824            Value::Int(number) => self.out.push_str(&number.to_string()),
8825            Value::Float(number) => {
8826                self.out
8827                    .push_str(&crate::value::number_to_string_for_print(*number));
8828            }
8829            Value::String(text) => self.print_string(&text.to_string_lossy()),
8830            Value::Object(object) => self.object(object, level),
8831        }
8832    }
8833
8834    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
8835        // A cycle is reported rather than followed; the index is where the object
8836        // already sits in the print stack, which is what the reference shows.
8837        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
8838            self.out.push_str(&format!("[circular {index}]"));
8839            return;
8840        }
8841        if object.is_callable() {
8842            let name = object
8843                .own_property("name")
8844                .and_then(|property| property.value)
8845                .map(|value| value.to_js_string())
8846                .unwrap_or_default();
8847            if name.is_empty() {
8848                self.out.push_str("[Function (anonymous)]");
8849            } else {
8850                self.out.push_str(&format!("[Function {name}]"));
8851            }
8852            return;
8853        }
8854        if level >= Self::MAX_DEPTH {
8855            let class = if object.is_array() { "Array" } else { "Object" };
8856            self.out.push_str(&format!("[{class}]"));
8857            return;
8858        }
8859        // `Date` and `Error` print as themselves rather than as bags of properties:
8860        // the ISO string, and `Name: message` followed by the trace.
8861        if let Some(class) = class_of(self.interp, object) {
8862            if class == "Date" {
8863                self.date(object);
8864                return;
8865            }
8866            if class == "Error" {
8867                self.error(object);
8868                return;
8869            }
8870        }
8871        self.stack.push(object.clone());
8872        if object.is_array() {
8873            self.array(object, level);
8874        } else {
8875            self.plain_object(object, level);
8876        }
8877        self.stack.pop();
8878    }
8879
8880    /// A Date prints as its ISO string; an invalid one falls through to the plain
8881    /// object form, the way the reference falls back when `toISOString` throws.
8882    fn date(&mut self, object: &Gc<JsObject>) {
8883        let value = self
8884            .interp
8885            .internal_get(object, "_date_value")
8886            .map(|value| value.to_number());
8887        match value.and_then(crate::builtins::date::iso_string) {
8888            Some(text) => self.out.push_str(&text),
8889            None => self.plain_object(object, 0),
8890        }
8891    }
8892
8893    /// `Name: message`, then the trace with its trailing newline removed.
8894    fn error(&mut self, object: &Gc<JsObject>) {
8895        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
8896        self.out.push_str(&name);
8897        if let Some(message) = inherited(object, "message")
8898            && !message.is_empty()
8899        {
8900            self.out.push_str(": ");
8901            self.out.push_str(&message);
8902        }
8903        if let Some(stack) = inherited(object, "stack") {
8904            self.out.push('\n');
8905            self.out.push_str(stack.trim_end_matches('\n'));
8906        }
8907    }
8908
8909    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
8910        let elements = object.array_elements().unwrap_or_default();
8911        self.out.push_str("[ ");
8912        // An interior hole means the array is "sparse": the reference prints those
8913        // as `index: value` pairs and says nothing about the holes themselves, while
8914        // a hole run at the end becomes a single `<N empty items>` note.
8915        let last_present = elements
8916            .iter()
8917            .rposition(|value| !matches!(value, Value::Hole));
8918        let has_interior_hole = match last_present {
8919            Some(last) => elements[..last]
8920                .iter()
8921                .any(|value| matches!(value, Value::Hole)),
8922            None => false,
8923        };
8924        let mut first = true;
8925        if has_interior_hole {
8926            let mut index = 0;
8927            while index < elements.len() {
8928                let value = &elements[index];
8929                if matches!(value, Value::Hole) {
8930                    index += 1;
8931                    continue;
8932                }
8933                if !first {
8934                    self.out.push_str(", ");
8935                }
8936                first = false;
8937                self.out.push_str(&format!("{index}: "));
8938                self.value(value, level + 1);
8939                index += 1;
8940            }
8941        } else {
8942            for (index, value) in elements.iter().enumerate() {
8943                if matches!(value, Value::Hole) {
8944                    continue;
8945                }
8946                if !first {
8947                    self.out.push_str(", ");
8948                }
8949                first = false;
8950                let _ = index;
8951                self.value(value, level + 1);
8952            }
8953            if let Some(last) = last_present {
8954                let trailing = elements.len() - last - 1;
8955                if trailing > 0 {
8956                    if !first {
8957                        self.out.push_str(", ");
8958                    }
8959                    self.out.push_str(&format!(
8960                        "<{trailing} empty item{}>",
8961                        if trailing > 1 { "s" } else { "" }
8962                    ));
8963                }
8964            } else if !elements.is_empty() {
8965                let count = elements.len();
8966                self.out.push_str(&format!(
8967                    "<{count} empty item{}>",
8968                    if count > 1 { "s" } else { "" }
8969                ));
8970            }
8971        }
8972        self.out.push_str(" ]");
8973    }
8974
8975    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
8976        self.out.push_str("{ ");
8977        let mut first = true;
8978        for key in object.own_keys() {
8979            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
8980                continue;
8981            };
8982            if !property.enumerable {
8983                continue;
8984            }
8985            if !first {
8986                self.out.push_str(", ");
8987            }
8988            first = false;
8989            self.out
8990                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
8991                    &key.to_string_lossy(),
8992                )));
8993            self.out.push_str(": ");
8994            // An accessor has no value to dump; the reference names the half that
8995            // exists instead of calling it.
8996            if property.is_accessor() {
8997                let text = match (property.getter.is_some(), property.setter.is_some()) {
8998                    (true, true) => "[Getter/Setter]",
8999                    (false, true) => "[Setter]",
9000                    _ => "[Getter]",
9001                };
9002                self.out.push_str(text);
9003            } else {
9004                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
9005            }
9006        }
9007        self.out.push_str(" }");
9008    }
9009
9010    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
9011    fn print_string(&mut self, text: &str) {
9012        self.out.push('"');
9013        for character in text.chars() {
9014            match character {
9015                '"' => self.out.push_str("\\\""),
9016                '\\' => self.out.push_str("\\\\"),
9017                '\n' => self.out.push_str("\\n"),
9018                '\r' => self.out.push_str("\\r"),
9019                '\t' => self.out.push_str("\\t"),
9020                c if (c as u32) < 0x20 => {
9021                    self.out.push_str(&format!("\\u{:04x}", c as u32));
9022                }
9023                c => self.out.push(c),
9024            }
9025        }
9026        self.out.push('"');
9027    }
9028}
9029
9030/// How `print` renders a value.
9031///
9032/// `ToString`, except that negative zero keeps its sign — the reference's host
9033/// printer does that while `String(-0)` is `"0"`.
9034pub fn display(value: &Value) -> String {
9035    match value {
9036        Value::Float(number) => crate::value::number_to_string_for_print(*number),
9037        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
9038            "undefined".to_string()
9039        }
9040        other => other.to_js_string(),
9041    }
9042}
9043
9044// ---------------------------------------------------------------------------
9045// Numeric operators
9046// ---------------------------------------------------------------------------
9047
9048/// `a + b` keeping the `Int` representation when it fits.
9049fn add_numbers(left: Value, right: Value) -> Value {
9050    match (&left, &right) {
9051        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9052            Some(sum) => Value::Int(sum),
9053            None => Value::Float(*a as f64 + *b as f64),
9054        },
9055        _ => Value::Float(left.to_number() + right.to_number()),
9056    }
9057}
9058
9059/// The arithmetic operators other than `+`, which needs string concatenation.
9060fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
9061    use Opcode::*;
9062    let (a, b) = (left.to_number(), right.to_number());
9063    Ok(match op {
9064        Sub => match (&left, &right) {
9065            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
9066                Some(value) => Value::Int(value),
9067                None => Value::Float(a - b),
9068            },
9069            _ => Value::Float(a - b),
9070        },
9071        Mul => Value::Float(a * b),
9072        Div => Value::Float(a / b),
9073        Mod => Value::Float(js_mod(a, b)),
9074        Pow => Value::Float(a.powf(b)),
9075        And => Value::Int(left.to_int32() & right.to_int32()),
9076        Or => Value::Int(left.to_int32() | right.to_int32()),
9077        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
9078        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
9079        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
9080        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
9081        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
9082        // fits the small-integer representation stays an `Int`; the rest become a
9083        // float, which is how the reference keeps `n >>> 0` non-negative.
9084        Shr => {
9085            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
9086            match i32::try_from(shifted) {
9087                Ok(value) => Value::Int(value),
9088                Err(_) => Value::Float(shifted as f64),
9089            }
9090        }
9091        _ => Value::Float(a),
9092    })
9093}
9094
9095/// `%`, which follows the sign of the dividend rather than Rust's.
9096fn js_mod(left: f64, right: f64) -> f64 {
9097    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
9098        return f64::NAN;
9099    }
9100    if right.is_infinite() {
9101        return left;
9102    }
9103    let remainder = left % right;
9104    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
9105    // the spec makes the sign match the dividend.
9106    if remainder == 0.0 {
9107        0.0f64.copysign(left)
9108    } else {
9109        remainder
9110    }
9111}
9112
9113fn negate(value: Value) -> Value {
9114    match value {
9115        Value::Int(0) => Value::Float(-0.0),
9116        Value::Int(i) => Value::Int(-i),
9117        other => Value::Float(-other.to_number()),
9118    }
9119}
9120
9121fn increment(value: Value) -> Value {
9122    match value {
9123        Value::Int(i) => match i.checked_add(1) {
9124            Some(next) => Value::Int(next),
9125            None => Value::Float(i as f64 + 1.0),
9126        },
9127        other => Value::Float(other.to_number() + 1.0),
9128    }
9129}
9130
9131fn decrement(value: Value) -> Value {
9132    match value {
9133        Value::Int(i) => match i.checked_sub(1) {
9134            Some(next) => Value::Int(next),
9135            None => Value::Float(i as f64 - 1.0),
9136        },
9137        other => Value::Float(other.to_number() - 1.0),
9138    }
9139}
9140
9141/// Compare a `BigInt` with an `f64` on their mathematical values.
9142///
9143/// Neither side is rounded to the other's precision: the number is split into its integer
9144/// part (compared as an exact bigint) and its fraction, which is what decides the answer
9145/// when the integer parts are equal. An infinite value is larger than every bigint.
9146fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
9147    use std::cmp::Ordering;
9148    if number.is_nan() {
9149        return None;
9150    }
9151    if number.is_infinite() {
9152        return Some(if number > 0.0 {
9153            Ordering::Less
9154        } else {
9155            Ordering::Greater
9156        });
9157    }
9158    let truncated = number.trunc();
9159    // A number wider than `i128` still has an exact integer part, but no bigint form we can
9160    // build cheaply; the sign of the difference is all that is needed, so compare against
9161    // the bigint's own magnitude instead.
9162    if truncated.abs() >= 1.7e38 {
9163        let big_as_f64 = big.to_f64();
9164        return big_as_f64.partial_cmp(&number);
9165    }
9166    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
9167    match big.cmp(&integer) {
9168        Ordering::Equal => {
9169            // Same integer part: the fraction decides, and a negative number's fraction is
9170            // below the integer (`-1.5` truncates to `-1`).
9171            if number > truncated {
9172                Some(Ordering::Less)
9173            } else if number < truncated {
9174                Some(Ordering::Greater)
9175            } else {
9176                Some(Ordering::Equal)
9177            }
9178        }
9179        other => Some(other),
9180    }
9181}