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::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25    Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26    NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27    lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34    /// A JavaScript exception carrying the thrown value.
35    Throw(Value),
36    /// The runtime ran out of memory.
37    OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45    /// Keep executing the current frame.
46    Continue,
47    /// The current frame returned this value.
48    Return(Value),
49    /// The frame parked at a suspension point, with the yielded value on its stack.
50    ///
51    /// Only a generator or an async function can produce this, and only its own frame —
52    /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53    /// detached and handed to the generator object, which is what lets it resume later
54    /// with its locals and operand stack intact.
55    Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61    /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62    /// without passing a value, because there is no `yield` expression to receive one.
63    Initial,
64    /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65    Yield,
66    /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67    /// `{value, done}` object from the inner iterator and is handed straight back.
68    YieldStar,
69    /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70    /// what was yielded is the plain value and still has to be awaited and wrapped —
71    /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72    /// made it pass a bare value through as if it were an iterator result, so
73    /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74    AsyncYieldStar,
75    /// `await expr`: the value is a promise the async machinery has to settle first.
76    Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84    /// The global object.
85    pub global: Gc<JsObject>,
86    /// `Object.prototype`.
87    pub object_proto: Gc<JsObject>,
88    /// `Function.prototype`, which is itself callable.
89    pub function_proto: Gc<JsObject>,
90    /// `Array.prototype`.
91    pub array_proto: Gc<JsObject>,
92    /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
93    pub array_constructor: Option<Gc<JsObject>>,
94    /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
95    pub promise_constructor: Option<Gc<JsObject>>,
96    /// Reference cells for globals declared by the script.
97    ///
98    /// A declared global is read with `get_var` (by name) but written with
99    /// `put_var_ref` (through the cell), so the cell is what makes a function
100    /// declaration and its uses agree on one binding.
101    pub globals: BTreeMap<String, Gc<Cell>>,
102    /// Names of the globals that came from a *declaration*, which are
103    /// non-configurable properties of the global object.
104    pub declared: Vec<String>,
105    /// Names among the lexical globals that are `const`.
106    ///
107    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
108    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
109    /// path does not carry, so a store through it would look like a plain `let`. The
110    /// realm records it once, at declaration, and answers for every reader.
111    pub lexical_consts: BTreeSet<String>,
112    /// The error constructors by class name, so a runtime error can throw a real
113    /// `TypeError` instance rather than a look-alike object.
114    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
115    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
116    pub string_proto: Option<Gc<JsObject>>,
117    /// `Number.prototype`.
118    pub number_proto: Option<Gc<JsObject>>,
119    /// `Boolean.prototype`.
120    pub boolean_proto: Option<Gc<JsObject>>,
121    /// `BigInt.prototype`.
122    pub bigint_proto: Option<Gc<JsObject>>,
123    /// `Error.prototype`, the prototype of every error instance.
124    pub error_proto: Gc<JsObject>,
125    /// `Date.prototype`, so the constructor can build an instance in the
126    /// function-call form (`Date()` returns a string) without going through `new`.
127    pub date_proto: Gc<JsObject>,
128    /// `%GeneratorPrototype%`, the prototype of every generator object.
129    pub generator_proto: Gc<JsObject>,
130    /// `Promise.prototype`, the prototype of every promise.
131    pub promise_proto: Option<Gc<JsObject>>,
132    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
133    pub async_generator_proto: Option<Gc<JsObject>>,
134    /// `Symbol.prototype`.
135    pub symbol_proto: Option<Gc<JsObject>>,
136    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
137    /// `_date_value`.
138    ///
139    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
140    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
141    /// language does not have and `new Error()` listed `_class` beside `message` and
142    /// `stack` — and a caller that copies every own property (which
143    /// `Object.create(null, props)` effectively does) tried to write an internal name and
144    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
145    /// and `JSON.stringify`, while remaining an ordinary traced property.
146    ///
147    /// `RefCell` because interning is memoisation rather than observable state: filling the
148    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
149    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
150    /// built while reporting a failure must not require an exclusive borrow.
151    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
152
153    /// The `Symbol.for` registry: `key -> symbol`.
154    ///
155    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
156    /// symbol every time within one script while a fresh realm starts empty.
157    pub symbol_registry: BTreeMap<String, Value>,
158    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
159    pub regexp_proto: Option<Gc<JsObject>>,
160    /// The `RegExp` constructor.
161    pub regexp_ctor: Option<Gc<JsObject>>,
162    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
163    ///
164    /// The prototype rather than the constructor on purpose: a script that replaces
165    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
166    /// error wrapping, which the `using` test suite checks explicitly.
167    pub suppressed_error_proto: Option<Gc<JsObject>>,
168    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
169    pub disposable_stack_proto: Option<Gc<JsObject>>,
170    /// `Map.prototype`.
171    pub map_proto: Option<Gc<JsObject>>,
172    /// `Set.prototype`.
173    pub set_proto: Option<Gc<JsObject>>,
174    /// Every live `FinalizationRegistry`, held weakly.
175    ///
176    /// The cleanup callback has to run from a *safe point* — a place where script is not
177    /// already executing and no engine borrow is held — and the collector cannot enumerate
178    /// heap objects by type. Registering each registry here gives the drain a list to walk.
179    ///
180    /// The handles are weak on purpose: a registry the script dropped must be collectable,
181    /// and it must not be resurrected merely because the drain knew about it. Entries whose
182    /// target has expired are swept out as the drain walks, so the vector does not grow
183    /// without bound in a program that creates many short-lived registries.
184    pub finalization_registries: Vec<WeakGc<JsObject>>,
185    /// `ArrayBuffer.prototype`.
186    pub array_buffer_proto: Option<Gc<JsObject>>,
187    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
188    pub typed_array_proto: Option<Gc<JsObject>>,
189    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
190    ///
191    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
192    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
193    /// `"Object"` and `r instanceof Int32Array` is false.
194    pub typed_array_protos: Vec<Gc<JsObject>>,
195    /// `DataView.prototype`.
196    pub data_view_proto: Option<Gc<JsObject>>,
197    /// The `AsyncDisposableStack` prototype.
198    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
199    /// `Iterator.prototype`.
200    pub iterator_proto: Option<Gc<JsObject>>,
201    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
202    ///
203    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
204    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
205    /// `[object Iterator Helper]`).
206    pub iterator_helper_proto: Option<Gc<JsObject>>,
207    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
208    /// that was not already an `Iterator`.
209    ///
210    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
211    /// untouched and does *not* override `@@toStringTag`, so
212    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
213    pub iterator_wrap_proto: Option<Gc<JsObject>>,
214    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
215    pub generator_function_proto: Option<Gc<JsObject>>,
216    /// `%AsyncFunction.prototype%`.
217    pub async_function_proto: Option<Gc<JsObject>>,
218    /// `%AsyncGeneratorFunction.prototype%`.
219    pub async_generator_function_proto: Option<Gc<JsObject>>,
220    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
221    ///
222    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
223    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
224    /// prototype per iterator made every array iterator's prototype distinct.
225    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
226    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
227    ///
228    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
229    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
230    /// both faster and impossible to break from a script.
231    well_known_symbols: WellKnownSymbols,
232    /// The classes the host registered, and the prototype each one hands its instances.
233    pub host_classes: HostClasses,
234}
235
236/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
237///
238/// One per realm, because a class id is only meaningful within the runtime that handed it
239/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
240/// a host class cannot collide.
241pub struct HostClasses {
242    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
243    /// `JS_GetOpaque(val, 0)` has to match nothing.
244    next_id: u32,
245    /// What each registered class does.
246    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
247    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
248    ///
249    /// A strong reference, so the prototype a host installed outlives every script
250    /// reference to it — which is what `JS_SetClassProto` promises.
251    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
252}
253
254impl HostClasses {
255    fn new() -> HostClasses {
256        HostClasses {
257            next_id: 1,
258            defs: std::collections::BTreeMap::new(),
259            protos: std::collections::BTreeMap::new(),
260        }
261    }
262
263    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
264    pub fn register(&mut self, def: ClassDef) -> ClassId {
265        let id = ClassId::from_raw(self.next_id);
266        self.next_id += 1;
267        self.defs.insert(id, std::rc::Rc::new(def));
268        id
269    }
270
271    /// Register `def` under an id the caller already has (`JS_NewClass`).
272    ///
273    /// The C API splits "get an id" from "register a class" because a module may be
274    /// initialised lazily; registering twice under one id replaces the definition, and an
275    /// object created under the old one keeps the old behaviour, since it carries its own
276    /// reference.
277    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
278        if !id.is_valid() {
279            return false;
280        }
281        // Keep the counter past any id handed out explicitly, so a later `register` cannot
282        // reuse one.
283        self.next_id = self.next_id.max(id.get() + 1);
284        self.defs.insert(id, std::rc::Rc::new(def));
285        true
286    }
287
288    /// What `id` was registered with.
289    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
290        self.defs.get(&id).cloned()
291    }
292
293    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
294    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
295        self.protos.insert(id, proto);
296    }
297
298    /// The prototype installed for `id`, if the host installed one.
299    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
300        self.protos.get(&id).cloned()
301    }
302
303    /// How many classes the host registered.
304    pub fn len(&self) -> usize {
305        self.defs.len()
306    }
307
308    /// Whether no class has been registered.
309    pub fn is_empty(&self) -> bool {
310        self.defs.is_empty()
311    }
312}
313
314impl Default for HostClasses {
315    fn default() -> HostClasses {
316        HostClasses::new()
317    }
318}
319
320/// One binding of the frame that called `eval`, so the eval'd code can read and
321/// write it by name.
322struct EvalBinding {
323    /// The name it was declared with.
324    name: String,
325    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
326    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
327    /// a function that declares `a` must find that `a`.
328    frame: usize,
329    /// Which table of that frame it lives in.
330    slot: EvalSlot,
331    /// The slot index within that table.
332    index: usize,
333}
334
335/// Which table of a frame an [`EvalBinding`] indexes.
336#[derive(Clone, Copy)]
337enum EvalSlot {
338    Arg,
339    Local,
340}
341
342/// One activation record.
343struct Frame {
344    /// The bytecode being run.
345    code: Gc<CompiledCode>,
346    /// The cells this closure captured.
347    env: Gc<ClosureEnv>,
348    /// The `this` binding.
349    this: Value,
350    /// Argument slots, sized to the declared parameter count.
351    args: Vec<Value>,
352    /// How many values the caller actually passed, which is what `arguments.length`
353    /// reports and what `...rest` slices from.
354    passed_count: usize,
355    /// The passed values, **only when they do not fit in [`Self::args`]**.
356    ///
357    /// `args` is sized to the declared parameters, so a call that passes no more than
358    /// that already holds every passed value in its first `passed_count` slots — copying
359    /// them here as well was two writes and a buffer per call, on the hottest path in
360    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
361    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
362    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
363    /// its own copy.
364    ///
365    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
366    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
367    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
368    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
369    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
370    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
371    #[allow(clippy::box_collection)]
372    passed_overflow: Option<Box<Vec<Value>>>,
373    /// Local slots.
374    locals: Vec<Value>,
375    /// Reference cells for this frame's own captured bindings.
376    cells: Vec<Gc<Cell>>,
377    /// The operand stack.
378    stack: Vec<Value>,
379    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
380    local_vars: Option<Gc<LocalVars>>,
381
382    /// Index of the next instruction, not a byte offset.
383    ///
384    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
385    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
386    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
387    /// `Frame`, and `frames.push` copies the whole struct on every call.
388    pc: usize,
389    /// Byte offset of the instruction being executed, which is what a stack trace
390    /// reports. `pc` has already moved past it by the time an instruction runs.
391    ///
392    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
393    at: usize,
394    /// The callee, so a native builtin can tell which constructor it is.
395    callee: Value,
396    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
397    new_target: Value,
398    /// What this frame costs against [`Interp::stack_limit`], in bytes.
399    ///
400    /// Cached rather than recomputed because it is charged on every call and a call is the
401    /// hottest thing in the interpreter.
402    cost: usize,
403    /// [`Interp::stack_used`] before this frame was pushed.
404    ///
405    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
406    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
407    /// leave the counter wrong. There are eight places that drop frames; one subtraction
408    /// forgotten in any of them would leak budget until the depth limit moved.
409    stack_base: usize,
410    /// Whether this frame's body ended in a `tail_call`.
411    ///
412    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
413    /// with its own frame just like `call` does and only skips storing the result
414    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
415    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
416    /// pushed as usual, and this marker makes its return value the *caller's* return
417    /// value without running the instructions after the call.
418    tail: bool,
419}
420
421impl Frame {
422    /// Read a local slot, taking the frame as `self`.
423    ///
424    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
425    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
426    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
427    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
428    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
429    #[inline]
430    fn read_loc(&self, slot: usize) -> Value {
431        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
432        if cell == -1 {
433            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
434        }
435        match self.cells.get(cell as usize) {
436            Some(cell) => cell.get(),
437            None => Value::Undefined,
438        }
439    }
440
441    /// [`Self::read_loc`] for an argument slot.
442    #[inline]
443    fn read_arg(&self, slot: usize) -> Value {
444        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
445        if cell == -1 {
446            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
447        }
448        match self.cells.get(cell as usize) {
449            Some(cell) => cell.get(),
450            None => Value::Undefined,
451        }
452    }
453
454    /// The values the caller actually passed, which is what `arguments` exposes.
455    ///
456    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
457    fn passed(&self) -> &[Value] {
458        match &self.passed_overflow {
459            Some(values) => values,
460            None => &self.args[..self.passed_count],
461        }
462    }
463
464    /// The decoded instructions of the function this frame runs.
465    ///
466    /// A method rather than `frame.code.insns` at the call site so that the borrow is
467    /// obviously of the frame — the dispatch loop holds one across a `get`.
468    fn insns(&self) -> &[crate::insn::Insn] {
469        &self.code.insns
470    }
471}
472
473impl js_gc::Trace for Frame {
474    fn trace(&self, tracer: &mut js_gc::Tracer) {
475        self.code.trace(tracer);
476        self.env.trace(tracer);
477        self.this.trace(tracer);
478        for value in &self.args {
479            value.trace(tracer);
480        }
481        for value in self.passed() {
482            value.trace(tracer);
483        }
484        for value in &self.locals {
485            value.trace(tracer);
486        }
487        for cell in &self.cells {
488            cell.trace(tracer);
489        }
490        if let Some(local_vars) = &self.local_vars {
491            tracer.visit(local_vars);
492        }
493        for value in &self.stack {
494            value.trace(tracer);
495        }
496        self.callee.trace(tracer);
497        self.new_target.trace(tracer);
498    }
499}
500
501/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
502/// emitted `if_false` treats as "keep going".
503/// How many finished frames' value buffers are kept for reuse.
504const RECYCLE_SLOTS: usize = 8;
505
506/// The largest buffer worth keeping. See [`Interp::free_values`].
507const RECYCLE_MAX_CAPACITY: usize = 4096;
508
509const RESUME_NEXT: i32 = 0;
510/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
511/// generator fall into its `return_async`.
512const RESUME_RETURN: i32 = 1;
513/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
514/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
515/// must forward the exception into the inner iterator rather than finish.
516const RESUME_THROW: i32 = 2;
517
518/// One microtask.
519///
520/// The queue holds *data* rather than closures because its contents are GC values: a
521/// closure would be invisible to the collector, and a pending reaction is exactly the
522/// kind of thing that must keep its handlers and its promise alive.
523pub enum Job {
524    /// A `then` reaction about to run.
525    Reaction {
526        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
527        handler: Option<Value>,
528        /// The value or reason to call it with.
529        argument: Value,
530        /// Whether the source promise rejected, which decides the pass-through kind.
531        rejected: bool,
532        /// The promise the answer settles.
533        promise: Gc<JsObject>,
534    },
535    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
536    Thenable {
537        /// The `then` that was found on the value.
538        then: Value,
539        /// The thenable itself, which becomes `then`'s `this`.
540        value: Value,
541        /// The promise being resolved.
542        promise: Gc<JsObject>,
543    },
544    /// A pending `import(specifier)`.
545    Import {
546        /// The specifier, already converted to a string.
547        specifier: String,
548        /// The module that asked, which the specifier resolves against.
549        referrer: String,
550        /// The promise `import()` handed back.
551        promise: Gc<JsObject>,
552    },
553    /// An async generator resuming after the value it awaited settled.
554    GeneratorResume {
555        /// The async generator to continue.
556        generator: Gc<JsObject>,
557        /// The promise the pending method returned.
558        promise: Gc<JsObject>,
559        /// Whether this delivers the value or raises the reason.
560        kind: ResumeKind,
561        /// The settled value, or the rejection reason.
562        value: Value,
563    },
564    /// An async function resuming after the value it awaited settled.
565    Resume {
566        /// The body, parked in a coroutine.
567        coroutine: Gc<JsObject>,
568        /// The promise the async function handed its caller.
569        promise: Gc<JsObject>,
570        /// Whether this resumption delivers a value or raises one.
571        kind: ResumeKind,
572        /// The settled value, or the rejection reason.
573        value: Value,
574    },
575}
576
577/// One macro-task: work the event loop owes the script but has not run yet.
578///
579/// The microtask queue ([`Job`]) is different: those run before the host regains control.
580/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
581/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
582/// logic: the engine decides *what* is due, the host decides *how to wait*.
583///
584/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
585/// reference counting even though nothing else references it — the same rule the `HostFn`
586/// documentation states from the other side (a host closure must not hold a `Gc`, so the
587/// `Gc` lives here instead).
588pub enum Task {
589    /// A `setTimeout` that is due at `due_at`.
590    ///
591    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
592    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
593    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
594    /// would give this engine a timer the reference cannot produce, with nothing to
595    /// compare it against.
596    Timer {
597        /// The id `setTimeout` returned, for `clearTimeout`.
598        id: i32,
599        /// What to call when it fires.
600        callback: Value,
601        /// When it becomes runnable, as a monotonic instant.
602        due_at: std::time::Instant,
603    },
604}
605
606/// A descriptor the host has to poll, and which directions have a handler.
607///
608/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
609/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
610/// blocks on it, and the host reports back through [`Interp::fire_fd`].
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub struct FdInterest {
613    /// The descriptor to watch.
614    pub fd: i32,
615    /// Whether `os.setReadHandler` registered a callback.
616    pub read: bool,
617    /// Whether `os.setWriteHandler` registered a callback.
618    pub write: bool,
619}
620
621/// The callbacks registered for one descriptor, per direction.
622#[derive(Default)]
623pub(crate) struct FdHandlers {
624    /// `os.setReadHandler`'s callback.
625    pub read: Option<Value>,
626    /// `os.setWriteHandler`'s callback.
627    pub write: Option<Value>,
628}
629
630/// The file name `eval` reports, which the reference does not inherit from the caller.
631///
632/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
633/// reference and the names show up in stack traces.
634/// The description of the private symbol a class brand is made from.
635///
636/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
637/// place no script can reach, since no expression can name a private symbol.
638const BRAND_DESCRIPTION: &str = "brand";
639
640/// One validated property lookup.
641///
642/// Covers both own-property hits and prototype hits. The second kind was deliberately left
643/// uncached at first ("a prototype hit depends on more than the object and the name"), and
644/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
645/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
646/// names on every iteration (measured: 100 ns per call over an empty loop).
647pub struct FieldCache {
648    /// The name, so two different properties of one object do not collide.
649    key: PropertyKey,
650    /// Where the value was found, relative to the chain below.
651    index: usize,
652    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
653    level: u8,
654    /// The receiver and every prototype down to (and including) the level that answered,
655    /// each with the length of its property table at the time.
656    ///
657    /// That length is the whole guard, and it is sufficient for the ways the answer can
658    /// change without a lookup: adding or deleting any property moves it, and a
659    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
660    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
661    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
662    /// the one that was cached.
663    ///
664    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
665    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
666    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
667}
668
669/// How many links of a prototype chain a [`FieldCache`] remembers.
670///
671/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
672/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
673/// at three.
674const MAX_CACHED_CHAIN: usize = 3;
675
676/// A remembered global-variable lookup.
677///
678/// A `var` global is an ordinary property of the global object, so reading one walks the
679/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
680/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
681/// fixed by the bytecode, and the slot in the object's table only changes if the global
682/// object is mutated, which the index-and-name check below catches.
683pub struct GlobalCache {
684    /// The global object the lookup was resolved on, weakly.
685    object: js_gc::WeakGc<JsObject>,
686    /// Index of the data property in the global object's table.
687    index: usize,
688}
689
690/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
691const GLOBAL_CACHE_SLOTS: usize = 1024;
692
693/// How many property lookups are remembered.
694///
695/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
696/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
697/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
698/// lookup itself. Making it bigger stops helping: the working set of a real program's
699/// property sites is bounded by its code size.
700const FIELD_CACHE_SLOTS: usize = 4096;
701
702/// How much the heap may grow past the last `out of memory` before saying it again.
703///
704/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
705/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
706/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
707/// because it looks like it works. The reference gets this for free: it fails inside
708/// `js_malloc`, and its printing path happens not to allocate.
709///
710/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
711/// allocating is stopped within a rounding error of the limit) and far above what a
712/// handler needs.
713const OOM_HYSTERESIS: usize = 64 * 1024;
714
715/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
716pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
717
718/// How many instructions run between polls of [`Interp::interrupt`].
719///
720/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
721/// order of magnitude on both implementations — which is what lets a C driver compare its
722/// output byte for byte (see `scripts/m15-capi.sh --embed`).
723pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
724
725/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
726///
727/// Chosen so that the byte budget is what actually decides for every ordinary
728/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
729/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
730/// millions of frames.
731pub const MAX_FRAMES: usize = 200_000;
732
733const EVAL_FILE: &str = "<input>";
734
735/// The file name `std.evalScript` reports.
736const EVAL_SCRIPT_FILE: &str = "<evalScript>";
737
738/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
739///
740/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
741/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
742fn clamp_delay(delay_ms: f64) -> std::time::Duration {
743    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
744    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
745    // non-positive delay mean "due now".
746    if delay_ms.is_nan() || delay_ms <= 0.0 {
747        return std::time::Duration::ZERO;
748    }
749    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
750}
751
752impl js_gc::Trace for Task {
753    fn trace(&self, tracer: &mut js_gc::Tracer) {
754        let Task::Timer { callback, .. } = self;
755        callback.trace(tracer);
756    }
757}
758
759/// What one turn of the event loop did, so the caller cannot spin by accident.
760///
761/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
762/// core until the timer is due. Naming the three cases makes the wait explicit.
763#[derive(Debug, Clone, Copy, PartialEq, Eq)]
764pub enum Turn {
765    /// Something ran. Call again immediately — there may be more ready work.
766    Ran,
767    /// Nothing is runnable, but descriptors are registered: the host must poll
768    /// [`Interp::pending_fds`] for at most this long, then report readiness with
769    /// [`Interp::fire_fd`].
770    ///
771    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
772    /// the failure this project treats as worst — a handler that silently never fires —
773    /// so the two cannot be confused by accident.
774    Poll(std::time::Duration),
775    /// Nothing is runnable yet, but something is pending. Block at most this long, then
776    /// call again.
777    Wait(std::time::Duration),
778    /// Nothing is pending at all: the loop is done.
779    Done,
780}
781
782impl js_gc::Trace for Job {
783    fn trace(&self, tracer: &mut js_gc::Tracer) {
784        match self {
785            Job::Reaction {
786                handler,
787                argument,
788                promise,
789                ..
790            } => {
791                if let Some(handler) = handler {
792                    handler.trace(tracer);
793                }
794                argument.trace(tracer);
795                tracer.visit(promise);
796            }
797            Job::Thenable {
798                then,
799                value,
800                promise,
801            } => {
802                then.trace(tracer);
803                value.trace(tracer);
804                tracer.visit(promise);
805            }
806            Job::Resume {
807                coroutine,
808                promise,
809                value,
810                ..
811            } => {
812                tracer.visit(coroutine);
813                tracer.visit(promise);
814                value.trace(tracer);
815            }
816            Job::Import { promise, .. } => tracer.visit(promise),
817            Job::GeneratorResume {
818                generator,
819                promise,
820                value,
821                ..
822            } => {
823                tracer.visit(generator);
824                tracer.visit(promise);
825                value.trace(tracer);
826            }
827        }
828    }
829}
830
831/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833pub enum ResumeKind {
834    /// The generator was just created and is being run to its first suspension.
835    Start,
836    /// `next(v)`.
837    Next,
838    /// `return(v)`.
839    Return,
840    /// `throw(e)`.
841    Throw,
842}
843
844/// A generator object's saved execution.
845///
846/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
847/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
848/// separately allocated buffers.
849pub struct GeneratorState {
850    /// The detached frame, or `None` once the generator has finished or while it runs.
851    frame: Option<Frame>,
852    /// How far it got.
853    phase: GeneratorPhase,
854    /// Whether the last suspension was an `await` rather than a `yield`.
855    ///
856    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
857    /// value and a magic number, because the emitted code branches on which method
858    /// resumed it, while an `await` simply continues with its value. Getting this wrong
859    /// leaves an extra value on the operand stack that the next instruction then
860    /// consumes — a wrong answer rather than a crash.
861    parked_on_await: bool,
862    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
863    ///
864    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
865    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
866    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
867    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
868    /// delegating. Tracking it as part of the phase, the way the reference splits
869    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
870    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
871    /// exception and never reached `xs.throw`.
872    parked_on_yield_star: bool,
873    /// Pending `next`/`return`/`throw` calls, oldest first.
874    ///
875    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
876    /// called back to back must answer in that order, with the second call's value
877    /// arriving at the *second* `yield`. Running each call straight into the body — which
878    /// is what this engine did before — delivered the last queued value to whichever
879    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
880    /// `a === b ===` the final argument.
881    ///
882    /// The front entry is the one being served; it stays there (with `async_busy` set)
883    /// until its promise settles, because an `await` inside the body is a suspension of
884    /// the *driver*, not the end of the request.
885    requests: std::collections::VecDeque<AsyncRequest>,
886    /// Whether the front request is in flight.
887    async_busy: bool,
888}
889
890/// How one async-generator request ended.
891enum AsyncOutcome {
892    /// The method answered this `{value, done}`.
893    Value(Value),
894    /// The body threw.
895    Error(Value),
896}
897
898/// One queued `next`/`return`/`throw` on an async generator: the reference's
899/// `JSAsyncGeneratorRequest`.
900pub struct AsyncRequest {
901    /// Which method was called.
902    kind: ResumeKind,
903    /// Its argument.
904    value: Value,
905    /// The promise the method answered.
906    promise: Gc<JsObject>,
907}
908
909/// Which of §27.5.3.3's states a generator is in.
910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
911enum GeneratorPhase {
912    /// Created, `initial_yield` reached, body not entered.
913    SuspendedStart,
914    /// Parked at a `yield`.
915    SuspendedYield,
916    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
917    Executing,
918    /// Finished; the frame is gone.
919    Completed,
920}
921
922impl js_gc::Trace for GeneratorState {
923    fn trace(&self, tracer: &mut js_gc::Tracer) {
924        if let Some(frame) = &self.frame {
925            frame.trace(tracer);
926        }
927        for request in &self.requests {
928            request.value.trace(tracer);
929            tracer.visit(&request.promise);
930        }
931    }
932}
933
934/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
935/// them in.
936///
937/// Each is a field rather than a map entry because the runtime reads them on hot paths
938/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
939/// failure — reaching a default here means the builtin did not install, and every
940/// accessor panics rather than silently answering `undefined`.
941///
942/// [`builtins::symbol`]: crate::builtins::symbol
943#[derive(Default)]
944pub struct WellKnownSymbols {
945    /// The symbol values, positionally. Empty until `Symbol` installs.
946    symbols: Vec<Value>,
947}
948
949/// Which well-known symbol a caller wants.
950///
951/// A typed accessor beats passing a name around: a typo is a compile error rather than
952/// an `undefined` key that quietly matches nothing.
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954pub enum WellKnown {
955    /// `Symbol.toPrimitive`.
956    ToPrimitive,
957    /// `Symbol.iterator`.
958    Iterator,
959    /// `Symbol.match`.
960    Match,
961    /// `Symbol.matchAll`.
962    MatchAll,
963    /// `Symbol.replace`.
964    Replace,
965    /// `Symbol.search`.
966    Search,
967    /// `Symbol.split`.
968    Split,
969    /// `Symbol.toStringTag`.
970    ToStringTag,
971    /// `Symbol.isConcatSpreadable`.
972    IsConcatSpreadable,
973    /// `Symbol.hasInstance`.
974    HasInstance,
975    /// `Symbol.species`.
976    Species,
977    /// `Symbol.unscopables`.
978    Unscopables,
979    /// `Symbol.asyncIterator`.
980    AsyncIterator,
981    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
982    Disposable,
983    /// `Symbol.asyncDispose` — the awaited form.
984    AsyncDisposable,
985}
986
987impl WellKnown {
988    /// The index `Symbol`'s installer creates this symbol at.
989    fn index(self) -> usize {
990        match self {
991            WellKnown::ToPrimitive => 0,
992            WellKnown::Iterator => 1,
993            WellKnown::Match => 2,
994            WellKnown::MatchAll => 3,
995            WellKnown::Replace => 4,
996            WellKnown::Search => 5,
997            WellKnown::Split => 6,
998            WellKnown::ToStringTag => 7,
999            WellKnown::IsConcatSpreadable => 8,
1000            WellKnown::HasInstance => 9,
1001            WellKnown::Species => 10,
1002            WellKnown::Unscopables => 11,
1003            WellKnown::AsyncIterator => 12,
1004            WellKnown::Disposable => 13,
1005            WellKnown::AsyncDisposable => 14,
1006        }
1007    }
1008}
1009
1010impl Realm {
1011    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1012    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1013        self.well_known_symbols.symbols = symbols;
1014    }
1015
1016    /// A well-known symbol.
1017    pub fn well_known(&self, which: WellKnown) -> Value {
1018        self.well_known_symbols
1019            .symbols
1020            .get(which.index())
1021            .cloned()
1022            .unwrap_or(Value::Undefined)
1023    }
1024
1025    /// The well-known symbol as a property key.
1026    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1027        match self.well_known(which) {
1028            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1029            // Unreachable once `Symbol` has installed; an empty string key matches
1030            // nothing, which degrades to "the object has no such method".
1031            _ => PropertyKey::from(String::new()),
1032        }
1033    }
1034}
1035
1036/// The interpreter: a realm plus a frame stack.
1037pub struct Interp<'a> {
1038    /// The heap everything is allocated on.
1039    pub heap: &'a Heap,
1040    /// The realm.
1041    pub realm: Realm,
1042    /// Active frames, outermost first.
1043    frames: Vec<Frame>,
1044    /// Value buffers from frames that have finished, reused by the next call.
1045    ///
1046    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1047    /// the locals and the operand stack — and free all four on return. `call:recursion`
1048    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1049    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1050    ///
1051    /// Bounded in both directions: a few buffers per kind, and none larger than
1052    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1053    /// and keeping its buffer would pin that memory for the rest of the run.
1054    free_values: Vec<Vec<Value>>,
1055    /// A strict-mode `eval`'s own variable scope, while its script runs.
1056    ///
1057    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1058    /// become a global. Name lookups still fall through to the realm, which is why
1059    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1060    eval_scope: Option<BTreeMap<String, Value>>,
1061    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1062    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1063    eval_depth: usize,
1064    /// The calling frame's own bindings, which the running `eval` can read and write.
1065    ///
1066    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1067    /// come from the frame, and a write is applied back to the frame (or to the cell
1068    /// the frame captured) when the eval finishes. That is what makes
1069    /// `f("a = 3")` visible to the caller as `a === 3`.
1070    eval_bindings: Vec<EvalBinding>,
1071    /// The calling frame's `arguments`, while an `eval` runs.
1072    ///
1073    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1074    /// own yet still has to see the caller's `arguments`.
1075    eval_arguments: Option<Value>,
1076    /// The `with` objects live at the moment the running `eval` started, innermost first.
1077    ///
1078    /// `None` outside an eval, which is what keeps a finished block's object from
1079    /// shadowing ordinary bytecode reads.
1080    eval_with: Option<Vec<Gc<JsObject>>>,
1081    /// The bindings the running direct `eval` makes visible, as name → cell.
1082    ///
1083    /// Set for the duration of an eval and then restored, but every closure created
1084    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1085    /// `eval("f = () => i")` work after the eval has returned.
1086    active_eval_scope: Option<Gc<EvalScope>>,
1087    /// The frame that called the direct `eval` currently running, if any.
1088    ///
1089    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1090    /// on the global object, which is what keeps
1091    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1092    /// gives each call its own `x`.
1093    eval_caller: Option<Option<usize>>,
1094    /// The caller's `new.target`, while an `eval` runs.
1095    ///
1096    /// The eval'd code is a script with no constructor of its own, so it inherits the
1097    /// one the enclosing function was called with.
1098    eval_new_target: Option<Value>,
1099    /// `new.target` for the frame about to be pushed.
1100    ///
1101    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1102    /// value reaches the frame without threading a parameter through every call site.
1103    pending_new_target: Option<Value>,
1104    /// Names of the native functions currently executing, outermost first.
1105    ///
1106    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1107    /// trace still names it with `(native)` instead of a position, so the names are
1108    /// tracked separately and stitched into [`Interp::stack_trace`].
1109    ///
1110    /// The third field is how many bytecode frames were live when the native was entered,
1111    /// which is what places it *among* them rather than before all of them. Native
1112    /// functions used to be emitted up front on the grounds that they never re-enter
1113    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1114    /// The natives currently running, innermost last: the function object and the
1115    /// depth it was entered at.
1116    ///
1117    /// The *name* is deliberately not stored. It used to be, read with
1118    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1119    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1120    /// benchmark. A stack trace is built rarely; it can read the name then.
1121    native_frames: Vec<(Gc<JsObject>, usize)>,
1122    /// The native function currently executing, for the ones that have to know *which*
1123    /// function they are — a typed-array constructor reads its element type off itself.
1124    ///
1125    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1126    /// reports whatever the enclosing bytecode frame was called with.
1127    current_native: Option<Gc<JsObject>>,
1128    /// Text written by `print` and friends, in order.
1129    ///
1130    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1131    /// once at the end, which is also when upstream's line buffering becomes
1132    /// visible for the cases compared here.
1133    pub output: String,
1134    /// Where `print` also writes, as it goes. `output` keeps the full log for
1135    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1136    ///
1137    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1138    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1139    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1140    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1141    /// would show a script's output all at once when it finished.
1142    pub output_sink: Option<Box<dyn std::io::Write>>,
1143    /// Where recent property reads found their value.
1144    ///
1145    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1146    /// table remembering *which object* and *which entry of its property table* answered a
1147    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1148    /// can move; the property can become an accessor), which is what makes a stale entry a
1149    /// miss rather than a wrong answer.
1150    ///
1151    /// The object is held weakly: a cache that held it strongly would keep up to
1152    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1153    /// program cannot see and cannot work around.
1154    pub field_cache: Vec<Option<FieldCache>>,
1155    /// Global lookups, by binding slot. See [`GlobalCache`].
1156    global_cache: Vec<Option<GlobalCache>>,
1157    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1158    /// under its limit. See [`Interp::check_memory`].
1159    pub oom_reported_at: usize,
1160    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1161    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1162    ///
1163    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1164    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1165    /// host that wants to stop a runaway script must not have to wait for it to return.
1166    ///
1167    /// Two things this cannot do, both of them differences a host can observe:
1168    ///
1169    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1170    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1171    ///   needs a signal that the `catch` machinery does not see, which is a change to
1172    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1173    ///   a host that stops the script itself.
1174    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1175    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1176    ///   both, so the difference is when the counter hits zero, not whether it will.
1177    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1178    /// Instructions until the next [`Interp::interrupt`] poll.
1179    pub interrupt_counter: u32,
1180    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1181    ///
1182    /// A separate field from [`Interp::uncatchable`] because the two live for different
1183    /// spans. This one is the host's standing request; it survives the start of an
1184    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1185    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1186    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1187    /// cleared it before the script it was set for had a chance to throw.
1188    pub uncatchable_next: bool,
1189    /// Whether the exception now unwinding may be caught by a `catch`.
1190    ///
1191    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1192    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1193    /// a host stopping a runaway loop is not fought by the loop.
1194    ///
1195    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1196    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1197    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1198    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1199    pub uncatchable: bool,
1200    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1201    ///
1202    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1203    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1204    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1205    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1206    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1207    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1208    ///
1209    /// The numbers come out close for the same reason a C frame and a heap frame of this
1210    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1211    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1212    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1213    /// `crates/quickjs-cli/tests/limits.rs`.
1214    pub stack_limit: usize,
1215    /// The most frames that may be live at once, whatever the byte budget says.
1216    ///
1217    /// A second bound for a reason the reference does not have: our frames cost less than
1218    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1219    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1220    /// `--stack-size 1G` from being a memory bomb.
1221    pub max_frames: usize,
1222    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1223    ///
1224    /// Script execution does not return until this has drained, which is what makes
1225    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1226    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1227    /// not a `for`.
1228    pub(crate) jobs: std::collections::VecDeque<Job>,
1229    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1230    ///
1231    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1232    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1233    pub(crate) tasks: Vec<Task>,
1234    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1235    /// barrier'd evaluation started.
1236    ///
1237    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1238    /// lets a REPL report an error from the line it just evaluated without also reporting
1239    /// its own readline loop.
1240    trace_barriers: Vec<usize>,
1241    /// `os.signal` handlers, keyed by signal number.
1242    ///
1243    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1244    /// a handler cannot be freed while it is still registered.
1245    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1246    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1247    ///
1248    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1249    /// that is only reachable from a host closure could be freed while still registered.
1250    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1251    /// The next timer id.
1252    ///
1253    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1254    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1255    next_timer_id: i32,
1256    /// Errors thrown by timer callbacks, already rendered.
1257    ///
1258    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1259    /// that throws has no promise behind it. Both are reported by the host at the end of
1260    /// the loop, but only one is fixed up by a later `.catch`.
1261    timer_errors: Vec<String>,
1262    /// The module registry, keyed by canonical name.
1263    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1264    /// How the host turns a specifier into bytes.
1265    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1266    /// The module the host was asked to run, for `import.meta.main`.
1267    pub main_module_name: Option<String>,
1268    /// Module bodies currently running, innermost last.
1269    ///
1270    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1271    /// this is the only place that knows which module that is.
1272    pub module_stack: Vec<String>,
1273    /// Rejections that no handler has claimed, with the promise they belong to.
1274    ///
1275    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1276    /// reason alone cannot say whether somebody eventually listened.
1277    unhandled: Vec<(Gc<JsObject>, Value)>,
1278}
1279
1280impl<'a> Interp<'a> {
1281    /// Build an interpreter over `heap`, with a fresh realm.
1282    pub fn new(heap: &'a Heap) -> Interp<'a> {
1283        let object_proto = JsObject::ordinary(heap, None);
1284        let function_proto = JsObject::function(
1285            heap,
1286            Some(object_proto.clone()),
1287            Callable::Native {
1288                func: |_, _, _| Ok(Value::Undefined),
1289                own_instance: false,
1290            },
1291        );
1292        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1293        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1294        let mut interp = Interp {
1295            heap,
1296            realm: Realm {
1297                global,
1298                object_proto,
1299                function_proto,
1300                array_proto,
1301                array_constructor: None,
1302                promise_constructor: None,
1303                globals: BTreeMap::new(),
1304                declared: Vec::new(),
1305                lexical_consts: BTreeSet::new(),
1306                errors: BTreeMap::new(),
1307                string_proto: None,
1308                number_proto: None,
1309                boolean_proto: None,
1310                bigint_proto: None,
1311                error_proto: JsObject::ordinary(heap, None),
1312                date_proto: JsObject::ordinary(heap, None),
1313                generator_proto: JsObject::ordinary(heap, None),
1314                promise_proto: None,
1315                async_generator_proto: None,
1316                symbol_proto: None,
1317                symbol_registry: BTreeMap::new(),
1318                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1319                regexp_proto: None,
1320                regexp_ctor: None,
1321                suppressed_error_proto: None,
1322                disposable_stack_proto: None,
1323                map_proto: None,
1324                set_proto: None,
1325                finalization_registries: Vec::new(),
1326                array_buffer_proto: None,
1327                typed_array_proto: None,
1328                typed_array_protos: Vec::new(),
1329                data_view_proto: None,
1330                async_disposable_stack_proto: None,
1331                iterator_proto: None,
1332                iterator_helper_proto: None,
1333                iterator_wrap_proto: None,
1334                generator_function_proto: None,
1335                async_function_proto: None,
1336                async_generator_function_proto: None,
1337                iterator_protos: std::collections::BTreeMap::new(),
1338                well_known_symbols: WellKnownSymbols::default(),
1339                host_classes: HostClasses::new(),
1340            },
1341            frames: Vec::new(),
1342            free_values: Vec::new(),
1343            global_cache: {
1344                let mut cache = Vec::new();
1345                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1346                cache
1347            },
1348            eval_scope: None,
1349            eval_depth: 0,
1350            eval_bindings: Vec::new(),
1351            eval_arguments: None,
1352            eval_with: None,
1353            active_eval_scope: None,
1354            eval_caller: None,
1355            pending_new_target: None,
1356            eval_new_target: None,
1357            native_frames: Vec::new(),
1358            current_native: None,
1359            output: String::new(),
1360            output_sink: None,
1361            field_cache: {
1362                let mut cache = Vec::new();
1363                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1364                cache
1365            },
1366            oom_reported_at: 0,
1367            interrupt: None,
1368            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1369            uncatchable_next: false,
1370            uncatchable: false,
1371            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1372            // absent.
1373            stack_limit: DEFAULT_STACK_SIZE,
1374            max_frames: MAX_FRAMES,
1375            jobs: std::collections::VecDeque::new(),
1376            tasks: Vec::new(),
1377            trace_barriers: Vec::new(),
1378            signal_handlers: std::collections::BTreeMap::new(),
1379            fd_handlers: std::collections::BTreeMap::new(),
1380            next_timer_id: 1,
1381            timer_errors: Vec::new(),
1382            modules: std::collections::BTreeMap::new(),
1383            module_loader: None,
1384            main_module_name: None,
1385            module_stack: Vec::new(),
1386            unhandled: Vec::new(),
1387        };
1388        crate::builtins::install(&mut interp);
1389        interp
1390    }
1391
1392    // -- allocation helpers -------------------------------------------------
1393
1394    /// A new string value.
1395    /// A `BigInt` value from a computed big integer.
1396    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1397        Value::BigInt(Gc::new(self.heap, value))
1398    }
1399
1400    /// A string value from bytes that are already WTF-8, which is how a string with an
1401    /// unpaired surrogate reaches a `Value`.
1402    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1403        Value::string_wtf8(self.heap, text)
1404    }
1405
1406    /// A new string value, from text that is valid UTF-8.
1407    pub fn string(&self, text: impl Into<String>) -> Value {
1408        Value::string(self.heap, text)
1409    }
1410
1411    /// A new ordinary object with the given prototype.
1412    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1413        JsObject::ordinary(self.heap, proto)
1414    }
1415
1416    // -- host classes -------------------------------------------------------
1417
1418    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1419    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1420        self.realm.host_classes.register(def)
1421    }
1422
1423    /// Register `def` under an id the host already holds (`JS_NewClass`).
1424    ///
1425    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1426    /// `JS_NewClass`.
1427    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1428        self.realm.host_classes.define(id, def)
1429    }
1430
1431    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1432    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1433        self.realm.host_classes.set_proto(id, proto);
1434    }
1435
1436    /// The prototype installed for `id`, if any.
1437    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1438        self.realm.host_classes.proto(id)
1439    }
1440
1441    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1442    ///
1443    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1444    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1445    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1446    /// host installed none.
1447    ///
1448    /// Answers `None` for an id that was never registered: the C API would return an
1449    /// exception, and silently making an ordinary object instead would move the failure to
1450    /// the first `JS_GetOpaque` that no longer matches.
1451    pub fn new_host_object(
1452        &mut self,
1453        proto: Option<Gc<JsObject>>,
1454        class_id: ClassId,
1455    ) -> Option<Gc<JsObject>> {
1456        let class = self.realm.host_classes.def(class_id)?;
1457        let proto = proto
1458            .or_else(|| self.realm.host_classes.proto(class_id))
1459            .or_else(|| Some(self.realm.object_proto.clone()));
1460        Some(JsObject::host_object(self.heap, proto, class_id, class))
1461    }
1462
1463    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1464    ///
1465    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1466    /// object, it is an object of another class, or the class never got a payload. A host
1467    /// that has to tell them apart uses [`JsObject::host_class_id`].
1468    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1469        let object = value.as_object()?;
1470        if object.host_class_id()? != class_id {
1471            return None;
1472        }
1473        object.host_opaque()
1474    }
1475
1476    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1477    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1478        match value.as_object() {
1479            Some(object) => object.set_host_opaque(opaque),
1480            None => false,
1481        }
1482    }
1483
1484    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1485    ///
1486    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1487    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1488    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1489    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1490    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1491    /// said `[object Object]` instead of `[object Array Iterator]`.
1492    ///
1493    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1494    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1495    /// its own.
1496    pub fn new_iterator_prototype(
1497        &mut self,
1498        tag: &str,
1499        next: crate::object::NativeFn,
1500    ) -> Gc<JsObject> {
1501        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1502            return existing.clone();
1503        }
1504        let parent = self.realm.iterator_proto.clone();
1505        let proto = self.new_object(parent);
1506        let next = self.new_native("next", 0, next);
1507        proto.define(
1508            "next",
1509            Property::with_attributes(Value::Object(next), true, false),
1510        );
1511        let key = self.realm.well_known_key(WellKnown::Iterator);
1512        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1513        proto.define_key(
1514            &key,
1515            Property::with_attributes(Value::Object(identity), true, false),
1516        );
1517        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1518        let tag_value = self.string(tag);
1519        proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
1520        self.realm
1521            .iterator_protos
1522            .insert(tag.to_string(), proto.clone());
1523        proto
1524    }
1525
1526    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1527    ///
1528    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1529    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1530    /// produced. That is why the two branches are not merged.
1531    pub fn object_own_property_keys(
1532        &mut self,
1533        object: &Gc<JsObject>,
1534    ) -> JsResult<Vec<PropertyKey>> {
1535        if let Some(keys) = self.proxy_own_keys(object)? {
1536            return Ok(keys);
1537        }
1538        // Integer-like keys ascending, then the string keys in insertion order, then the
1539        // symbols — the order every schema that walks an object expects.
1540        let entries = object.property_entries();
1541        let mut numeric: Vec<u32> = Vec::new();
1542        // An integer-indexed exotic object reports its indices as own keys even though they
1543        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1544        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1545        // order). The length is asked per call, so a resizable buffer's view reports the
1546        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1547        if object.typed_array_parts().is_some() {
1548            for index in 0..object.typed_array_length().unwrap_or(0) {
1549                // `u32::try_from` cannot fail for a real length, but the length is a
1550                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1551                // as an array index and one element beyond is not.
1552                match u32::try_from(index) {
1553                    Ok(index) => numeric.push(index),
1554                    Err(_) => break,
1555                }
1556            }
1557        }
1558        let mut strings: Vec<PropertyKey> = Vec::new();
1559        let mut symbols: Vec<PropertyKey> = Vec::new();
1560        for (key, _) in entries {
1561            match &key {
1562                // A class-private name is never reported by any enumeration: that is the
1563                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1564                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1565                // symbol skip, `Object.assign`) therefore cannot see it.
1566                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1567                PropertyKey::Symbol(_) => symbols.push(key),
1568                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1569                    Some(index) => {
1570                        if !numeric.contains(&index) {
1571                            numeric.push(index);
1572                        }
1573                    }
1574                    None => strings.push(key),
1575                },
1576            }
1577        }
1578        numeric.sort_unstable();
1579        let mut keys: Vec<PropertyKey> = numeric
1580            .into_iter()
1581            .map(|index| PropertyKey::from(index.to_string()))
1582            .collect();
1583        keys.extend(strings);
1584        keys.extend(symbols);
1585        Ok(keys)
1586    }
1587
1588    /// The state behind a promise object, or `None` when `object` is not one.
1589    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1590        object.with(|data| match &data.kind {
1591            ObjectKind::Promise(state) => Some(state.clone()),
1592            _ => None,
1593        })
1594    }
1595
1596    /// A new pending promise.
1597    pub fn new_promise(&mut self) -> Gc<JsObject> {
1598        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1599        // the one place every promise is built, and a subclass that builds its instances
1600        // somewhere else would be invisible to `instanceof`.
1601        let default = self.realm.promise_proto.clone();
1602        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1603        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1604        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1605        // `prototype` getter therefore still gets a working promise; the alternative is a
1606        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1607        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1608        let promise = JsObject::ordinary(self.heap, proto);
1609        promise.with_mut(|data| {
1610            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1611                crate::object::PromiseState::default(),
1612            )));
1613        });
1614        promise
1615    }
1616
1617    /// Fulfil `promise`, unless it has already settled.
1618    ///
1619    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1620    /// after `reject`, changes nothing.
1621    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1622        let Some(state) = self.promise_state(promise) else {
1623            return;
1624        };
1625        let reactions = {
1626            let mut state = state.borrow_mut();
1627            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1628                return;
1629            }
1630            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1631            std::mem::take(&mut state.reactions)
1632        };
1633        self.queue_reactions(reactions, value, false);
1634    }
1635
1636    /// Reject `promise`, unless it has already settled.
1637    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1638        let Some(state) = self.promise_state(promise) else {
1639            return;
1640        };
1641        let reactions = {
1642            let mut state = state.borrow_mut();
1643            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1644                return;
1645            }
1646            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1647            std::mem::take(&mut state.reactions)
1648        };
1649        // Remember it only when nothing is listening *now*; a `then` registered later
1650        // prunes the entry in `perform_then`.
1651        if reactions.is_empty() {
1652            self.unhandled.push((promise.clone(), reason.clone()));
1653        }
1654        self.queue_reactions(reactions, reason, true);
1655    }
1656
1657    /// Queue one job per reaction.
1658    ///
1659    /// This is what makes `then` asynchronous even on an already-settled promise:
1660    /// `p.then(f); g()` calls `g` first.
1661    fn queue_reactions(
1662        &mut self,
1663        reactions: Vec<crate::object::PromiseReaction>,
1664        argument: Value,
1665        rejected: bool,
1666    ) {
1667        for reaction in reactions {
1668            let handler = if rejected {
1669                reaction.on_rejected.clone()
1670            } else {
1671                reaction.on_fulfilled.clone()
1672            };
1673            self.jobs.push_back(Job::Reaction {
1674                handler,
1675                argument: argument.clone(),
1676                rejected,
1677                promise: reaction.promise,
1678            });
1679        }
1680    }
1681
1682    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1683    /// resolve/reject pair.
1684    ///
1685    /// The pair are callable objects rather than Rust closures, because the script gets
1686    /// them and may stash them for later.
1687    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1688        let promise = self.new_promise();
1689        // Both handlers are built-ins with an empty name and length 1, in
1690        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1691        // off `Object.getOwnPropertyNames`.
1692        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1693        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1694        (promise, Value::Object(resolve), Value::Object(reject))
1695    }
1696
1697    /// §27.2.1.5 `NewPromiseCapability(C)`.
1698    ///
1699    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1700    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1701    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1702    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1703    /// silently ignored argument.
1704    ///
1705    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1706    /// the engine's own executor is exactly what `new_promise_capability` builds.
1707    pub fn new_promise_capability_for(
1708        &mut self,
1709        constructor: &Value,
1710    ) -> JsResult<(Value, Value, Value)> {
1711        let Some(object) = constructor.as_object().cloned() else {
1712            return Err(self.type_error("promise constructor is not a constructor"));
1713        };
1714        if !object.is_constructor() {
1715            return Err(self.type_error("promise constructor is not a constructor"));
1716        }
1717        if self
1718            .realm
1719            .promise_constructor
1720            .as_ref()
1721            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1722        {
1723            let (promise, resolve, reject) = self.new_promise_capability();
1724            return Ok((Value::Object(promise), resolve, reject));
1725        }
1726        let state = self.new_object(Some(self.realm.object_proto.clone()));
1727        let executor = self.builtin_function(
1728            "",
1729            1,
1730            Callable::CapabilityExecutor {
1731                state: state.clone(),
1732            },
1733        );
1734        let promise = self.construct(
1735            Value::Object(object.clone()),
1736            Value::Object(object),
1737            vec![Value::Object(executor)],
1738        )?;
1739        // The pair is read *after* the constructor returns, so a constructor that never
1740        // called its executor, or called it with non-callables, is the spec's step 11
1741        // `TypeError` — not something the engine can paper over.
1742        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1743            return Err(self.type_error("promise executor never ran"));
1744        };
1745        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1746            return Err(self.type_error("promise executor never ran"));
1747        };
1748        for handler in [&resolve, &reject] {
1749            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1750                return Err(self.type_error("promise capability handler is not callable"));
1751            }
1752        }
1753        Ok((promise, resolve, reject))
1754    }
1755
1756    /// §27.2.3.1 `PromiseResolve(C, x)`.
1757    ///
1758    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1759    /// an `x` that is already a promise of exactly this constructor is handed back
1760    /// unchanged, and anything else gets a fresh capability from `C`.
1761    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1762        if let Value::Object(object) = &value
1763            && self.promise_state(object).is_some()
1764        {
1765            // `x.constructor === C` means "already the right kind", so no capability is
1766            // built — which is observable through a `resolve` that counts its calls.
1767            let x_constructor = self.get_property(object, "constructor")?;
1768            let same = match (
1769                x_constructor.as_ref().and_then(Value::as_object),
1770                constructor.as_object(),
1771            ) {
1772                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1773                _ => false,
1774            };
1775            if same {
1776                return Ok(value);
1777            }
1778        }
1779        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1780        self.call_value(resolve, Value::Undefined, vec![value])?;
1781        Ok(promise)
1782    }
1783
1784    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1785    /// promise, as `{ value: completion }`.
1786    ///
1787    /// The three cases are the reference's, and they differ on purpose:
1788    ///
1789    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1790    ///   exception before any promise exists;
1791    /// * a **runtime** error rejects the returned promise;
1792    /// * success resolves it with `{ value }`, where the value is the script's completion
1793    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1794    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1795    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1796    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1797    ///
1798    /// # What this does not do
1799    ///
1800    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1801    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1802    /// the parser and the suspension machinery to accept a suspended top-level script, and
1803    /// is not implemented — such source is a syntax error here. Everything else about the
1804    /// flag is reproduced.
1805    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1806        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1807        // too, and the reference truncates that one at the same place as a runtime failure.
1808        if barrier {
1809            let depth = self.frames.len();
1810            self.trace_barriers.push(depth);
1811        }
1812        // Compiled before the promise exists, so a parse failure propagates as a throw
1813        // instead of being folded into a rejection.
1814        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1815            Ok(compiled) => compiled,
1816            Err(error) => {
1817                if barrier {
1818                    self.trace_barriers.pop();
1819                }
1820                return Err(error);
1821            }
1822        };
1823        // An async body answers its own promise, and that promise is what the reference
1824        // hands back — the same object, not a wrapper around it. Its resolution value is
1825        // the `{value}` object the compiled epilogue built.
1826        if compiled.kind.is_async() {
1827            let strict = compiled.strict;
1828            let promise = self.run_eval_script(compiled, strict)?;
1829            if barrier {
1830                self.trace_barriers.pop();
1831            }
1832            return Ok(promise);
1833        }
1834        let (promise, resolve, reject) = self.new_promise_capability();
1835        let strict = compiled.strict;
1836        match self.run_eval_script(compiled, strict) {
1837            Ok(value) => {
1838                // `{ value }` is a plain object, so resolving with it adopts nothing even
1839                // when the completion value is itself a promise.
1840                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1841                self.set_property(&wrapped, "value", value)?;
1842                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1843            }
1844            Err(Signal::Throw(error)) => {
1845                self.call_value(reject, Value::Undefined, vec![error])?;
1846            }
1847            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1848        }
1849        if barrier {
1850            self.trace_barriers.pop();
1851        }
1852        Ok(Value::Object(promise))
1853    }
1854
1855    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1856    ///
1857    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1858    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1859    /// timer table, where the collector already scans it.
1860    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1861        let (promise, resolve, _reject) = self.new_promise_capability();
1862        let resolve = self.new_host_function(
1863            "resolve",
1864            1,
1865            Box::new(
1866                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1867                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1868                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1869                },
1870            ),
1871        );
1872        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1873        // timer table is part of what the collector walks.
1874        self.schedule_timer(Value::Object(resolve), delay_ms);
1875        Ok(Value::Object(promise))
1876    }
1877
1878    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1879    /// new promise resolved with it.
1880    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1881        if let Value::Object(object) = &value
1882            && self.promise_state(object).is_some()
1883        {
1884            return Ok(value);
1885        }
1886        let promise = self.new_promise();
1887        self.resolve_promise_with(&promise, value)?;
1888        Ok(Value::Object(promise))
1889    }
1890
1891    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1892    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1893        // Resolving a promise with itself is a `TypeError`. The check exists because the
1894        // alternative is a chain of self-reactions that never settles.
1895        if let Value::Object(object) = &value
1896            && object.ptr_eq(promise)
1897        {
1898            // The spec rejects *and* throws, so both the promise and the caller see it.
1899            let thrown = self.type_error("cannot resolve a promise with itself");
1900            let Signal::Throw(error) = thrown.clone() else {
1901                unreachable!("type_error always throws")
1902            };
1903            self.reject_promise(promise, error);
1904            return Err(thrown);
1905        }
1906        let then = match &value {
1907            Value::Object(object) => self.get_property(object, "then")?,
1908            _ => None,
1909        };
1910        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1911        if !callable_then {
1912            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1913            self.fulfill_promise(promise, value);
1914            return Ok(());
1915        }
1916        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1917        // inside `resolve`, so a script cannot make a promise settle synchronously.
1918        self.jobs.push_back(Job::Thenable {
1919            then: then.expect("checked callable"),
1920            value,
1921            promise: promise.clone(),
1922        });
1923        Ok(())
1924    }
1925
1926    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1927    ///
1928    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1929    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1930    ///
1931    /// The property read is **not** short-circuitable even for a real promise: the spec says
1932    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1933    /// expects it to run. Skipping the read for promises not only lost the throw, it made
1934    /// the combinator's loop infinite — the test's iterator never sets `done`.
1935    pub fn invoke_then(
1936        &mut self,
1937        thenable: Value,
1938        on_fulfilled: Value,
1939        on_rejected: Value,
1940    ) -> JsResult<()> {
1941        let then = match &thenable {
1942            Value::Object(object) => self.get_property(object, "then")?,
1943            primitive => {
1944                let boxed = self.object_from(primitive)?;
1945                self.get_property(&boxed, "then")?
1946            }
1947        };
1948        let Some(then) = then else {
1949            return Err(self.type_error("thenable has no then method"));
1950        };
1951        if !matches!(&then, Value::Object(object) if object.is_callable()) {
1952            return Err(self.type_error("then is not a function"));
1953        }
1954        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1955        Ok(())
1956    }
1957
1958    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1959    ///
1960    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1961    /// promise.
1962    pub fn perform_then(
1963        &mut self,
1964        promise: &Gc<JsObject>,
1965        on_fulfilled: Option<Value>,
1966        on_rejected: Option<Value>,
1967    ) -> JsResult<Value> {
1968        let Some(state) = self.promise_state(promise) else {
1969            return Err(self.type_error("not a promise"));
1970        };
1971        // Whether a rejection handler is being attached decides whether a recorded
1972        // rejection stops being unhandled, so it is read before the values are moved.
1973        let has_rejection_handler = on_rejected.is_some();
1974        let derived = self.new_promise();
1975        let reaction = crate::object::PromiseReaction {
1976            on_fulfilled,
1977            on_rejected,
1978            promise: derived.clone(),
1979        };
1980        let settled = {
1981            let mut state = state.borrow_mut();
1982            // A rejection somebody reacts to is no longer unhandled.
1983            state.handled = true;
1984            match &state.status {
1985                crate::object::PromiseStatus::Pending => {
1986                    state.reactions.push(reaction.clone());
1987                    None
1988                }
1989                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1990                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1991            }
1992        };
1993        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1994        // later, means somebody is listening after all.
1995        if has_rejection_handler {
1996            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1997        }
1998        if let Some((argument, rejected)) = settled {
1999            let handler = if rejected {
2000                reaction.on_rejected
2001            } else {
2002                reaction.on_fulfilled
2003            };
2004            self.jobs.push_back(Job::Reaction {
2005                handler,
2006                argument,
2007                rejected,
2008                promise: reaction.promise,
2009            });
2010        }
2011        Ok(Value::Object(derived))
2012    }
2013
2014    /// The rejections nobody listened to, formatted the way the reference reports them.
2015    ///
2016    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2017    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2018    /// unhandled at the point the queue drains, because a `then` may still be attached
2019    /// before the host acts on it.
2020    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2021        let entries = std::mem::take(&mut self.unhandled);
2022        // Somebody may have attached a handler after the rejection was recorded, so the
2023        // promise is the authority rather than the list.
2024        let still_unhandled: Vec<Value> = entries
2025            .into_iter()
2026            .filter_map(|(promise, reason)| {
2027                let handled = self
2028                    .promise_state(&promise)
2029                    .map(|state| state.borrow().handled)
2030                    .unwrap_or(true);
2031                (!handled).then_some(reason)
2032            })
2033            .collect();
2034        still_unhandled
2035            .into_iter()
2036            .map(|reason| {
2037                let text = self.describe_exception(&reason);
2038                let stack = match &reason {
2039                    Value::Object(object) => self
2040                        .get_property(object, "stack")
2041                        .ok()
2042                        .flatten()
2043                        .map(|value| value.to_js_string())
2044                        // `stack` carries a trailing newline of its own, which would leave
2045                        // a blank line between two reported rejections.
2046                        .map(|text| text.trim_end().to_string())
2047                        .unwrap_or_default(),
2048                    _ => String::new(),
2049                };
2050                if stack.is_empty() {
2051                    format!("Possibly unhandled promise rejection: {text}")
2052                } else {
2053                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2054                }
2055            })
2056            .collect()
2057    }
2058
2059    /// Run the microtask queue to exhaustion.
2060    ///
2061    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2062    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2063    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2064    ///
2065    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2066    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2067    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2068    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2069        crate::builtins::json::parse_text(self, text, true)
2070    }
2071
2072    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2073    ///
2074    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2075    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2076    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2077    ///
2078    /// The callback is called with **no arguments**. The reference stores only the function
2079    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2080    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2081    /// extra arguments arrive as `undefined`.
2082    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2083        let id = self.next_timer_id;
2084        // Wrap rather than grow: the id reaches the script as an `Int32`.
2085        self.next_timer_id = if self.next_timer_id == i32::MAX {
2086            1
2087        } else {
2088            self.next_timer_id + 1
2089        };
2090        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2091        self.tasks.push(Task::Timer {
2092            id,
2093            callback,
2094            due_at,
2095        });
2096        id
2097    }
2098
2099    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2100    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2101    pub fn cancel_timer(&mut self, id: i32) -> bool {
2102        let before = self.tasks.len();
2103        self.tasks.retain(|task| match task {
2104            Task::Timer { id: task_id, .. } => *task_id != id,
2105        });
2106        self.tasks.len() != before
2107    }
2108
2109    /// How long until the earliest pending timer, or `None` when none is pending.
2110    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2111        let now = std::time::Instant::now();
2112        self.tasks
2113            .iter()
2114            .map(|task| match task {
2115                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2116            })
2117            .min()
2118    }
2119
2120    /// Run one turn of the event loop.
2121    ///
2122    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2123    /// run at most one due timer, then drain again. The blocking belongs to the caller
2124    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2125    /// is how it asks.
2126    ///
2127    /// One timer per turn rather than all of them: a timer callback may schedule another
2128    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2129    /// starve the microtask queue.
2130    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2131        self.drain_jobs()?;
2132        let now = std::time::Instant::now();
2133        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2134        // followed by `setTimeout(g, 1)` must run `g` first.
2135        let due = self
2136            .tasks
2137            .iter()
2138            .enumerate()
2139            .filter(|(_, task)| match task {
2140                Task::Timer { due_at, .. } => *due_at <= now,
2141            })
2142            .min_by_key(|(_, task)| match task {
2143                Task::Timer { due_at, .. } => *due_at,
2144            })
2145            .map(|(index, _)| index);
2146        let Some(index) = due else {
2147            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2148            // descriptor is registered but no timer is closer, so a script that never
2149            // touches the descriptor still gets control back. Without a cap a handler on a
2150            // descriptor that is never ready would block for as long as the host allows.
2151            let timeout = self
2152                .next_timeout()
2153                .unwrap_or(std::time::Duration::from_secs(10))
2154                .min(std::time::Duration::from_secs(10));
2155            if !self.fd_handlers.is_empty() {
2156                // Blocking on a timer while descriptors are registered would starve them,
2157                // and blocking on the descriptors while a timer is due would delay it; the
2158                // host polls with the earlier of the two deadlines, which this timeout is.
2159                return Ok(Turn::Poll(timeout));
2160            }
2161            return Ok(match self.next_timeout() {
2162                Some(wait) => Turn::Wait(wait),
2163                None => Turn::Done,
2164            });
2165        };
2166        let Task::Timer { callback, .. } = self.tasks.remove(index);
2167        let this = Value::Undefined;
2168        // A throwing timer callback must not stop the loop: the reference reports it and
2169        // keeps going, because the alternative is that one bad timer silently stops every
2170        // later one.
2171        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2172        match self.call_value(callback, this, Vec::new()) {
2173            Ok(_) => {}
2174            Err(Signal::Throw(value)) => {
2175                let text = self.describe_exception(&value);
2176                self.timer_errors.push(text);
2177            }
2178            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2179        }
2180        self.drain_jobs()?;
2181        Ok(Turn::Ran)
2182    }
2183
2184    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2185    ///
2186    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2187    /// left is removed — the reference does the same, so a script can rely on
2188    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2189    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2190        let entry = self.fd_handlers.entry(fd).or_default();
2191        if readable {
2192            entry.read = callback;
2193        } else {
2194            entry.write = callback;
2195        }
2196        if entry.read.is_none() && entry.write.is_none() {
2197            self.fd_handlers.remove(&fd);
2198        }
2199    }
2200
2201    /// Register or clear an `os.signal` handler.
2202    ///
2203    /// `None` removes it; the host separately restores the default disposition or sets
2204    /// ignore, because which of those happened is the script's choice (`null` versus
2205    /// `undefined`) and not something this table can express.
2206    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2207        match handler {
2208            Some(handler) => {
2209                self.signal_handlers.insert(signal, handler);
2210            }
2211            None => {
2212                self.signal_handlers.remove(&signal);
2213            }
2214        }
2215    }
2216
2217    /// Run the handler for `signal`, reporting whether one ran.
2218    ///
2219    /// A throwing handler is reported and the loop continues, like a timer's.
2220    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2221        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2222            return Ok(false);
2223        };
2224        match self.call_value(handler, Value::Undefined, Vec::new()) {
2225            Ok(_) => {}
2226            Err(Signal::Throw(value)) => {
2227                let text = self.describe_exception(&value);
2228                self.timer_errors.push(text);
2229            }
2230            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2231        }
2232        self.drain_jobs()?;
2233        Ok(true)
2234    }
2235
2236    /// The descriptors the host has to poll, and in which direction.
2237    ///
2238    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2239    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2240    /// `os_poll` asks for.
2241    pub fn pending_fds(&self) -> Vec<FdInterest> {
2242        self.fd_handlers
2243            .iter()
2244            .map(|(fd, entry)| FdInterest {
2245                fd: *fd,
2246                read: entry.read.is_some(),
2247                write: entry.write.is_some(),
2248            })
2249            .collect()
2250    }
2251
2252    /// Call the handler registered for `fd`, reporting whether one ran.
2253    ///
2254    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2255    /// poll iteration and then restarts the loop, because the handler may have changed the
2256    /// registration list underneath it; doing the same here keeps a handler that
2257    /// unregisters itself from being called with stale state.
2258    ///
2259    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2260    /// every later one, exactly as with timers.
2261    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2262        let Some(entry) = self.fd_handlers.get(&fd) else {
2263            return Ok(false);
2264        };
2265        let callback = if readable {
2266            entry.read.clone()
2267        } else if writable {
2268            entry.write.clone()
2269        } else {
2270            None
2271        };
2272        let Some(callback) = callback else {
2273            return Ok(false);
2274        };
2275        self.drain_jobs()?;
2276        match self.call_value(callback, Value::Undefined, Vec::new()) {
2277            Ok(_) => {}
2278            Err(Signal::Throw(value)) => {
2279                let text = self.describe_exception(&value);
2280                self.timer_errors.push(text);
2281            }
2282            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2283        }
2284        self.drain_jobs()?;
2285        Ok(true)
2286    }
2287
2288    /// Take the errors timer callbacks threw, leaving the list empty.
2289    pub fn take_timer_errors(&mut self) -> Vec<String> {
2290        std::mem::take(&mut self.timer_errors)
2291    }
2292
2293    /// Whether anything is still pending: a microtask or a timer.
2294    pub fn has_pending_work(&self) -> bool {
2295        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2296    }
2297
2298    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2299    pub fn has_pending_timers_or_jobs(&self) -> bool {
2300        !self.jobs.is_empty() || !self.tasks.is_empty()
2301    }
2302
2303    /// Run every queued microtask, including ones queued while draining.
2304    pub fn drain_jobs(&mut self) -> JsResult<()> {
2305        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2306        // would spin forever, so the drain is bounded the way the call stack is.
2307        let mut budget = 1_000_000usize;
2308        while let Some(job) = self.jobs.pop_front() {
2309            if budget == 0 {
2310                return Err(Signal::Throw(
2311                    self.make_error("InternalError", "promise job queue did not drain"),
2312                ));
2313            }
2314            budget -= 1;
2315            self.run_job(job)?;
2316            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2317            // engine may run script that the script itself did not ask for. Doing it here
2318            // rather than from a drop hook is what keeps the callback out of arbitrary
2319            // engine bookkeeping — see `builtins::weak`'s header.
2320            crate::builtins::weak::drain_finalizers(self)?;
2321        }
2322        // A script that queued no jobs may still have dropped targets, so the checkpoint
2323        // runs once more after the queue empties.
2324        crate::builtins::weak::drain_finalizers(self)?;
2325        Ok(())
2326    }
2327
2328    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2329    ///
2330    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2331    /// `None` and is swept out here. This is also where the realm learns that a registry
2332    /// died, which is why it is a mutation rather than a read.
2333    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2334        let handles = std::mem::take(&mut self.realm.finalization_registries);
2335        let mut live = Vec::with_capacity(handles.len());
2336        for handle in handles {
2337            let Some(object) = handle.upgrade() else {
2338                continue;
2339            };
2340            let Some(state) = object.finalization_state() else {
2341                continue;
2342            };
2343            live.push((object.clone(), *state));
2344            self.realm.finalization_registries.push(object.downgrade());
2345        }
2346        live
2347    }
2348
2349    /// Run one microtask.
2350    fn run_job(&mut self, job: Job) -> JsResult<()> {
2351        match job {
2352            Job::Reaction {
2353                handler: None,
2354                argument,
2355                rejected,
2356                promise,
2357            } => {
2358                // No handler: the settlement passes straight through to the derived
2359                // promise, which is why `p.catch(f)` ignores fulfilments.
2360                if rejected {
2361                    self.reject_promise(&promise, argument);
2362                } else {
2363                    self.fulfill_promise(&promise, argument);
2364                }
2365                Ok(())
2366            }
2367            Job::Reaction {
2368                handler: Some(handler),
2369                argument,
2370                promise,
2371                ..
2372            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2373                Ok(answer) => {
2374                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2375                        self.reject_promise(&promise, error);
2376                    }
2377                    Ok(())
2378                }
2379                Err(Signal::Throw(reason)) => {
2380                    self.reject_promise(&promise, reason);
2381                    Ok(())
2382                }
2383                Err(other) => Err(other),
2384            },
2385            Job::Thenable {
2386                then,
2387                value,
2388                promise,
2389            } => {
2390                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2391                // the value it produces settles `promise`.
2392                // The thenable's `then` gets this promise's own pair, so whatever it
2393                // produces settles `promise`.
2394                let resolve = JsObject::function(
2395                    self.heap,
2396                    Some(self.realm.function_proto.clone()),
2397                    Callable::PromiseResolve(promise.clone()),
2398                );
2399                let reject = JsObject::function(
2400                    self.heap,
2401                    Some(self.realm.function_proto.clone()),
2402                    Callable::PromiseReject(promise.clone()),
2403                );
2404                match self.call_value(
2405                    then,
2406                    value,
2407                    vec![Value::Object(resolve), Value::Object(reject)],
2408                ) {
2409                    Ok(_) => Ok(()),
2410                    Err(Signal::Throw(reason)) => {
2411                        self.reject_promise(&promise, reason);
2412                        Ok(())
2413                    }
2414                    Err(other) => Err(other),
2415                }
2416            }
2417            Job::Resume {
2418                coroutine,
2419                promise,
2420                kind,
2421                value,
2422            } => self.drive_async(&coroutine, &promise, kind, value),
2423            Job::GeneratorResume {
2424                generator,
2425                promise,
2426                kind,
2427                value,
2428            } => self.step_async_generator(&generator, &promise, kind, value),
2429            Job::Import {
2430                specifier,
2431                referrer,
2432                promise,
2433            } => {
2434                self.run_dynamic_import(&specifier, &referrer, &promise);
2435                Ok(())
2436            }
2437        }
2438    }
2439
2440    /// One element of a `Promise` combinator settled.
2441    ///
2442    /// The shared state object holds the result array, the number still outstanding, and
2443    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2444    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2445    /// to settle, only whatever `Sub` said a capability is.
2446    ///
2447    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2448    /// and `any` must ignore every later settlement, and `all` must not report a second
2449    /// rejection after the first.
2450    fn settle_combinator(
2451        &mut self,
2452        state: &Gc<JsObject>,
2453        index: usize,
2454        fulfilled: bool,
2455        value: Value,
2456    ) -> JsResult<()> {
2457        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2458        // Each element settles at most once: a thenable may call `onFulfilled` twice
2459        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2460        // call a no-op. Without it the second call decremented `remaining` again and settled
2461        // `all` with a short values array (`call-resolve-element-items`).
2462        let done = field("done");
2463        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2464        let settled = field("settled").is_some_and(|value| value.to_boolean());
2465        if settled {
2466            return Ok(());
2467        }
2468        if let Some(Value::Object(done)) = &done {
2469            if done
2470                .array_get(index)
2471                .is_some_and(|value| value.to_boolean())
2472            {
2473                return Ok(());
2474            }
2475            done.array_set(self.heap, index, Value::Bool(true));
2476        }
2477        let resolve = field("resolve");
2478        let reject = field("reject");
2479        let results = field("results").and_then(|value| value.as_object().cloned());
2480        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2481        // promise: the handler is a plain function the constructor chose.
2482        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2483            if let Some(handler) = handler {
2484                interp.call_value(handler, Value::Undefined, vec![value])?;
2485            }
2486            Ok(())
2487        };
2488        match kind {
2489            // `race`: the first settlement wins and stops the rest.
2490            3 => {
2491                state.define_data("settled", Value::Bool(true));
2492                let handler = if fulfilled { resolve } else { reject };
2493                settle_with(self, handler, value)?;
2494                return Ok(());
2495            }
2496            // `all`: the first rejection wins outright.
2497            0 if !fulfilled => {
2498                state.define_data("settled", Value::Bool(true));
2499                settle_with(self, reject, value)?;
2500                return Ok(());
2501            }
2502            // `any`: the first fulfilment wins.
2503            2 if fulfilled => {
2504                state.define_data("settled", Value::Bool(true));
2505                settle_with(self, resolve, value)?;
2506                return Ok(());
2507            }
2508            _ => {}
2509        }
2510        let Some(results) = &results else {
2511            return Ok(());
2512        };
2513        match kind {
2514            0 => {
2515                results.array_set(self.heap, index, value);
2516            }
2517            // `allSettled` never rejects; each slot records what happened.
2518            1 => {
2519                let record = self.new_object(Some(self.realm.object_proto.clone()));
2520                if fulfilled {
2521                    record.define_data("status", self.string("fulfilled"));
2522                    record.define_data("value", value);
2523                } else {
2524                    record.define_data("status", self.string("rejected"));
2525                    record.define_data("reason", value);
2526                }
2527                results.array_set(self.heap, index, Value::Object(record));
2528            }
2529            // `any`: a rejection is parked in the errors array and the sweep continues.
2530            2 => {
2531                results.array_set(self.heap, index, value);
2532            }
2533            _ => {}
2534        }
2535        let remaining = field("remaining")
2536            .map(|value| value.to_int32())
2537            .unwrap_or(0);
2538        let left = remaining - 1;
2539        state.define_data("remaining", Value::Int(left));
2540        if left != 0 {
2541            return Ok(());
2542        }
2543        state.define_data("settled", Value::Bool(true));
2544        match kind {
2545            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2546            2 => {
2547                // The rejection is an `AggregateError` whose `errors` is the results array
2548                // itself — the slots are the reasons, in input order.
2549                let errors = results.array_elements().unwrap_or_default();
2550                let error = self.aggregate_error(errors, "all promises were rejected");
2551                settle_with(self, reject, error)?;
2552            }
2553            _ => {}
2554        }
2555        Ok(())
2556    }
2557
2558    /// Build an async function's result: a promise whose body runs as a coroutine.
2559    pub fn new_async_function(
2560        &mut self,
2561        function: Value,
2562        this: Value,
2563        args: Vec<Value>,
2564    ) -> JsResult<Value> {
2565        let promise = self.new_promise();
2566        let coroutine = self.new_coroutine(function, this, args)?;
2567        if let Err(Signal::Throw(reason)) =
2568            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2569        {
2570            self.reject_promise(&promise, reason);
2571        }
2572        Ok(Value::Object(promise))
2573    }
2574
2575    /// The coroutine an async body runs in.
2576    ///
2577    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2578    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2579    /// than growing a second state machine. The difference is only in the ending — a
2580    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2581    /// Run `code` as an async function body, answering the promise it settles.
2582    ///
2583    /// Used for a module with top-level `await`: its body is an async function whose
2584    /// caller is the host, so there is no function object to pass through
2585    /// [`Interp::new_async_function`].
2586    pub fn run_async_body(
2587        &mut self,
2588        code: Gc<CompiledCode>,
2589        env: Gc<ClosureEnv>,
2590        this: Value,
2591    ) -> JsResult<Value> {
2592        let promise = self.new_promise();
2593        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2594        if let Err(Signal::Throw(reason)) =
2595            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2596        {
2597            self.reject_promise(&promise, reason);
2598        }
2599        Ok(Value::Object(promise))
2600    }
2601
2602    fn new_coroutine(
2603        &mut self,
2604        function: Value,
2605        this: Value,
2606        args: Vec<Value>,
2607    ) -> JsResult<Gc<JsObject>> {
2608        let Some(object) = function.as_object().cloned() else {
2609            return Err(self.type_error("not a function"));
2610        };
2611        let Some((code, env)) = bytecode_of(&object) else {
2612            return Err(self.type_error("not a function"));
2613        };
2614        self.new_coroutine_from(code, env, this, args)
2615    }
2616
2617    /// Build a coroutine over an already-resolved body.
2618    fn new_coroutine_from(
2619        &mut self,
2620        code: Gc<CompiledCode>,
2621        env: Gc<ClosureEnv>,
2622        this: Value,
2623        args: Vec<Value>,
2624    ) -> JsResult<Gc<JsObject>> {
2625        let function = Value::Undefined;
2626        self.push_frame(code, env, this, args, function)?;
2627        let frame = self.frames.pop().expect("push_frame just pushed it");
2628        let state = GeneratorState {
2629            frame: Some(frame),
2630            phase: GeneratorPhase::SuspendedStart,
2631            parked_on_await: false,
2632            parked_on_yield_star: false,
2633            requests: std::collections::VecDeque::new(),
2634            async_busy: false,
2635        };
2636        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2637        coroutine.with_mut(|data| {
2638            data.kind = ObjectKind::Generator(Box::new(state));
2639        });
2640        Ok(coroutine)
2641    }
2642
2643    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2644    /// `await` and `value` is what it awaited.
2645    fn resume_coroutine(
2646        &mut self,
2647        coroutine: &Gc<JsObject>,
2648        kind: ResumeKind,
2649        value: Value,
2650    ) -> JsResult<(Value, bool)> {
2651        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2652            ObjectKind::Generator(state) => Some(std::mem::replace(
2653                state.as_mut(),
2654                GeneratorState {
2655                    frame: None,
2656                    phase: GeneratorPhase::Executing,
2657                    parked_on_await: false,
2658                    parked_on_yield_star: false,
2659                    requests: std::collections::VecDeque::new(),
2660                    async_busy: false,
2661                },
2662            )),
2663            _ => None,
2664        }) else {
2665            return Err(self.type_error("not a coroutine"));
2666        };
2667        let result = self.step_generator(&mut state, kind, value);
2668        coroutine.with_mut(|data| {
2669            data.kind = ObjectKind::Generator(Box::new(state));
2670        });
2671        let (value, done, _ready, _reason) = result?;
2672        Ok((value, done))
2673    }
2674
2675    /// Advance an async body and settle its promise with the outcome.
2676    fn drive_async(
2677        &mut self,
2678        coroutine: &Gc<JsObject>,
2679        promise: &Gc<JsObject>,
2680        kind: ResumeKind,
2681        value: Value,
2682    ) -> JsResult<()> {
2683        match self.resume_coroutine(coroutine, kind, value) {
2684            Ok((value, true)) => {
2685                // `Ok` with `done` means the body finished *normally*, even when it was
2686                // resumed by a `throw` — `try { await p } catch {}` completes by
2687                // returning. Only the `Err` arm below is a rejection.
2688                //
2689                // Resolving rather than fulfilling matters: `return promise` in an async
2690                // body adopts the inner promise, so `async function f(){ return
2691                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2692                // promise.
2693                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2694                    self.reject_promise(promise, reason);
2695                }
2696                Ok(())
2697            }
2698            Ok((value, false)) => {
2699                // Parked on `await`: follow what it awaited and resume with the outcome.
2700                let awaited = match self.promise_resolve_value(value) {
2701                    Ok(awaited) => awaited,
2702                    Err(Signal::Throw(error)) => {
2703                        self.reject_promise(promise, error);
2704                        return Ok(());
2705                    }
2706                    Err(other) => return Err(other),
2707                };
2708                self.hook_await(awaited, coroutine, promise)
2709            }
2710            Err(Signal::Throw(reason)) => {
2711                self.reject_promise(promise, reason);
2712                Ok(())
2713            }
2714            Err(other) => Err(other),
2715        }
2716    }
2717
2718    /// Arrange for `coroutine` to resume when `awaited` settles.
2719    fn hook_await(
2720        &mut self,
2721        awaited: Value,
2722        coroutine: &Gc<JsObject>,
2723        promise: &Gc<JsObject>,
2724    ) -> JsResult<()> {
2725        let resumed = JsObject::function(
2726            self.heap,
2727            Some(self.realm.function_proto.clone()),
2728            Callable::AwaitResume {
2729                coroutine: coroutine.clone(),
2730                promise: promise.clone(),
2731                kind: ResumeKind::Next,
2732            },
2733        );
2734        let raised = JsObject::function(
2735            self.heap,
2736            Some(self.realm.function_proto.clone()),
2737            Callable::AwaitResume {
2738                coroutine: coroutine.clone(),
2739                promise: promise.clone(),
2740                kind: ResumeKind::Throw,
2741            },
2742        );
2743        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2744        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2745        let Value::Object(awaited) = &awaited else {
2746            self.jobs.push_back(Job::Resume {
2747                coroutine: coroutine.clone(),
2748                promise: promise.clone(),
2749                kind: ResumeKind::Next,
2750                value: awaited,
2751            });
2752            return Ok(());
2753        };
2754        self.perform_then(
2755            awaited,
2756            Some(Value::Object(resumed)),
2757            Some(Value::Object(raised)),
2758        )?;
2759        Ok(())
2760    }
2761
2762    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2763    /// things an engine keeps outside it — array elements and an array's `length`.
2764    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2765        if let Some(property) = object.own_property_key(key) {
2766            return Some(property);
2767        }
2768        // An array's elements live in their own vector rather than the property table, so
2769        // a descriptor for one has to be synthesized — with the attributes an element has.
2770        if let Some(index) = key.as_str().and_then(array_index)
2771            && let Some(value) = object.array_get(index as usize)
2772            && !matches!(value, Value::Hole)
2773        {
2774            return Some(Property::data(value));
2775        }
2776        // `length` is an own property of an array that is not in its property table
2777        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2778        // and non-enumerable.
2779        if key.as_str() == Some("length")
2780            && let Some(length) = object.array_length()
2781        {
2782            return Some(Property {
2783                value: Some(crate::object::length_value(length)),
2784                writable: object.length_writable(),
2785                enumerable: false,
2786                configurable: false,
2787                getter: None,
2788                setter: None,
2789            });
2790        }
2791        None
2792    }
2793
2794    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2795    pub fn object_get_own_property(
2796        &mut self,
2797        object: &Gc<JsObject>,
2798        key: &PropertyKey,
2799    ) -> JsResult<Option<Property>> {
2800        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2801            return Ok(answer);
2802        }
2803        if let Some(exotic) = object.exotic()
2804            && let Some(answer) = exotic.get_own_property(self, object, key)?
2805        {
2806            return Ok(answer);
2807        }
2808        Ok(Self::ordinary_own_property(object, key))
2809    }
2810
2811    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2812    pub fn object_define_own_property(
2813        &mut self,
2814        object: &Gc<JsObject>,
2815        key: &PropertyKey,
2816        property: Property,
2817    ) -> JsResult<bool> {
2818        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2819            return Ok(accepted);
2820        }
2821        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
2822        // non-extensible object. The check lives here rather than in the callers because
2823        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
2824        // `Array.prototype.filter` uses to store its result, and a species object made
2825        // non-extensible by its own constructor must make that a `TypeError`
2826        // (`target-array-non-extensible`).
2827        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
2828            return Ok(false);
2829        }
2830        // A host class that intercepts definitions owns the attributes of the properties it
2831        // defines: `_class`-style storage on the native side is the usual reason.
2832        if let Some(exotic) = object.exotic()
2833            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
2834        {
2835            return Ok(accepted);
2836        }
2837        // An array index is stored in the element vector, which can hold a plain value and
2838        // nothing else. An accessor — or a data property with non-default attributes —
2839        // therefore has to live in the property table, and the element slot is blanked so
2840        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2841        // {get})` stored the accessor where no read ever looked, and the array kept
2842        // answering its old value.
2843        // An array's `length` is not stored in the property table, so defining it has to
2844        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2845        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2846        // {value: 1})` reported success and changed nothing.
2847        if key.as_str() == Some("length") && object.is_array() {
2848            // `{writable: false}` on `length` does not change the length, but it does make
2849            // it read-only — after which neither a later `{writable: true}` nor a store
2850            // past the end may succeed.
2851            if property.value.is_none() {
2852                if !object.length_writable() && property.writable {
2853                    return Ok(false);
2854                }
2855                object.set_length_writable(property.writable);
2856                return Ok(true);
2857            }
2858            if !object.length_writable() {
2859                return Ok(false);
2860            }
2861        }
2862        if key.as_str() == Some("length")
2863            && object.is_array()
2864            && let Some(value) = property.value.clone()
2865        {
2866            let requested = value.to_number();
2867            let valid = requested.is_finite()
2868                && requested >= 0.0
2869                && requested.fract() == 0.0
2870                && requested <= u32::MAX as f64;
2871            if !valid {
2872                return Err(self.range_error("invalid array length"));
2873            }
2874            // Truncating deletes the elements above the new length, and a non-configurable
2875            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2876            // makes `a.length = 2` fail rather than quietly drop it.
2877            let current = object.array_length().unwrap_or(0);
2878            let requested = requested as usize;
2879            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2880                return Ok(false);
2881            }
2882            object.array_set_length(self.heap, requested);
2883            return Ok(true);
2884        }
2885        let plain = property.writable
2886            && property.enumerable
2887            && property.configurable
2888            && !property.is_accessor();
2889        if let Some(index) = key.as_str().and_then(array_index)
2890            && object.is_array()
2891        {
2892            // Growing the array needs a writable `length`: after
2893            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2894            // be added.
2895            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2896                return Ok(false);
2897            }
2898            if plain && property.value.is_some() {
2899                // An ordinary element: the vector is where a read looks first, so it has
2900                // to be the vector that changes — unless the index is too far out to be
2901                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2902                // one property, because past its own limit it stores the index as an
2903                // ordinary key. Falling through to `define_key` below is the same choice,
2904                // and the alternative was worse: the store used to be *dropped* and the
2905                // length left at 0, which is a silent wrong answer.
2906                let value = property.value.clone().unwrap_or(Value::Undefined);
2907                object.delete_key(key);
2908                if object.array_set(self.heap, index as usize, value) {
2909                    return Ok(true);
2910                }
2911                // Past the dense limit the element lives in the table like any property.
2912                object.note_element_descriptor();
2913                object.define_key(key, property);
2914                // A sparse store past the dense limit still extends `length`, which is what
2915                // `a[a.length] = v` relies on — but only extends: shortening would delete
2916                // the sparse properties above the index, including this one.
2917                if index as usize + 1 > object.array_length().unwrap_or(0) {
2918                    object.array_set_length(self.heap, index as usize + 1);
2919                }
2920                return Ok(true);
2921            }
2922            // A non-plain element — an accessor, or an attribute that is not the default —
2923            // lives in the table while the slot becomes a hole. Recording it keeps every
2924            // later `a[i] = v` off the dense path, where the write would have shadowed the
2925            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
2926            // replace the accessor with a plain data property.
2927            object.note_element_descriptor();
2928            object.define_key(key, property);
2929            // The slot stays, so `length` does not shrink; a hole is not an element, so
2930            // the table entry is now what a read finds.
2931            object.array_set(self.heap, index as usize, Value::Hole);
2932            return Ok(true);
2933        }
2934        object.define_key(key, property);
2935        Ok(true)
2936    }
2937
2938    /// Build a proxy object over `target`, with its traps read from `handler`.
2939    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2940        JsObject::proxy(self.heap, target, handler)
2941    }
2942
2943    /// The `revoke` function for a proxy's slots.
2944    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2945        JsObject::function(
2946            self.heap,
2947            Some(self.realm.function_proto.clone()),
2948            Callable::Revoker(slots),
2949        )
2950    }
2951
2952    /// A new array.
2953    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2954        let array = JsObject::array(
2955            self.heap,
2956            Some(self.realm.array_proto.clone()),
2957            elements.len(),
2958        );
2959        for (index, element) in elements.into_iter().enumerate() {
2960            array.array_set(self.heap, index, element);
2961        }
2962        array
2963    }
2964
2965    /// A new native function object.
2966    ///
2967    /// The observable `name` and `length` are installed as properties here, which is
2968    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2969    /// so `f.name = "x"` behaves like the writable property it is.
2970    /// A native constructor that builds its own instance after validating its arguments.
2971    ///
2972    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2973    /// check runs before `new.target.prototype` is read.
2974    pub fn new_native_ctor(
2975        &self,
2976        name: impl Into<String>,
2977        length: u32,
2978        func: NativeFn,
2979    ) -> Gc<JsObject> {
2980        let function = JsObject::function(
2981            self.heap,
2982            Some(self.realm.function_proto.clone()),
2983            Callable::Native {
2984                func,
2985                own_instance: true,
2986            },
2987        );
2988        function.set_constructible(true);
2989        function.define(
2990            "length",
2991            Property::name_or_length(Value::Int(length as i32)),
2992        );
2993        function.define("name", Property::name_or_length(self.string(name)));
2994        function
2995    }
2996
2997    /// A native constructor that lets `new` build the instance first.
2998    ///
2999    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3000    /// validation that must precede reading `new.target.prototype`, so the object can be
3001    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3002    /// which makes a *method* and therefore not a constructor at all.
3003    pub fn new_native_constructor(
3004        &self,
3005        name: impl Into<String>,
3006        length: u32,
3007        func: NativeFn,
3008    ) -> Gc<JsObject> {
3009        let function = self.new_native(name, length, func);
3010        function.set_constructible(true);
3011        function
3012    }
3013
3014    /// A new host function object: a native closure that carries its own state.
3015    ///
3016    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3017    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3018    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3019    /// this safe: the closure must not capture a `Gc`.
3020    pub fn new_host_function(
3021        &self,
3022        name: impl Into<String>,
3023        length: u32,
3024        func: crate::object::HostFn,
3025    ) -> Gc<JsObject> {
3026        self.new_host_inner(name.into(), length, func, false)
3027    }
3028
3029    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3030    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3031    pub fn new_host_ctor(
3032        &self,
3033        name: impl Into<String>,
3034        length: u32,
3035        func: crate::object::HostFn,
3036    ) -> Gc<JsObject> {
3037        let function = self.new_host_inner(name.into(), length, func, true);
3038        function.set_constructible(true);
3039        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3040        // installs its own methods on it, so it starts as a plain object.
3041        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3042        function.define(
3043            "prototype",
3044            Property {
3045                value: Some(Value::Object(proto)),
3046                writable: true,
3047                enumerable: false,
3048                configurable: false,
3049                ..Property::default()
3050            },
3051        );
3052        function
3053    }
3054
3055    fn new_host_inner(
3056        &self,
3057        name: String,
3058        length: u32,
3059        func: crate::object::HostFn,
3060        own_instance: bool,
3061    ) -> Gc<JsObject> {
3062        let function = JsObject::function(
3063            self.heap,
3064            Some(self.realm.function_proto.clone()),
3065            Callable::Host {
3066                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3067                own_instance,
3068            },
3069        );
3070        function.define(
3071            "length",
3072            Property::name_or_length(Value::Int(length as i32)),
3073        );
3074        function.define("name", Property::name_or_length(self.string(name)));
3075        function
3076    }
3077
3078    /// A callable object with the `length`/`name` a built-in function has, in that order.
3079    ///
3080    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3081    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3082    /// [`JsObject::function`] defines neither, which is why every capability helper built
3083    /// with it reported no own `length` and no own `name` at all.
3084    ///
3085    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3086    /// configurable.
3087    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3088        let function =
3089            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3090        function.define(
3091            "length",
3092            Property::name_or_length(Value::Int(length as i32)),
3093        );
3094        function.define("name", Property::name_or_length(self.string(name)));
3095        function
3096    }
3097
3098    /// A new native function object.
3099    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3100        let function = JsObject::function(
3101            self.heap,
3102            Some(self.realm.function_proto.clone()),
3103            Callable::Native {
3104                func,
3105                own_instance: false,
3106            },
3107        );
3108        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3109        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3110        // `length,name` and this listed `name,length`. A bytecode function already gets it
3111        // the right way round; only native ones were built backwards.
3112        function.define(
3113            "length",
3114            Property::name_or_length(Value::Int(length as i32)),
3115        );
3116        function.define("name", Property::name_or_length(self.string(name)));
3117        function
3118    }
3119
3120    /// A new bound function.
3121    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3122        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3123        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3124        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3125        let constructible = target
3126            .as_object()
3127            .is_some_and(|target| target.is_constructor());
3128        let bound = JsObject::function(
3129            self.heap,
3130            Some(self.realm.function_proto.clone()),
3131            Callable::Bound { target, this, args },
3132        );
3133        bound.set_constructible(constructible);
3134        bound
3135    }
3136
3137    /// A new reference cell.
3138    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3139        Gc::new(self.heap, Cell::new(value))
3140    }
3141
3142    // -- running ------------------------------------------------------------
3143
3144    /// Evaluate `code` as a script body and return its completion value.
3145    /// Compile and run `source` for the engine's own use, returning its completion value.
3146    ///
3147    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3148    /// needs to be a real async function, and the engine already runs those as coroutines,
3149    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3150    ///
3151    /// Differences from [`Self::eval_in_global`], both deliberate:
3152    ///
3153    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3154    ///   being built, and the source is an IIFE that only constructs a closure, so there
3155    ///   is nothing to drain — and draining here would run script-queued jobs in the
3156    ///   middle of `install`.
3157    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3158    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3159    ///   and it should not look like the user wrote something wrong.
3160    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3161        let program = match js_parse::parse_script(source) {
3162            Ok(program) => program,
3163            Err(error) => {
3164                let message = format!("builtin source does not parse: {error}");
3165                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3166            }
3167        };
3168        let mut code = match js_compile::compile_script(&program) {
3169            Ok(code) => code,
3170            Err(error) => {
3171                let message = format!("builtin source does not compile: {}", error.message);
3172                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3173            }
3174        };
3175        // The frame has to name something, and `<builtin>` is what a stack trace through
3176        // this code should say.
3177        code.set_filename("<builtin>");
3178        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3179        let closure_vars = compiled.code.closure_vars.clone();
3180        let env = self.global_env(&closure_vars);
3181        let this = Value::Object(self.realm.global.clone());
3182        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3183    }
3184
3185    /// Run an already-parsed script and drain the microtasks it queued.
3186    ///
3187    /// The drain is what lets an `async` function's body advance past its first `await`
3188    /// before the host sees the result: nothing else pumps the job queue.
3189    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3190        let this = Value::Object(self.realm.global.clone());
3191        self.run_script_with_this(code, this)
3192    }
3193
3194    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3195    ///
3196    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3197    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3198    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3199    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3200    /// state the next script evaluation tripped over.
3201    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3202        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3203        let closure_vars = compiled.code.closure_vars.clone();
3204        let env = self.global_env(&closure_vars);
3205        let callee = Value::Undefined;
3206        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3207        // The script is done, so the microtasks it queued run before the host sees the
3208        // result. Without this an `async` function's body would never advance past its
3209        // first `await`, because nothing else drains the queue.
3210        self.drain_jobs()?;
3211        Ok(result)
3212    }
3213
3214    /// Compile and run `source` in global scope, returning its completion value.
3215    ///
3216    /// This is what `eval` and `new Function` use. Running it as a script means it
3217    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3218    /// for a `Function` body; a *direct* eval that reads a local variable would need
3219    /// the compiler to hand its variable environment over, which is not implemented.
3220    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3221        self.eval_in_global_named(source, EVAL_FILE, false)
3222    }
3223
3224    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3225    ///
3226    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3227    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3228    /// through the code, so they cannot share one constant.
3229    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3230        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3231    }
3232
3233    /// Evaluate `source` as a global script, reported under `file`.
3234    ///
3235    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3236    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3237    /// from inside a C callback, where the interpreter is the running one rather than a
3238    /// context's own.
3239    pub fn eval_in_global_named(
3240        &mut self,
3241        source: &str,
3242        file: &str,
3243        barrier: bool,
3244    ) -> JsResult<Value> {
3245        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3246        // eval-created global binding — configurable, unlike a script's own `var`.
3247        self.eval_depth += 1;
3248        if barrier {
3249            let depth = self.frames.len();
3250            self.trace_barriers.push(depth);
3251        }
3252        let result = self.eval_in_global_inner(source, file);
3253        if barrier {
3254            self.trace_barriers.pop();
3255        }
3256        self.eval_depth -= 1;
3257        result
3258    }
3259
3260    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3261        let compiled = self.compile_global_script(source, file, false)?;
3262        let strict = compiled.strict;
3263        self.run_eval_script(compiled, strict)
3264    }
3265
3266    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3267    ///
3268    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3269    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3270    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3271    /// direct eval's is.
3272    pub fn eval_script_with_this(
3273        &mut self,
3274        source: &str,
3275        file: &str,
3276        this: Value,
3277    ) -> JsResult<Value> {
3278        let program = match js_parse::parse_script(source) {
3279            Ok(program) => program,
3280            Err(error) => {
3281                return Err(Signal::Throw(self.syntax_error_at(
3282                    file,
3283                    error.span.start.line,
3284                    error.span.start.column,
3285                    &error.message,
3286                )));
3287            }
3288        };
3289        let mut compiled = match js_compile::compile_script(&program) {
3290            Ok(compiled) => compiled,
3291            Err(error) => {
3292                return Err(Signal::Throw(self.syntax_error_at(
3293                    file,
3294                    error.span.start.line,
3295                    error.span.start.column,
3296                    &error.message,
3297                )));
3298            }
3299        };
3300        compiled.set_filename(file);
3301        self.run_script_with_this(compiled, this)
3302    }
3303
3304    /// Parse and compile `source` as a global script, without running it.
3305    ///
3306    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3307    /// before a promise exists to reject — while still evaluating in the same eval context
3308    /// (direct-eval strictness, `new.target`, `super`).
3309    fn compile_global_script(
3310        &mut self,
3311        source: &str,
3312        file: &str,
3313        async_body: bool,
3314    ) -> JsResult<CompiledFunction> {
3315        // A *direct* eval inherits the strictness of the code that called it, which is
3316        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3317        // implicit global. The caller's frame is the innermost one here, because a
3318        // native function does not push a frame of its own.
3319        let strict = self.current_strict();
3320        // `eval` runs in the caller's function context, so `new.target` is legal here
3321        // even though the source is a bare script — and so is `super.x` when the caller
3322        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3323        // caller's, which is what `special_object 4` already does.
3324        let context = js_parse::EvalContext {
3325            in_method: self.enclosing_home_object().is_some(),
3326            // `super()` belongs to a derived constructor, and an eval'd body is not a
3327            // constructor at all: the caller frame's `this` is already built.
3328            in_derived_constructor: false,
3329        };
3330        // A *global* eval is not a function body: `new.target` and `super` are out of
3331        // reach there. Its `{async: true}` form differs in the other direction — the body
3332        // may `await` — so the two flags are independent and the reference sets both from
3333        // the eval type rather than from the caller.
3334        let parsed = if async_body {
3335            js_parse::parse_suspensible_global_eval(source, strict)
3336        } else {
3337            js_parse::parse_eval_script_in(source, strict, context)
3338        };
3339        let program = match parsed {
3340            Ok(program) => program,
3341            Err(error) => {
3342                // The message is bare: the position lives in `fileName`,
3343                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3344                // the reference puts it. An `invalid source: L:C: ` prefix made
3345                // `e.message` differ from the reference while the stack already agreed.
3346                return Err(Signal::Throw(self.syntax_error_at(
3347                    file,
3348                    error.span.start.line,
3349                    error.span.start.column,
3350                    &error.message,
3351                )));
3352            }
3353        };
3354        let mut compiled = match if async_body {
3355            js_compile::compile_script_suspensible(&program)
3356        } else {
3357            js_compile::compile_script(&program)
3358        } {
3359            Ok(compiled) => compiled,
3360            // A construct the compiler does not handle yet is reported the same way a
3361            // parse error is: it happens before anything runs, so the trace is the
3362            // position in the source followed by the caller.
3363            Err(error) => {
3364                return Err(Signal::Throw(self.syntax_error_at(
3365                    file,
3366                    error.span.start.line,
3367                    error.span.start.column,
3368                    &error.message,
3369                )));
3370            }
3371        };
3372        compiled.set_filename(file);
3373        Ok(compiled)
3374    }
3375
3376    /// Run an `eval`'d script in the caller's scope.
3377    ///
3378    /// Three things have to come from the calling frame, because the eval'd code is a
3379    /// script and would otherwise see only the global object:
3380    ///
3381    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3382    /// * `arguments`, exposed as a binding of the eval's own scope, so
3383    ///   `f("arguments.length", 1)` sees the caller's arguments;
3384    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3385    ///   `eval("var v = 1")` into the global object.
3386    ///
3387    /// Locals of the calling function are *not* reachable: that needs the compiler to
3388    /// hand its variable environment over, which this milestone does not do.
3389    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3390        // `this` and `arguments` come from the innermost frame only — those are not
3391        // lexical — while the name bindings come from the whole chain of frames, part
3392        // of it being ordinary scope resolution.
3393        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3394        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3395        // read from its closure.
3396        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3397        // variable environment is the innermost frame of all: an arrow's own body is where
3398        // `var`s declared by an `eval` inside it belong.
3399        let caller_index = self
3400            .frames
3401            .iter()
3402            .rposition(|frame| !frame.code.code.is_arrow)
3403            .or_else(|| self.frames.len().checked_sub(1));
3404        let env_index = self.frames.len().checked_sub(1);
3405        let caller = caller_index.and_then(|index| self.frames.get(index));
3406        let (this, passed) = match caller {
3407            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3408            // No frame at all: the eval is running at the top level, so there is
3409            // nothing to inherit and the global receiver is right.
3410            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3411        };
3412        // Innermost frame first, so the first binding found for a name is the one that
3413        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3414        let mut bindings: Vec<EvalBinding> = Vec::new();
3415        // The calling function's own bindings, resolved by the compiler at the call
3416        // site. That table is the only reliable answer when a name is declared twice in
3417        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3418        // body means, and guessing by declaration order picks the wrong one as soon as
3419        // two loops in a row use the same name.
3420        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3421        // every direct call — a bare `eval(...)` callee — so finding one at the current
3422        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3423        // callee to a value first and leave no site behind.
3424        let mut direct = false;
3425        let mut resolved_here = false;
3426        if let Some(frame) = self.frames.last() {
3427            let (line, column) = frame
3428                .code
3429                .code
3430                .position_at(frame.at as u32)
3431                .unwrap_or_default();
3432            // The nearest site at or before the current position, not an exact match:
3433            // the recorded position of the `call` instruction is the callee's, which
3434            // sits a few columns inside the call expression the compiler recorded. A
3435            // site is unique per call, so "the closest one behind us" identifies it.
3436            if let Some(site) = frame
3437                .code
3438                .code
3439                .eval_sites
3440                .iter()
3441                .filter(|site| (site.line, site.column) <= (line, column))
3442                .max_by_key(|site| (site.line, site.column))
3443            {
3444                direct = true;
3445                resolved_here = true;
3446                for binding in &site.bindings {
3447                    // An enclosing function's frame sits `owner` levels below the one
3448                    // running the call.
3449                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3450                    else {
3451                        continue;
3452                    };
3453                    bindings.push(EvalBinding {
3454                        name: binding.name.clone(),
3455                        frame,
3456                        slot: if binding.is_arg {
3457                            EvalSlot::Arg
3458                        } else {
3459                            EvalSlot::Local
3460                        },
3461                        index: binding.index as usize,
3462                    });
3463                }
3464            }
3465        }
3466        for frame_index in (0..self.frames.len()).rev() {
3467            // Skip the innermost frame's flat scan when the compiler already answered
3468            // for it; an enclosing frame still needs one, because the eval resolves
3469            // those names dynamically.
3470            if resolved_here && frame_index == self.frames.len() - 1 {
3471                continue;
3472            }
3473            let frame = &self.frames[frame_index];
3474            for (index, arg) in frame.code.code.args.iter().enumerate() {
3475                bindings.push(EvalBinding {
3476                    name: arg.name.clone(),
3477                    frame: frame_index,
3478                    slot: EvalSlot::Arg,
3479                    index,
3480                });
3481            }
3482            for (index, local) in frame.code.code.vars.iter().enumerate() {
3483                bindings.push(EvalBinding {
3484                    name: local.name.clone(),
3485                    frame: frame_index,
3486                    slot: EvalSlot::Local,
3487                    index,
3488                });
3489            }
3490        }
3491        let mut seen = BTreeSet::new();
3492        bindings.retain(|binding| seen.insert(binding.name.clone()));
3493
3494        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3495        // elements is all the spec's ordinary uses need.
3496        //
3497        // Known divergence: this is bound for a *global* eval too, where there is no
3498        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3499        // needs "does the calling frame have an `arguments` of its own", which is not
3500        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3501        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3502        // the call-site detection does not answer it. Modelled as a binding in the caller's
3503        // variable environment, this would fall out; that is a larger change than the one
3504        // this comment is attached to.
3505        let arguments = Value::Object(self.new_array(passed));
3506
3507        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3508        // declares its `var`s in the caller's — which for a top-level eval is the global
3509        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3510        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3511        // vanish into a scope nobody reads back from.
3512        let previous_scope = if code_strict {
3513            self.eval_scope.replace(BTreeMap::new())
3514        } else {
3515            None
3516        };
3517        let previous_arguments = self.eval_arguments.replace(arguments);
3518        let previous_with = self.eval_with.replace(self.with_objects());
3519        let inherited_new_target = self
3520            .frames
3521            .iter()
3522            .rev()
3523            .find(|frame| !frame.code.code.is_arrow)
3524            .map(|frame| frame.new_target.clone());
3525        let previous_new_target = self
3526            .eval_new_target
3527            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3528        let eval_cells = self.eval_cells_for(&bindings);
3529        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3530        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3531        // `declare_eval_local` needs to know which frame that is.
3532        // An indirect eval gets the global environment, so nothing of the caller's is
3533        // recorded as the place its `var`s belong.
3534        let previous_caller = self
3535            .eval_caller
3536            .replace(if direct { env_index } else { None });
3537        // The cell-based view of the same bindings, which is what a closure created
3538        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3539        // whose compiler did not put a binding in a cell simply does not appear here —
3540        // reads and writes still work through `eval_bindings`, they just cannot outlive
3541        // the eval.
3542        let previous_eval_scope = self
3543            .active_eval_scope
3544            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3545        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3546        let closure_vars = compiled.code.closure_vars.clone();
3547        let env = self.global_env(&closure_vars);
3548        let callee = Value::Undefined;
3549        // An async body does not run here: it becomes a coroutine and answers a promise,
3550        // which is what makes `await` legal in it. `this` still has to be the caller's
3551        // (for a global eval, the global object), because `this` is not part of `await`.
3552        let result = if compiled.code.kind.is_async() {
3553            self.run_async_body(compiled, env, this)
3554        } else {
3555            self.execute(compiled, env, this, Vec::new(), callee)
3556        };
3557        self.eval_scope = previous_scope;
3558        self.eval_arguments = previous_arguments;
3559        self.eval_with = previous_with;
3560        self.eval_new_target = previous_new_target;
3561        self.eval_bindings = previous_bindings;
3562        self.eval_caller = previous_caller;
3563        self.active_eval_scope = previous_eval_scope;
3564        result
3565    }
3566
3567    /// The cell-backed subset of `bindings`, in the same priority order.
3568    ///
3569    /// Both lookup routes have to agree — the eval's own reads go through
3570    /// [`Interp::eval_binding_value`] and the closures it builds go through
3571    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3572    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3573    /// is not in a cell simply does not appear: reads and writes still work, they just
3574    /// cannot be handed to a closure that outlives the eval.
3575    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3576        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3577        for binding in bindings {
3578            let Some(frame) = self.frames.get(binding.frame) else {
3579                continue;
3580            };
3581            let cell = match binding.slot {
3582                EvalSlot::Arg => frame
3583                    .code
3584                    .arg_cell
3585                    .get(binding.index)
3586                    .copied()
3587                    .unwrap_or(-1),
3588                EvalSlot::Local => frame
3589                    .code
3590                    .loc_cell
3591                    .get(binding.index)
3592                    .copied()
3593                    .unwrap_or(-1),
3594            };
3595            if cell < 0 {
3596                continue;
3597            }
3598            if let Some(cell) = frame.cells.get(cell as usize) {
3599                names.push((binding.name.clone(), cell.clone()));
3600            }
3601        }
3602        names
3603    }
3604
3605    /// A `SyntaxError` that reports where in the source it happened.
3606    ///
3607    /// Compile-time failures never run, so they have no frame of their own; the
3608    /// reference still puts the position first in the trace, with no function name and
3609    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3610    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3611    /// reference borrows), which is how a script reads the position without parsing
3612    /// the trace.
3613    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3614    ///
3615    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3616    /// `columnNumber`, which is how the reference prints one. A positionless error
3617    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3618    /// the reference raises it from `js_resolve_module`, where there is no position.
3619    pub(crate) fn syntax_error_plain(
3620        &mut self,
3621        error: &js_parse::SyntaxError,
3622        file: &str,
3623    ) -> Value {
3624        if error.positionless {
3625            return self.make_error("SyntaxError", &error.message);
3626        }
3627        self.syntax_error_at(
3628            file,
3629            error.span.start.line,
3630            error.span.start.column,
3631            &error.message,
3632        )
3633    }
3634
3635    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3636        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
3637        let value = self.make_error("SyntaxError", message);
3638        if let Value::Object(object) = &value {
3639            let text = self.string(blamed);
3640            object.define("stack", Property::with_attributes(text, true, true));
3641            let name = self.string(file);
3642            object.define("fileName", Property::with_attributes(name, true, true));
3643            object.define(
3644                "lineNumber",
3645                Property::with_attributes(Value::Int(line as i32), true, true),
3646            );
3647            object.define(
3648                "columnNumber",
3649                Property::with_attributes(Value::Int(column as i32), true, true),
3650            );
3651        }
3652        value
3653    }
3654
3655    /// Run a compiled script whose completion value is a function, returning it.
3656    ///
3657    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3658    /// get the closure out, which keeps the constant-pool plumbing in one place.
3659    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3660        self.run_script(code)
3661    }
3662
3663    /// The environment of a script or of any function compiled at global scope:
3664    /// every entry is a global binding, so each one resolves to the realm's cell.
3665    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3666        let mut cells = Vec::with_capacity(closure_vars.len());
3667        for closure_var in closure_vars {
3668            let cell = match closure_var.closure_type {
3669                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3670                    if closure_var.is_lexical =>
3671                {
3672                    // A lexical declaration: the cell is created here holding the
3673                    // dead-zone marker, which is what makes the binding exist and
3674                    // unreadable before its initialiser runs.
3675                    self.declare_global(&closure_var.name, closure_var.is_const);
3676                    self.realm.globals[&closure_var.name].clone()
3677                }
3678                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3679                    // A `var` or function declaration becomes a property of the global
3680                    // object, and it exists from here on — which is why
3681                    // `print(v); var v = 1` prints `undefined` instead of raising.
3682                    // Declaring it at instantiation time (rather than at the
3683                    // initialiser) is also what makes it non-configurable: the store
3684                    // then lands on an existing property instead of creating one.
3685                    self.declare_var_global(&closure_var.name);
3686                    // The cell is a placeholder that nothing indexes; it cannot be
3687                    // omitted because the slot has to hold something.
3688                    self.new_cell(Value::Undefined)
3689                }
3690                _ => {
3691                    // An undeclared global is read by name; the cell is a
3692                    // placeholder that nothing indexes.
3693                    self.new_cell(Value::Undefined)
3694                }
3695            };
3696            cells.push(cell);
3697        }
3698        Gc::new(
3699            self.heap,
3700            ClosureEnv {
3701                cells,
3702                eval_scope: None,
3703                local_vars: None,
3704                local_phase: 1,
3705            },
3706        )
3707    }
3708
3709    /// Push a frame and run until it returns.
3710    pub(crate) fn execute(
3711        &mut self,
3712        code: Gc<CompiledCode>,
3713        env: Gc<ClosureEnv>,
3714        this: Value,
3715        args: Vec<Value>,
3716        callee: Value,
3717    ) -> JsResult<Value> {
3718        let depth = self.frames.len();
3719        if depth == 0 {
3720            // A throw that reached the host ends the *active* mode: the next one is catchable
3721            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3722            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3723            // for the throw that evaluation will raise.
3724            self.uncatchable = false;
3725        }
3726        self.push_frame(code, env, this, args, callee)?;
3727        loop {
3728            // The fast loop first: it runs whole runs of records with `pc` in a register.
3729            //
3730            // `step`'s `pc` lives in the frame, so every instruction writes it back and
3731            // reads it again — a store, a load and two bounds checks that a loop body does
3732            // not need, because nothing outside the loop can run in between. This is the
3733            // classic split: advance a register, and only spill it when leaving.
3734            //
3735            // `Some(value)` means the function ended by running off the end of its
3736            // instruction array, which is a normal return.
3737            let step = match self.run_fast() {
3738                Ok(Some(value)) => Ok(Step::Return(value)),
3739                Ok(None) => self.step(),
3740                Err(signal) => Err(signal),
3741            };
3742            match step {
3743                Ok(Step::Continue) => {}
3744                Ok(Step::Return(value)) => {
3745                    self.pop_frame();
3746                    // A frame that ended in a `tail_call` hands its value straight to
3747                    // its caller: nothing after the call can run, so every frame above
3748                    // the callee unwinds with the same value. See [`Frame::tail`] —
3749                    // the reference does not reuse frames either, so recursion depth
3750                    // and the stack-overflow limit behave the same way.
3751                    while self.frames.len() > depth && self.frame().tail {
3752                        self.pop_frame();
3753                    }
3754                    if self.frames.len() == depth {
3755                        return Ok(value);
3756                    }
3757                    // The caller resumes with the value on its stack.
3758                    self.frames
3759                        .last_mut()
3760                        .expect("a caller is live")
3761                        .stack
3762                        .push(value);
3763                }
3764                Err(Signal::Throw(value)) => {
3765                    // The host's standing request becomes the active mode for this unwind,
3766                    // and is consumed here so it does not leak into the next throw.
3767                    if self.uncatchable_next {
3768                        self.uncatchable_next = false;
3769                        self.uncatchable = true;
3770                    }
3771                    // An uncatchable throw walks past every `catch` on the way out. The
3772                    // frames are still popped, because the values they hold have to be
3773                    // dropped — only the search for a handler is skipped.
3774                    if self.uncatchable {
3775                        while self.frames.len() > depth {
3776                            self.frames.pop();
3777                        }
3778                        return Err(Signal::Throw(value));
3779                    }
3780                    // A handler lives on the stack of the frame that is throwing —
3781                    // `catch` pushed it there — so this frame gets the first chance
3782                    // to catch before it is popped.
3783                    let value = value;
3784                    loop {
3785                        if self.frames.len() <= depth {
3786                            return Err(Signal::Throw(value));
3787                        }
3788                        if self.catch_here(value.clone()).is_some() {
3789                            break;
3790                        }
3791                        self.frames.pop();
3792                    }
3793                }
3794                // A `yield` in a frame that `execute` is running directly means a
3795                // generator body was entered as an ordinary call, which only happens if
3796                // the generator check in `call_or_push` was bypassed.
3797                Ok(Step::Suspend(_)) => {
3798                    return Err(Signal::Throw(self.make_error(
3799                        "InternalError",
3800                        "a generator body ran as an ordinary call",
3801                    )));
3802                }
3803                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3804            }
3805        }
3806    }
3807
3808    /// Install a handler for `value` if this frame has one, resuming at it.
3809    ///
3810    /// The scan is the reference's: walk the frame's stack downwards looking for the
3811    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3812    /// `0` is an enumerator marker rather than a handler — it exists so that a
3813    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3814    /// here and the unwinding continues.
3815    fn catch_here(&mut self, value: Value) -> Option<()> {
3816        let frame = self.frames.last_mut()?;
3817        while let Some(top) = frame.stack.pop() {
3818            if let Value::CatchOffset(offset) = top {
3819                if offset == 0 {
3820                    continue;
3821                }
3822                frame.stack.push(value);
3823                frame.pc = offset as usize;
3824                return Some(());
3825            }
3826        }
3827        None
3828    }
3829
3830    fn push_frame(
3831        &mut self,
3832        code: Gc<CompiledCode>,
3833        env: Gc<ClosureEnv>,
3834        this: Value,
3835        mut args: Vec<Value>,
3836        callee: Value,
3837    ) -> JsResult<()> {
3838        // Two bounds, and the byte budget is the one that decides in practice. The
3839        // reference's message is `stack overflow` on an `InternalError`, not V8's
3840        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3841        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3842        let frame_cost = Self::frame_cost(&code);
3843        let stack_base = self.stack_used();
3844        if self.frames.len() >= self.max_frames
3845            || stack_base.saturating_add(frame_cost) > self.stack_limit
3846        {
3847            return Err(Signal::Throw(
3848                self.make_error("InternalError", "stack overflow"),
3849            ));
3850        }
3851        let arg_count = code.code.args.len();
3852        // How many were actually passed, which `arguments.length` reports and
3853        // `assert(x)` depends on: a call with one argument must not look like a call
3854        // with one argument and an explicit `undefined`.
3855        let passed = args.len();
3856        // Missing arguments are `undefined` in their slots; extra ones are dropped
3857        // from the slots but still reachable through `arguments`.
3858        //
3859        // A call that passes no more than the declared parameters needs **no** copy:
3860        // after the resize below, `args[..passed]` *is* the passed values. Only the
3861        // extra ones — which `truncate` is about to drop — have to be kept, and they are
3862        // the rare case. This used to copy every call: one `Value` clone per argument
3863        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3864        let passed_overflow = (passed > arg_count).then(|| {
3865            let mut values = self.take_values(passed, Value::Undefined);
3866            values[..passed].clone_from_slice(&args[..passed]);
3867            values
3868        });
3869        // Only when the counts differ, which for the overwhelmingly common call — as many
3870        // arguments as parameters — is never. `resize` followed by `truncate` on equal
3871        // lengths is two length compares and nothing else, but this is the hottest few
3872        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3873        if passed != arg_count {
3874            args.resize(arg_count, Value::Undefined);
3875            args.truncate(arg_count);
3876        }
3877        let cell_count = code.code.var_ref_count as usize;
3878        let mut cells = Vec::with_capacity(cell_count);
3879        for _ in 0..cell_count {
3880            cells.push(self.new_cell(Value::Undefined));
3881        }
3882        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3883        // A captured argument lives in its cell, not in the argument slot, so the
3884        // incoming value has to be moved there before the body runs.
3885        for (slot, cell) in code.arg_cell.iter().enumerate() {
3886            if *cell >= 0
3887                && let Some(value) = args.get(slot).cloned()
3888            {
3889                cells[*cell as usize].set(value);
3890            }
3891        }
3892        // Sloppy mode substitutes the global object for a missing receiver and boxes a
3893        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3894        // reports `object`. Strict mode passes the value through untouched.
3895        let this = if code.code.strict {
3896            this
3897        } else if this.is_nullish() {
3898            Value::Object(self.realm.global.clone())
3899        } else if matches!(this, Value::Object(_)) {
3900            this
3901        } else {
3902            match crate::builtins::this_object(self, &this) {
3903                Ok(boxed) => Value::Object(boxed),
3904                Err(_) => this,
3905            }
3906        };
3907        let stack_depth = code.code.stack_size as usize + 1;
3908        // Taken before the `push` borrows `self.frames`, because the operand stack comes
3909        // out of the same recycle pool the locals did.
3910        let stack = self.take_values(stack_depth, Value::Undefined);
3911        self.frames.push(Frame {
3912            code,
3913            env,
3914            this,
3915            args,
3916            passed_count: passed,
3917            passed_overflow: passed_overflow.map(Box::new),
3918            locals,
3919            cells,
3920            local_vars: None,
3921            // Exactly the depth the compiler computed, so the operand stack never
3922            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
3923            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
3924            // the buffer between calls, so "exactly" costs nothing after the first one.
3925            stack,
3926            pc: 0,
3927            at: 0,
3928            callee,
3929            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3930            cost: frame_cost,
3931            stack_base,
3932            tail: false,
3933        });
3934        Ok(())
3935    }
3936
3937    /// A value buffer of `len` slots, from the recycle pool when there is one.
3938    ///
3939    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
3940    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
3941        // A frame with no locals asks for nothing, and that is most frames: taking a
3942        // buffer out of the pool, clearing it and resizing it to zero is four operations
3943        // and a pool pop for an empty `Vec`, which is free to construct.
3944        if len == 0 {
3945            return Vec::new();
3946        }
3947        let mut buffer = self.free_values.pop().unwrap_or_default();
3948        buffer.clear();
3949        buffer.resize(len, fill);
3950        buffer
3951    }
3952
3953    /// Return a finished frame's value buffers for the next call to reuse.
3954    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
3955        for mut buffer in [
3956            std::mem::take(&mut frame.locals),
3957            frame
3958                .passed_overflow
3959                .take()
3960                .map(|buffer| *buffer)
3961                .unwrap_or_default(),
3962            std::mem::take(&mut frame.stack),
3963        ] {
3964            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
3965            // GC root: it kept every value the frame held reachable, which is invisible
3966            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
3967            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
3968            // exactly that within one run — the target `{}` of a finished IIFE was still
3969            // in its operand stack, in the pool.
3970            buffer.clear();
3971            // A buffer with no capacity is what `Vec::new` is; putting it back would just
3972            // fill the pool with nothing to offer.
3973            if free_values.len() < RECYCLE_SLOTS
3974                && buffer.capacity() > 0
3975                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
3976            {
3977                free_values.push(buffer);
3978            }
3979        }
3980    }
3981
3982    /// Pop a finished frame and keep its buffers.
3983    ///
3984    /// Every place that drops a frame goes through here: a recycled buffer is also where
3985    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
3986    /// nothing but the reuse.
3987    fn pop_frame(&mut self) -> Option<()> {
3988        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
3989        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
3990        let last = self.frames.len().checked_sub(1)?;
3991        Self::recycle(&mut self.free_values, &mut self.frames[last]);
3992        self.frames.truncate(last);
3993        Some(())
3994    }
3995
3996    /// Poll the host's interrupt handler, if one is installed.
3997    ///
3998    /// The counter is what keeps this off the hot path when nobody asked: the early return is
3999    /// one `Option` test, and with no handler installed the whole function is that test —
4000    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4001    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4002    #[inline]
4003    fn check_interrupt(&mut self) -> JsResult<()> {
4004        if self.interrupt.is_none() {
4005            return Ok(());
4006        }
4007        if self.interrupt_counter > 0 {
4008            self.interrupt_counter -= 1;
4009            return Ok(());
4010        }
4011        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4012        // The closure is taken out for the duration so that a handler which re-enters the
4013        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4014        let mut handler = self.interrupt.take().expect("checked above");
4015        let abort = handler();
4016        self.interrupt = Some(handler);
4017        if abort {
4018            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4019            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4020            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4021            // documentation says.
4022            self.uncatchable = true;
4023            return Err(Signal::Throw(
4024                self.make_error("InternalError", "interrupted"),
4025            ));
4026        }
4027        Ok(())
4028    }
4029
4030    /// A memory checkpoint: does the heap still fit under its limit?
4031    ///
4032    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4033    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4034    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4035    /// only at calls would let it run until the machine died, which is the exact failure
4036    /// `--memory-limit` exists to prevent.
4037    ///
4038    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4039    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4040    /// script that catches it, drops the reference and carries on is legitimate: measured
4041    /// on `qjs --memory-limit 1M`, the engine recovers.
4042    fn check_memory(&mut self) -> JsResult<()> {
4043        // One `Cell` read and a predictable branch when no limit is set, and an integer
4044        // compare when one is. Containers report their own growth as it happens
4045        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4046        // walking it here was the first version and it was O(live) per 256 instructions,
4047        // which turned a 100k-element push loop into a five-minute one.
4048        let Some(limit) = self.heap.memory_limit() else {
4049            return Ok(());
4050        };
4051        let used = self.heap.used_bytes();
4052        if used <= limit {
4053            // Back under the limit — a collection or a dropped reference did it. The next
4054            // time it goes over is a new failure, not a repeat of this one.
4055            self.oom_reported_at = 0;
4056            return Ok(());
4057        }
4058        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4059        // block runs normally after `out of memory` — it allocates nothing, so nothing
4060        // fails. A check that re-fired on every instruction made the handler itself throw,
4061        // which is a dead end: the error became unobservable from script.
4062        //
4063        // Comparing against the total at the last report gives the same behaviour: the
4064        // handler runs while the total is unchanged, and the very next allocation over the
4065        // limit fails.
4066        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4067        {
4068            return Ok(());
4069        }
4070        self.oom_reported_at = used;
4071        Err(Signal::Throw(
4072            self.make_error("InternalError", "out of memory"),
4073        ))
4074    }
4075
4076    /// Fail before allocating `payload` bytes, if they would not fit.
4077    ///
4078    /// For the allocations whose size comes from script data — `new Array(n)`,
4079    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4080    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4081    /// answering NULL for the one big request.
4082    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4083        if self.heap.fits(payload) {
4084            return Ok(());
4085        }
4086        Err(Signal::Throw(
4087            self.make_error("InternalError", "out of memory"),
4088        ))
4089    }
4090
4091    /// Bytes of frame state the live call chain accounts for.
4092    pub fn stack_used(&self) -> usize {
4093        match self.frames.last() {
4094            Some(frame) => frame.stack_base + frame.cost,
4095            None => 0,
4096        }
4097    }
4098
4099    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4100    ///
4101    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4102    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4103    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4104    /// instead. That is the whole difference between the two models: it rations C stack, we
4105    /// ration frame state, and both quantities are dominated by the value slots — which is
4106    /// why the two depths come out comparable rather than merely proportional.
4107    fn frame_cost(code: &CompiledCode) -> usize {
4108        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4109        std::mem::size_of::<Frame>()
4110            + std::mem::size_of::<Value>() * slots
4111            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4112    }
4113
4114    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4115    ///
4116    /// Only names the eval created are here: a name the frame already declared statically
4117    /// is written through to its own slot instead, so this cannot shadow a real local.
4118    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4119        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4120        let (local_vars, phase) = self.visible_local_vars()?;
4121        if !local_vars.contains(name) {
4122            return None;
4123        }
4124        local_vars.get(name, phase)
4125    }
4126
4127    /// The variables a direct `eval` declared, as the code currently running sees them.
4128    ///
4129    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4130    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4131    /// else it is the current frame's, falling back to the frame the closure was created
4132    /// in.
4133    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4134    ///
4135    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4136    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4137    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4138    /// just to be asked `is_none`.
4139    fn has_visible_local_vars(&self) -> bool {
4140        let index = match self.eval_caller.flatten() {
4141            Some(caller) => caller,
4142            None => match self.frames.len().checked_sub(1) {
4143                Some(top) => top,
4144                None => return false,
4145            },
4146        };
4147        match self.frames.get(index) {
4148            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4149            None => false,
4150        }
4151    }
4152
4153    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4154        // While an `eval` runs, its own frame is on top but its variable environment is
4155        // the *caller's* — so the caller is what the lookup has to start from.
4156        let (index, phase) = match self.eval_caller.flatten() {
4157            Some(caller) => (
4158                caller,
4159                if self.in_parameter_list_at(caller) {
4160                    0
4161                } else {
4162                    1
4163                },
4164            ),
4165            None => (
4166                self.frames.len().checked_sub(1)?,
4167                if self.in_parameter_list() { 0 } else { 1 },
4168            ),
4169        };
4170        let frame = self.frames.get(index)?;
4171        // The frame's own variables, or — for an arrow, which has no variable environment
4172        // of its own — the one it was created in, which `ClosureEnv` carries.
4173        if let Some(local_vars) = frame.local_vars.clone() {
4174            return Some((local_vars, phase));
4175        }
4176        frame
4177            .env
4178            .local_vars
4179            .clone()
4180            .map(|local_vars| (local_vars, frame.env.local_phase))
4181    }
4182
4183    /// Whether the innermost frame is still evaluating its parameter list.
4184    ///
4185    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4186    /// and a closure created there may only see that much of [`LocalVars`].
4187    fn in_parameter_list(&self) -> bool {
4188        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4189    }
4190
4191    /// [`Interp::in_parameter_list`] for a specific frame.
4192    fn in_parameter_list_at(&self, frame: usize) -> bool {
4193        let Some(frame) = self.frames.get(frame) else {
4194            return false;
4195        };
4196        let code = &frame.code.code;
4197        if !code.has_parameter_expressions {
4198            return false;
4199        }
4200        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4201        // function as its body and let a direct `eval` act accordingly.
4202        if code.body_start == (0, 0) {
4203            return false;
4204        }
4205        match code.position_at(frame.at as u32) {
4206            Some(position) => position < code.body_start,
4207            None => false,
4208        }
4209    }
4210
4211    fn frame(&self) -> &Frame {
4212        self.frames.last().expect("a frame is live")
4213    }
4214
4215    fn frame_mut(&mut self) -> &mut Frame {
4216        self.frames.last_mut().expect("a frame is live")
4217    }
4218
4219    // -- slot access --------------------------------------------------------
4220
4221    /// Move a local's value out, leaving `undefined` in the slot.
4222    ///
4223    /// `None` for a captured slot: its value lives in a cell shared with every closure
4224    /// that closed over it, so it can never be exclusively ours and must not be taken.
4225    ///
4226    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4227    /// for every read and fatal for this one — a clone is exactly the second handle that
4228    /// rules out growing the string in place.
4229    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4230        let frame = self.frames.last_mut()?;
4231        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4232            return None;
4233        }
4234        frame
4235            .locals
4236            .get_mut(slot)
4237            .map(|value| std::mem::replace(value, Value::Undefined))
4238    }
4239
4240    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4241    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4242    ///
4243    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4244    /// it** — the value is put back before the general path runs — so a `valueOf` that
4245    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4246    /// error as it would have without the fusion. This is why the in-place attempt is a
4247    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4248    /// a wrong answer with a good excuse.
4249    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4250        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4251        // is put back on every path that does not append. An earlier version wrote the two
4252        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4253        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4254        // through with its value already taken and dropped: the general path below then
4255        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4256        // A wrong answer, from an optimisation, with every test green.
4257        if matches!(right, Value::String(_))
4258            && let Some(taken) = self.take_loc(slot)
4259        {
4260            if let Value::String(mut left) = taken {
4261                let appended = match left.get_mut() {
4262                    Some(string) => string.append_in_place(
4263                        // The pattern is the one `matches!` just checked.
4264                        match &right {
4265                            Value::String(text) => text,
4266                            _ => unreachable!("guarded above"),
4267                        },
4268                    ),
4269                    None => None,
4270                };
4271                self.put_loc(slot, Value::String(left));
4272                if let Some(added) = appended {
4273                    // The buffer grew where it stood, so the heap's running total has to
4274                    // be told: `measure_used` would report the new length, and the two must
4275                    // agree or the subtraction at free time leaves the counter wrong.
4276                    self.heap.adjust_payload(added as isize);
4277                    return Ok(());
4278                }
4279            } else {
4280                self.put_loc(slot, taken);
4281            }
4282        }
4283        // The two-number case, without an operand stack round trip. Everything below
4284        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4285        // store it — five operations and two `Value` clones for what is one integer add.
4286        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4287        // for string append and never got the numeric half, so `t += i` — a counting loop
4288        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4289        let left = self.get_loc(slot);
4290        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4291            self.put_loc(
4292                slot,
4293                match a.checked_add(*b) {
4294                    Some(sum) => Value::Int(sum),
4295                    None => Value::Float(*a as f64 + *b as f64),
4296                },
4297            );
4298            return Ok(());
4299        }
4300        self.push(left);
4301        self.push(right);
4302        self.binary_add()?;
4303        let value = self.pop();
4304        self.put_loc(slot, value);
4305        Ok(())
4306    }
4307
4308    fn get_arg(&self, slot: usize) -> Value {
4309        self.frame().read_arg(slot)
4310    }
4311
4312    fn put_arg(&mut self, slot: usize, value: Value) {
4313        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4314        if cell == -1 {
4315            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4316                *slot = value;
4317            }
4318        } else {
4319            self.frame().cells[cell as usize].set(value);
4320        }
4321    }
4322
4323    fn get_loc(&self, slot: usize) -> Value {
4324        // The cell mapping is `-1` for every slot that was not captured — which is all of
4325        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4326        // so the common case is one array read and a clone: 20% of every loop iteration
4327        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4328        // sample of `dispatch:arith`).
4329        self.frame().read_loc(slot)
4330    }
4331
4332    fn put_loc(&mut self, slot: usize, value: Value) {
4333        // One borrow instead of three, and the cell check on the frame we already hold.
4334        let frame = self.frames.last_mut().expect("a frame is live");
4335        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4336        if cell < 0 {
4337            if let Some(slot) = frame.locals.get_mut(slot) {
4338                *slot = value;
4339            }
4340        } else if let Some(cell) = frame.cells.get(cell as usize) {
4341            cell.set(value);
4342        }
4343    }
4344
4345    // -- globals ------------------------------------------------------------
4346
4347    /// The name a global-slot operand refers to.
4348    fn global_name(&self, slot: usize) -> String {
4349        self.frame()
4350            .code
4351            .code
4352            .closure_vars
4353            .get(slot)
4354            .map(|c| c.name.clone())
4355            .unwrap_or_default()
4356    }
4357
4358    /// The facts about a global binding that decide where it lives.
4359    ///
4360    /// A script's globals split in two, and the split is observable: `var` and
4361    /// function declarations become properties of the global object (`globalThis.v`
4362    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4363    /// declarations live in the global *lexical* environment and are invisible there
4364    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4365    /// `is_lexical` flag means the answer is already in the bytecode.
4366    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4367        let name = self.global_name(slot);
4368        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4369        // while forwarding a reference through a nested function is built with the
4370        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4371        // closure. Presence in the realm's lexical table is the same fact, recorded
4372        // once, and every slot sees it.
4373        let lexical = self.realm.globals.contains_key(&name);
4374        let is_const = self.realm.lexical_consts.contains(&name);
4375        (name, lexical, is_const)
4376    }
4377
4378    /// The value of `name` in the innermost active `with` object, if any.
4379    ///
4380    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4381    /// innermost frame first and innermost block first within one. Walking frames rather
4382    /// than keeping a separate stack is what makes a closure called from inside a `with`
4383    /// see it, and what keeps the object alive only as long as the block is.
4384    /// The innermost active `with` object that has `name`, if any.
4385    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4386        let objects = self.eval_with.clone().unwrap_or_default();
4387        for object in objects {
4388            let key = self.string(name.to_string());
4389            if self
4390                .has_property(&key, &Value::Object(object.clone()))
4391                .ok()?
4392            {
4393                return Some(object);
4394            }
4395        }
4396        None
4397    }
4398
4399    /// Every active `with` object, innermost first.
4400    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4401        let mut objects = Vec::new();
4402        for frame in self.frames.iter().rev() {
4403            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4404                if var.kind != js_compile::VarKind::With {
4405                    continue;
4406                }
4407                // A captured binding lives in its cell and not in the slot list, so the
4408                // cell is consulted first — a closure created inside the block is exactly
4409                // what makes the object captured. Before the store runs the slot still
4410                // holds `undefined`, and a `with` object is always boxed, so a non-object
4411                // entry is simply not in scope yet.
4412                let value = frame
4413                    .code
4414                    .loc_cell
4415                    .get(index)
4416                    .copied()
4417                    .filter(|cell| *cell >= 0)
4418                    .and_then(|cell| frame.cells.get(cell as usize))
4419                    .map(|cell| cell.get())
4420                    .or_else(|| frame.locals.get(index).cloned());
4421                if let Some(Value::Object(object)) = value {
4422                    objects.push(object);
4423                }
4424            }
4425        }
4426        objects
4427    }
4428
4429    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4430        for object in self.eval_with.clone().unwrap_or_default() {
4431            let key = self.string(name.to_string());
4432            if self.has_property(&key, &Value::Object(object.clone()))? {
4433                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4434            }
4435        }
4436        Ok(None)
4437    }
4438
4439    /// Whether every scope between here and the global object is an ordinary one.
4440    ///
4441    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4442    /// bytecode resolved; when any is live the general path has to run in full order. When
4443    /// none is — every ordinary program — a global read is a property read and nothing
4444    /// else, and that is worth caching.
4445    fn scopes_are_plain(&self) -> bool {
4446        self.eval_caller.is_none()
4447            && self.eval_with.is_none()
4448            && self.eval_arguments.is_none()
4449            && self.eval_bindings.is_empty()
4450            && self.eval_scope.is_none()
4451            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4452            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4453            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4454            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4455            // upstream corpus caught and no unit test did.
4456            && !self.has_visible_local_vars()
4457            && self.frame().env.eval_scope.is_none()
4458    }
4459
4460    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4461        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4462        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4463        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4464        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4465        // borrow outlive the `&mut self` the lookup needs.
4466        //
4467        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4468        // forwarded through a nested function has its flags cleared, so the flag cannot
4469        // be believed.
4470        let code = self.frame().code.clone();
4471        let name = code
4472            .code
4473            .closure_vars
4474            .get(slot)
4475            .map(|c| c.name.as_str())
4476            .unwrap_or_default();
4477        let lexical = self.realm.globals.contains_key(name);
4478        // The common case, first: an ordinary global `var`, with a cache in front of the
4479        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4480        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4481        // cache hit and return without touching any of it.
4482        if !lexical && self.scopes_are_plain() {
4483            return self.get_plain_global(name, slot);
4484        }
4485        if name == "arguments"
4486            && let Some(arguments) = &self.eval_arguments
4487        {
4488            return Ok(arguments.clone());
4489        }
4490        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4491        // the objects live when the eval started are consulted before anything else. The
4492        // snapshot is taken at entry rather than scanning the frames on every read: a
4493        // block that has already finished still leaves its object in the slot, and a
4494        // bytecode read outside the block must not see it.
4495        if let Some(value) = self.with_lookup(name)? {
4496            return Ok(value);
4497        }
4498        // A variable a direct `eval` declared shadows everything the compiler resolved,
4499        // including an enclosing function's binding: the eval put it in the caller's own
4500        // variable environment, which is nearer than any captured scope.
4501        if let Some((local_vars, phase)) = self.visible_local_vars()
4502            && let Some(cell) = local_vars.get(name, phase)
4503        {
4504            return Ok(cell.get());
4505        }
4506        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4507        // its local `a` wins over a global `a`.
4508        if let Some(value) = self.eval_binding_value(name) {
4509            return Ok(value);
4510        }
4511        // A closure created by an `eval` resolves its free names against the bindings
4512        // that eval saw, even after the eval (and its frames) are gone.
4513        if let Some(cell) = self
4514            .frame()
4515            .env
4516            .eval_scope
4517            .as_ref()
4518            .and_then(|scope| scope.get(name))
4519        {
4520            let value = cell.get();
4521            if matches!(value, Value::Uninitialized) {
4522                return Err(self.throw_reference(name));
4523            }
4524            return Ok(value);
4525        }
4526        // A binding declared by the strict `eval` currently running shadows anything
4527        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4528        if let Some(scope) = &self.eval_scope
4529            && let Some(value) = scope.get(name)
4530        {
4531            return Ok(value.clone());
4532        }
4533        if lexical {
4534            // A lexical global is a binding in a side table, so the dead zone is
4535            // visible and it is nowhere on the global object.
4536            if let Some(cell) = self.realm.globals.get(name) {
4537                let value = cell.get();
4538                if matches!(value, Value::Uninitialized) {
4539                    return Err(self.throw_reference(name));
4540                }
4541                return Ok(value);
4542            }
4543            return Err(self.throw_reference(name));
4544        }
4545        // A `var` global is an ordinary property, so the prototype chain and the
4546        // global object's own builtins are all reachable through it.
4547        match self.get_property(&self.realm.global.clone(), name)? {
4548            Some(value) => Ok(value),
4549            None => Err(self.throw_reference(name)),
4550        }
4551    }
4552
4553    /// Read a plain global `var`: a cached own data property, or the full lookup.
4554    ///
4555    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4556    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4557    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4558        let object = self.realm.global.clone();
4559        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4560        if let Some(cached) = &self.global_cache[site]
4561            && object.upgrades_to(&cached.object)
4562            && let Some(value) = object.data_property_at(cached.index, name)
4563        {
4564            return Ok(value);
4565        }
4566        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4567        // chain exactly as before, then remember the answer if it is worth remembering.
4568        let Some(value) = self.get_property(&object, name)? else {
4569            return Err(self.throw_reference(name));
4570        };
4571        if let Some(index) = object.own_data_index(name) {
4572            self.global_cache[site] = Some(GlobalCache {
4573                object: object.downgrade(),
4574                index,
4575            });
4576        }
4577        Ok(value)
4578    }
4579
4580    /// Store to a global binding.
4581    ///
4582    /// Returns a signal when the store is refused: a `const` global may only be
4583    /// written by its initialiser, and a non-configurable `var` global may not be
4584    /// deleted but is always writable.
4585    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4586        let (name, lexical, is_const) = self.global_binding(slot);
4587
4588        // An assignment inside a `with` writes through to the object that supplies the
4589        // name, which for an `eval` means consulting the same chain `get_global` does.
4590        if let Some(owner) = self.with_owner(&name) {
4591            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4592            return Ok(());
4593        }
4594        // A variable the running eval *declared* takes the write before any caller
4595        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4596        // environment even when an enclosing function has a `var c` of its own.
4597        if self.eval_caller.flatten().is_some()
4598            && let Some((local_vars, phase)) = self.visible_local_vars()
4599            && local_vars.contains(&name)
4600            && let Some(cell) = local_vars.get(&name, phase)
4601        {
4602            cell.set(value);
4603            return Ok(());
4604        }
4605        // A binding of the frame that called `eval` takes the write, which is what
4606        // makes `f("a = 3")` change the caller's `a`.
4607        if self.set_eval_binding(&name, &value)? {
4608            return Ok(());
4609        }
4610        // A closure that outlived its `eval` writes through to the same cell it reads.
4611        if let Some(cell) = self
4612            .frame()
4613            .env
4614            .eval_scope
4615            .as_ref()
4616            .and_then(|scope| scope.get(&name))
4617            .cloned()
4618        {
4619            cell.set(value);
4620            return Ok(());
4621        }
4622        // Inside a strict `eval`, a name it declared itself is stored there. An
4623        // *assignment* to a name nobody declared is not a declaration, so it falls
4624        // through: strict mode raises `ReferenceError` for it, which is what
4625        // `eval("1 + (@not_def = 1)")` has to do.
4626        if let Some(scope) = self.eval_scope.as_mut()
4627            && scope.contains_key(&name)
4628        {
4629            scope.insert(name, value);
4630            return Ok(());
4631        }
4632        if lexical {
4633            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4634                if is_const && !matches!(cell.get(), Value::Uninitialized) {
4635                    return Err(self.read_only_global(&name));
4636                }
4637                cell.set(value);
4638                return Ok(());
4639            }
4640            // Writing an undeclared lexical global is a `ReferenceError` in strict
4641            // mode and a silent global creation otherwise; creating the cell here
4642            // keeps both paths from losing the value.
4643            let cell = self.new_cell(value);
4644            self.realm.globals.insert(name, cell);
4645            return Ok(());
4646        }
4647        // A variable a direct `eval` declared in this call shadows the global object, even
4648        // when the global already has a property of that name — `var c = "global"` at the
4649        // top level must not capture `eval("var c = 1")` inside a function.
4650        if let Some((local_vars, phase)) = self.visible_local_vars()
4651            && local_vars.contains(&name)
4652            && let Some(cell) = local_vars.get(&name, phase)
4653        {
4654            cell.set(value);
4655            return Ok(());
4656        }
4657        let global = self.realm.global.clone();
4658        match global.own_property(&name) {
4659            // A `var` global is writable, so the store goes straight through — but
4660            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4661            // store (a non-writable or accessor-without-setter global) is a silent
4662            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4663            // split every other assignment has.
4664            Some(_) => {
4665                let on_failure = if self.current_strict() {
4666                    DeleteFailure::Throw
4667                } else {
4668                    DeleteFailure::Ignore
4669                };
4670                self.set_property_with(&global, &name, value, on_failure)
4671            }
4672            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4673            // declaration creates a *configurable* property, which is what makes it
4674            // deletable and is the one way a global differs from a declared `var`.
4675            // In strict mode the same store is a `ReferenceError` instead: that is the
4676            // whole point of strict mode, and creating the global silently meant
4677            // `"use strict"; x = 1` looked like it worked.
4678            None => {
4679                if self.current_strict() {
4680                    return Err(self.throw_reference(&name));
4681                }
4682                // A direct eval declares here rather than on the global object: its
4683                // `var`s belong to the caller's variable environment. `declare_eval_local`
4684                // also covers a plain assignment to a variable an earlier eval made.
4685                if let Some(cell) = self.declare_eval_local(&name) {
4686                    cell.set(value);
4687                    return Ok(());
4688                }
4689                global.define_data(&name, value);
4690                Ok(())
4691            }
4692        }
4693    }
4694
4695    /// The value of a binding of the frame that called `eval`, if there is one.
4696    fn eval_binding_value(&self, name: &str) -> Option<Value> {
4697        let binding = self
4698            .eval_bindings
4699            .iter()
4700            .find(|binding| binding.name == name)?;
4701        let owner = self.frames.get(binding.frame)?;
4702        let (slot, index) = (binding.slot, binding.index);
4703        Some(match slot {
4704            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4705                cell if cell >= 0 => owner
4706                    .cells
4707                    .get(cell as usize)
4708                    .map(|cell| cell.get())
4709                    .unwrap_or(Value::Undefined),
4710                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4711            },
4712            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4713                cell if cell >= 0 => owner
4714                    .cells
4715                    .get(cell as usize)
4716                    .map(|cell| cell.get())
4717                    .unwrap_or(Value::Undefined),
4718                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4719            },
4720        })
4721    }
4722
4723    /// Write to a binding of the frame that called `eval`.
4724    ///
4725    /// `Ok(false)` means no binding matched and the caller should keep looking. A
4726    /// matched binding can still refuse the store, which is why this is fallible: a
4727    /// `const` is read-only everywhere, and a named function expression's own name is
4728    /// read-only in strict mode.
4729    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4730        let Some(binding) = self
4731            .eval_bindings
4732            .iter()
4733            .find(|binding| binding.name == name)
4734        else {
4735            return Ok(false);
4736        };
4737        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4738        let strict = self.current_strict();
4739        let Some(owner) = self.frames.get_mut(frame) else {
4740            return Ok(false);
4741        };
4742        match slot {
4743            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4744                cell if cell >= 0 => {
4745                    if let Some(cell) = owner.cells.get(cell as usize) {
4746                        cell.set(value.clone());
4747                    }
4748                }
4749                _ => {
4750                    if let Some(slot) = owner.args.get_mut(index) {
4751                        *slot = value.clone();
4752                    }
4753                }
4754            },
4755            EvalSlot::Local => {
4756                let declared = owner.code.code.vars.get(index);
4757                // A `const` is read-only even through `eval`. The realm records this for
4758                // globals (see `lexical_consts`), but a local's `const`-ness is only in
4759                // the bytecode, so this is where it has to be enforced.
4760                if declared.is_some_and(|var| var.is_const) {
4761                    return Err(self.read_only_local(name));
4762                }
4763                // The name of a named function expression is read-only too, but only
4764                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4765                // such a name is ignored, the same as a direct store would be.
4766                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4767                    return if strict {
4768                        Err(self.read_only_local(name))
4769                    } else {
4770                        Ok(true)
4771                    };
4772                }
4773                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4774                    cell if cell >= 0 => {
4775                        if let Some(cell) = owner.cells.get(cell as usize) {
4776                            cell.set(value.clone());
4777                        }
4778                    }
4779                    _ => {
4780                        if let Some(slot) = owner.locals.get_mut(index) {
4781                            *slot = value.clone();
4782                        }
4783                    }
4784                }
4785            }
4786        }
4787        Ok(true)
4788    }
4789
4790    /// The `TypeError` an assignment to a read-only binding raises.
4791    fn read_only_local(&self, name: &str) -> Signal {
4792        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4793    }
4794
4795    /// Declare `name` as a variable of the frame that called the running `eval`.
4796    ///
4797    /// `None` when there is no direct eval in progress, or it was called from the top
4798    /// level — then the caller's variable environment *is* the global one and the
4799    /// existing path is right.
4800    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4801        let caller = self.eval_caller.flatten()?;
4802        // The bottom frame is the top-level script, whose variable environment *is* the
4803        // global one — so `eval("var x = 1")` at the top level still creates a global.
4804        if caller == 0 {
4805            return None;
4806        }
4807        // A name the eval's *own* variable environment already binds is not a new
4808        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4809        // `arguments`, and creating a second binding would leave the first — the one
4810        // closures read — untouched. A binding of an *outer* frame does not count: a
4811        // declaration shadows it rather than writing through.
4812        if self
4813            .eval_bindings
4814            .iter()
4815            .any(|binding| binding.name == name && binding.frame == caller)
4816        {
4817            return None;
4818        }
4819        let phase = if self.in_parameter_list_at(caller) {
4820            0
4821        } else {
4822            1
4823        };
4824        self.frame_local_vars(caller)?;
4825        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4826        if let Some(cell) = local_vars.get(name, 1) {
4827            return Some(cell);
4828        }
4829        let cell = self.new_cell(Value::Undefined);
4830        Some(local_vars.declare(name, phase, cell))
4831    }
4832
4833    /// Make sure `frame` has a `LocalVars`, creating it on demand.
4834    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4835        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4836            return Some(local_vars.clone());
4837        }
4838        let local_vars = Gc::new(self.heap, LocalVars::new());
4839        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4840        Some(local_vars)
4841    }
4842
4843    /// Whether the realm already has a binding for `name`, lexically or as an *own*
4844    /// property of the global object. Used to decide whether a store inside an
4845    /// `eval` writes through to the realm or declares a binding of its own.
4846    ///
4847    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4848    /// write to `Object.prototype.toString`, and must not shadow it either.
4849    fn global_knows(&mut self, name: &str) -> bool {
4850        if self.realm.globals.contains_key(name) {
4851            return true;
4852        }
4853        self.realm.global.own_property(name).is_some()
4854    }
4855
4856    /// Whether the code currently running is strict.
4857    ///
4858    /// Read off the frame's function, which is where the parser's answer ended up; a
4859    /// native function never runs strict-only checks, and there is no frame at all
4860    /// before the first script.
4861    pub fn current_strict(&self) -> bool {
4862        self.frames
4863            .last()
4864            .is_some_and(|frame| frame.code.code.strict)
4865    }
4866
4867    /// Initialise a declared global, which is what ends its dead zone.
4868    ///
4869    /// A `var` global becomes a property of the global object: writable, so a later
4870    /// assignment goes through, and non-configurable, so `delete` refuses.
4871    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4872        let (name, lexical, _) = self.global_binding(slot);
4873        // A `var` declared by the strict `eval` currently running belongs to the
4874        // eval's scope, not to the global object: `eval("var v = 1")` must not make
4875        // `typeof v` answer `"number"` afterwards. A name the realm already has is
4876        // initialised in place, which is what a re-declaration inside eval does.
4877        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4878            self.eval_scope
4879                .as_mut()
4880                .expect("checked above")
4881                .insert(name, value);
4882            return Ok(());
4883        }
4884        if let Some(scope) = self.eval_scope.as_mut()
4885            && scope.contains_key(&name)
4886        {
4887            scope.insert(name, value);
4888            return Ok(());
4889        }
4890        if lexical {
4891            // The cell exists (created at declaration time) holding the dead-zone
4892            // marker; storing the value is what makes the binding readable.
4893            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4894                cell.set(value);
4895                return Ok(());
4896            }
4897            let cell = self.new_cell(value);
4898            self.realm.globals.insert(name, cell);
4899            return Ok(());
4900        }
4901        let global = self.realm.global.clone();
4902        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4903        // to answer `false` and leave the binding in place. `with_attributes` ties
4904        // `configurable` to `writable`, so the property is built field by field.
4905        global.define(
4906            &name,
4907            Property {
4908                value: Some(value),
4909                writable: true,
4910                enumerable: true,
4911                configurable: false,
4912                ..Property::default()
4913            },
4914        );
4915        Ok(())
4916    }
4917
4918    /// The `TypeError` a store to a `const` global raises.
4919    fn read_only_global(&self, name: &str) -> Signal {
4920        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4921    }
4922
4923    // -- properties ---------------------------------------------------------
4924
4925    /// Read `object[key]`, following the prototype chain.
4926    ///
4927    /// An inherited accessor runs with the *receiver* as `this`, which is why the
4928    /// lookup returns the owner rather than just the value.
4929    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4930        self.get_property_key(object, &PropertyKey::from(key))
4931    }
4932
4933    /// [`Interp::get_property`] with a key that may be a symbol.
4934    pub fn get_property_key(
4935        &mut self,
4936        object: &Gc<JsObject>,
4937        key: &PropertyKey,
4938    ) -> JsResult<Option<Value>> {
4939        self.get_property_key_for(object, None, key)
4940    }
4941
4942    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
4943    ///
4944    /// The receiver matters when the property is found on a *prototype*: a getter has to
4945    /// see the object the read started from. For a primitive that is the primitive
4946    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
4947    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4948    /// the owner.
4949    pub fn get_property_key_for(
4950        &mut self,
4951        object: &Gc<JsObject>,
4952        receiver: Option<&Value>,
4953        key: &PropertyKey,
4954    ) -> JsResult<Option<Value>> {
4955        // A proxy answers for itself, before any of the shortcuts below: `new
4956        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4957        // have.
4958        if object.proxy_state().is_some() {
4959            let receiver = receiver
4960                .cloned()
4961                .unwrap_or_else(|| Value::Object(object.clone()));
4962            return self.proxy_get(object, &receiver, key);
4963        }
4964        // A host class's `get_property` trap replaces the whole read, prototype walk
4965        // included — that is what makes a native accessor free rather than a JavaScript
4966        // getter call.
4967        if let Some(exotic) = object.exotic() {
4968            let receiver_value = receiver
4969                .cloned()
4970                .unwrap_or_else(|| Value::Object(object.clone()));
4971            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
4972                return Ok(Some(value));
4973            }
4974            // With no `get_property` trap, a `get_own_property` trap still answers for the
4975            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
4976            // and the hook lives exactly there. A key the trap reports as absent is still
4977            // looked for on the prototype, which is why the search resumes *above*.
4978            if let Some(property) = exotic.get_own_property(self, object, key)? {
4979                return match property {
4980                    Some(property) => self.read_property(property, object, receiver),
4981                    None => match lookup_key_above(object, key) {
4982                        Some((_, property)) => self.read_property(property, object, receiver),
4983                        None => Ok(None),
4984                    },
4985                };
4986            }
4987        }
4988        // The element-vector and `length` shortcuts are string-only: an array index
4989        // has no symbol spelling.
4990        if let Some(text) = key.as_str() {
4991            if let Some(value) = self.own_element(object, text) {
4992                return Ok(Some(value));
4993            }
4994            // `length` is not stored as a property: an array's length is its element
4995            // count, and keeping one copy of it is what makes `push`/`pop` and
4996            // `a.length = n` agree.
4997            if let Some(length) = object.array_length()
4998                && text == "length"
4999            {
5000                // Not `Value::Int(length as i32)`: see [`length_value`].
5001                return Ok(Some(crate::object::length_value(length)));
5002            }
5003        }
5004        match lookup_key(object, key) {
5005            Some((_, property)) => self.read_property(property, object, receiver),
5006            None => Ok(None),
5007        }
5008    }
5009
5010    /// The value a property read answers.
5011    ///
5012    /// One place rather than three, because an accessor has to run with the *receiver* as
5013    /// `this` whether the descriptor came from the property table, an exotic
5014    /// `get_own_property` trap, or a prototype above one.
5015    fn read_property(
5016        &mut self,
5017        property: Property,
5018        object: &Gc<JsObject>,
5019        receiver: Option<&Value>,
5020    ) -> JsResult<Option<Value>> {
5021        if property.is_accessor() {
5022            match &property.getter {
5023                Some(getter) if !matches!(getter, Value::Undefined) => {
5024                    let receiver = receiver
5025                        .cloned()
5026                        .unwrap_or_else(|| Value::Object(object.clone()));
5027                    self.call_value(getter.clone(), receiver, Vec::new())
5028                        .map(Some)
5029                }
5030                // An accessor with no getter reads as `undefined`.
5031                _ => Ok(Some(Value::Undefined)),
5032            }
5033        } else {
5034            Ok(property.value)
5035        }
5036    }
5037
5038    /// `super.key` — start the search at `proto`, but report to `receiver`.
5039    ///
5040    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5041    /// found on the prototype of a class has to see the *instance* as `this`, and a
5042    /// plain property read off `proto` would lose that.
5043    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5044        let start = self.require_object(proto)?;
5045        let key = self.propkey(key)?;
5046        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5047        if matches!(proto, Value::Null) {
5048            return Ok(Value::Undefined);
5049        }
5050        match lookup_key(&start, &key) {
5051            Some((_, property)) if property.is_accessor() => match &property.getter {
5052                Some(getter) if !matches!(getter, Value::Undefined) => {
5053                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5054                }
5055                _ => Ok(Value::Undefined),
5056            },
5057            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5058            None => Ok(Value::Undefined),
5059        }
5060    }
5061
5062    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5063    ///
5064    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5065    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5066    /// assignment follows.
5067    fn super_write(
5068        &mut self,
5069        receiver: &Value,
5070        proto: &Value,
5071        key: &Value,
5072        value: Value,
5073    ) -> JsResult<()> {
5074        let target = self.require_object(receiver)?;
5075        let key = self.propkey(key)?;
5076        if !matches!(proto, Value::Null)
5077            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5078        {
5079            if property.is_accessor() {
5080                if let Some(setter) = &property.setter
5081                    && !matches!(setter, Value::Undefined)
5082                {
5083                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5084                }
5085                return Ok(());
5086            }
5087            // A data property on the prototype is writable or not; reading `owner` at
5088            // all is only for the attribute check.
5089            if !property.writable {
5090                return Err(self.type_error(format!("'{key}' is read-only")));
5091            }
5092            let _ = owner;
5093        }
5094        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5095    }
5096
5097    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5098    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5099        match value.as_object() {
5100            Some(object) => Ok(object.clone()),
5101            None => Err(Signal::Throw(
5102                self.make_error("TypeError", "value is not an object"),
5103            )),
5104        }
5105    }
5106
5107    /// Build the class object `define_class` produces.
5108    ///
5109    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5110    /// whose prototype property is a fresh object inheriting from the parent's
5111    /// prototype, and whose own prototype is the parent constructor — which is what makes
5112    /// a static method inherited too.
5113    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5114        let ctor = self.pop();
5115        let parent = self.pop();
5116        let Value::Object(function) = &ctor else {
5117            return Err(Signal::Throw(
5118                self.make_error("TypeError", "class constructor must be a function"),
5119            ));
5120        };
5121        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5122        // but gives the instances no prototype at all.
5123        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5124            match &parent {
5125                Value::Null => (Some(self.realm.function_proto.clone()), None),
5126                Value::Object(parent_class) => {
5127                    if !parent_class.is_callable() {
5128                        return Err(Signal::Throw(
5129                            self.make_error("TypeError", "parent class must be constructor"),
5130                        ));
5131                    }
5132                    let proto = self.get_property(parent_class, "prototype")?;
5133                    match proto {
5134                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5135                        Some(Value::Null) => (Some(parent_class.clone()), None),
5136                        _ => {
5137                            return Err(Signal::Throw(self.make_error(
5138                                "TypeError",
5139                                "parent prototype must be an object or null",
5140                            )));
5141                        }
5142                    }
5143                }
5144                _ => {
5145                    return Err(Signal::Throw(
5146                        self.make_error("TypeError", "parent class must be constructor"),
5147                    ));
5148                }
5149            }
5150        } else {
5151            (
5152                Some(self.realm.function_proto.clone()),
5153                Some(self.realm.object_proto.clone()),
5154            )
5155        };
5156        let proto = self.new_object(parent_proto);
5157        function.set_proto(parent_ctor);
5158        // A class is not callable without `new`, and its `prototype` is not writable —
5159        // both follow from being a class and are what `class A {}; A()` throws on.
5160        function.set_class_constructor(true);
5161        function.set_home_object(None);
5162        self.set_function_name(&ctor, name);
5163        self.define_class_properties(function, &ctor, &proto)?;
5164        Ok((ctor, proto))
5165    }
5166
5167    /// Give the constructor its `prototype` and `length`, and the prototype its
5168    /// `constructor` back-pointer.
5169    fn define_class_properties(
5170        &mut self,
5171        function: &Gc<JsObject>,
5172        ctor: &Value,
5173        proto: &Gc<JsObject>,
5174    ) -> JsResult<()> {
5175        proto.define(
5176            "constructor",
5177            Property::with_attributes(ctor.clone(), true, false),
5178        );
5179        function.define(
5180            "prototype",
5181            Property::prototype_of(Value::Object(proto.clone()), false),
5182        );
5183        if let Some((code, _)) = bytecode_of(function) {
5184            let length = code.code.defined_args;
5185            function.define(
5186                "length",
5187                Property::name_or_length(Value::Int(length as i32)),
5188            );
5189        }
5190        Ok(())
5191    }
5192
5193    /// The own array element `key` names, if this object has one.
5194    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5195        let index = array_index(key)?;
5196        // A typed array's elements live in its buffer, not in a property list: reading one
5197        // goes through the view's element type so a bounds check and a detached buffer are
5198        // both handled there.
5199        if object.typed_array_parts().is_some() {
5200            return object.typed_array_element(index as usize);
5201        }
5202        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5203        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5204        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5205        // `[1,,3][1]`.
5206        match object.array_get(index as usize) {
5207            Some(Value::Hole) | None => None,
5208            other => other,
5209        }
5210    }
5211
5212    /// Store `object[key] = value`, honouring setters and inherited properties.
5213    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5214        self.set_property_with(object, key, value, DeleteFailure::Throw)
5215    }
5216
5217    /// Store a property, choosing what to do when the object refuses.
5218    ///
5219    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5220    /// mode, which is the one place assignment differs by mode. Native code (the array
5221    /// methods, `JSON`) always asks for the throw.
5222    pub fn set_property_with(
5223        &mut self,
5224        object: &Gc<JsObject>,
5225        key: &str,
5226        value: Value,
5227        on_failure: DeleteFailure,
5228    ) -> JsResult<()> {
5229        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5230    }
5231
5232    /// [`Interp::set_property_with`] with a key that may be a symbol.
5233    pub fn set_property_with_key(
5234        &mut self,
5235        object: &Gc<JsObject>,
5236        key: &PropertyKey,
5237        value: Value,
5238        on_failure: DeleteFailure,
5239    ) -> JsResult<()> {
5240        self.set_property_with_key_receiver_aware(object, key, value, on_failure, true)
5241    }
5242
5243    /// As [`Interp::set_property_with_key`], with the receiver explicit.
5244    ///
5245    /// `same_receiver` is `SameValue(O, Receiver)` from §10.4.5.5 step 1.b.i, and the two
5246    /// branches it separates are observable in opposite directions: when the receiver *is*
5247    /// the view the element store converts `V` first and then asks whether the index is
5248    /// valid (`Set/resized-out-of-bounds-to-in-bounds-index`, where a `valueOf` puts the
5249    /// index back in bounds), and when it is not, an invalid index returns `true` without
5250    /// converting anything (`key-is-out-of-bounds-receiver-is-not-object`).
5251    fn set_property_with_key_receiver_aware(
5252        &mut self,
5253        object: &Gc<JsObject>,
5254        key: &PropertyKey,
5255        value: Value,
5256        on_failure: DeleteFailure,
5257        same_receiver: bool,
5258    ) -> JsResult<()> {
5259        // A proxy's `set` trap decides, and its `false` means the same thing an
5260        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5261        if object.proxy_state().is_some() {
5262            let receiver = Value::Object(object.clone());
5263            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5264                return match (accepted, on_failure) {
5265                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5266                    (false, DeleteFailure::Throw) => {
5267                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5268                    }
5269                };
5270            }
5271        }
5272        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5273        // refusal and means exactly what a proxy's `false` means.
5274        if let Some(exotic) = object.exotic() {
5275            let receiver = Value::Object(object.clone());
5276            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5277                return match (accepted, on_failure) {
5278                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5279                    (false, DeleteFailure::Throw) => {
5280                        Err(self.type_error(format!("property '{key}' is read-only")))
5281                    }
5282                };
5283            }
5284        }
5285        // The element and `length` shortcuts only exist for string keys: an array
5286        // index has no symbol spelling, and a symbol named `length` is an ordinary
5287        // property.
5288        let text = key.as_str();
5289        // A typed array's elements are a window onto its buffer: the store has to go
5290        // through the view's element type so the value is wrapped (or clamped) and so an
5291        // out-of-range or detached write is a silent no-op, as the spec says.
5292        if let Some(text) = text
5293            && let Some(index) = array_index(text)
5294            && let Some(element) = object.typed_array_element_type()
5295        {
5296            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5297            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5298            // in `Interp`, because it is script-observable and the storage borrow inside
5299            // `typed_array_set` must not be held across it.
5300            //
5301            // It runs even for an index that is out of bounds *now*, because `V` itself can
5302            // put it back in bounds: `TypedArraySetElement` converts first and asks
5303            // `IsValidIntegerIndex` afterwards, which is what
5304            // `Set/resized-out-of-bounds-to-in-bounds-index` asserts (a `valueOf` that
5305            // resizes a 0-byte buffer to 1 makes `ta[0] = value` store 100). The write is
5306            // still a no-op when the index stays out of bounds, which is why the extra
5307            // length check that used to guard this has no job left.
5308            if !same_receiver && index as usize >= object.typed_array_length().unwrap_or(0) {
5309                return Ok(());
5310            }
5311            let stored = self.element_value(element, value)?;
5312            if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5313                return Err(self.type_error(reason));
5314            }
5315            return Ok(());
5316        }
5317        if let Some(text) = text
5318            && let Some(index) = array_index(text)
5319            && object.is_array()
5320        {
5321            // An accessor defined on an index lives in the property table while the
5322            // element slot is a hole, so the store has to go through the property first.
5323            // Writing the vector directly skipped the setter entirely.
5324            if let Some(existing) = object.own_property_key(key) {
5325                if existing.is_accessor() {
5326                    return match existing.setter.clone() {
5327                        Some(setter) if !matches!(setter, Value::Undefined) => {
5328                            let receiver = Value::Object(object.clone());
5329                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5330                        }
5331                        _ => match on_failure {
5332                            DeleteFailure::Throw => Err(self.type_error(format!(
5333                                "cannot set property '{text}', it has only a getter"
5334                            ))),
5335                            DeleteFailure::Ignore => Ok(()),
5336                        },
5337                    };
5338                }
5339                if !existing.writable {
5340                    return match on_failure {
5341                        DeleteFailure::Throw => {
5342                            Err(self.type_error(format!("'{text}' is read-only")))
5343                        }
5344                        DeleteFailure::Ignore => Ok(()),
5345                    };
5346                }
5347            }
5348            {
5349                // Growing the array needs a writable `length`.
5350                if (index as usize) >= object.array_length().unwrap_or(0)
5351                    && !object.length_writable()
5352                {
5353                    return match on_failure {
5354                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5355                        DeleteFailure::Ignore => Ok(()),
5356                    };
5357                }
5358                // Adding an index past the end makes the array longer, which a
5359                // non-extensible array refuses.
5360                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5361                    return match on_failure {
5362                        DeleteFailure::Throw => Err(self.type_error(format!(
5363                            "cannot add property '{key}', object is not extensible"
5364                        ))),
5365                        DeleteFailure::Ignore => Ok(()),
5366                    };
5367                }
5368                if object.element_is_locked(index) {
5369                    return match on_failure {
5370                        DeleteFailure::Throw => {
5371                            Err(self.type_error(format!("'{key}' is read-only")))
5372                        }
5373                        DeleteFailure::Ignore => Ok(()),
5374                    };
5375                }
5376                // The element vector is only half of `[[Set]]` for an index: the
5377                // prototype chain is consulted first, and a setter there answers instead
5378                // of the element store. This branch used to write the element directly, so
5379                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5380                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5381                // the reference calls the setter and the array keeps no own index.
5382                if let Some((owner, property)) = lookup_key(object, key)
5383                    && !owner.ptr_eq(object)
5384                {
5385                    match &property {
5386                        property if property.is_accessor() => {
5387                            match &property.setter {
5388                                Some(setter) if !matches!(setter, Value::Undefined) => {
5389                                    let receiver = Value::Object(object.clone());
5390                                    self.call_value(setter.clone(), receiver, vec![value])?;
5391                                }
5392                                _ => {
5393                                    return match on_failure {
5394                                        DeleteFailure::Throw => Err(self.type_error(format!(
5395                                            "cannot set property '{text}', it has only a getter"
5396                                        ))),
5397                                        DeleteFailure::Ignore => Ok(()),
5398                                    };
5399                                }
5400                            }
5401                            return Ok(());
5402                        }
5403                        property if !property.writable => {
5404                            return match on_failure {
5405                                DeleteFailure::Throw => {
5406                                    Err(self.type_error(format!("'{text}' is read-only")))
5407                                }
5408                                DeleteFailure::Ignore => Ok(()),
5409                            };
5410                        }
5411                        _ => {}
5412                    }
5413                }
5414                if object.array_set(self.heap, index as usize, value.clone()) {
5415                    return Ok(());
5416                }
5417                // Past the dense limit the slot is too far out to be worth one `Value`
5418                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5419                // constant time by keeping the index as an ordinary property. The store
5420                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5421                // to a legal program.
5422                object.define_key(key, Property::with_attributes(value, true, true));
5423                // Extend, never shorten: the index may be *inside* the current length (a
5424                // huge `length` with a sparse store), and shortening would delete the
5425                // sparse properties above it — including the one just stored.
5426                if index as usize + 1 > object.array_length().unwrap_or(0) {
5427                    object.array_set_length(self.heap, index as usize + 1);
5428                }
5429                return Ok(());
5430            }
5431        }
5432        if text == Some("length") && object.is_array() {
5433            if !object.length_writable() {
5434                return match on_failure {
5435                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5436                    DeleteFailure::Ignore => Ok(()),
5437                };
5438            }
5439            let length = value.to_number();
5440            if length.is_finite() && length >= 0.0 {
5441                let length = length as usize;
5442                // `a.length = n` with `n` below a non-configurable element cannot
5443                // drop that element, so the whole assignment fails. The spec makes
5444                // this a `TypeError` rather than a silent no-op, in any mode.
5445                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5446                    // Sloppy mode stops the truncation at the blocking element
5447                    // instead of failing; strict mode raises.
5448                    // Both modes stop at the blocking element; they differ in
5449                    // whether that is reported. The reference truncates *then*
5450                    // throws, so the array is left in the shortened state.
5451                    object.array_truncate(self.heap, blocked + 1);
5452                    return match on_failure {
5453                        DeleteFailure::Throw => {
5454                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5455                        }
5456                        DeleteFailure::Ignore => Ok(()),
5457                    };
5458                }
5459                object.array_set_length(self.heap, length);
5460                return Ok(());
5461            }
5462        }
5463        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5464        {
5465            return match on_failure {
5466                DeleteFailure::Throw => Err(self.type_error(format!(
5467                    "cannot add property {}, object is not extensible",
5468                    key
5469                ))),
5470                DeleteFailure::Ignore => Ok(()),
5471            };
5472        }
5473        if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5474            if property.is_accessor() {
5475                match &property.setter {
5476                    Some(setter) if !matches!(setter, Value::Undefined) => {
5477                        let receiver = Value::Object(object.clone());
5478                        self.call_value(setter.clone(), receiver, vec![value])?;
5479                    }
5480                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5481                    // Sloppy code swallows that refusal, strict code raises — the same
5482                    // rule the read-only *data* property below follows, and skipping it
5483                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5484                    // return silently. The reference answers `TypeError: 'x' is
5485                    // read-only`.
5486                    _ => {
5487                        return match on_failure {
5488                            DeleteFailure::Throw => {
5489                                Err(self.type_error(format!("'{key}' is read-only")))
5490                            }
5491                            DeleteFailure::Ignore => Ok(()),
5492                        };
5493                    }
5494                }
5495                return Ok(());
5496            }
5497            // A non-writable data property refuses the write, own **or inherited**: an
5498            // own one stops here because nothing may change it, and an inherited one
5499            // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5500            //
5501            // The `ptr_eq` this used to carry meant an inherited read-only property fell
5502            // through to `define_data_key` and *did* create the shadow — `var o =
5503            // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5504            // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5505            // and `false`.
5506            if !property.writable {
5507                return match on_failure {
5508                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5509                    DeleteFailure::Ignore => Ok(()),
5510                };
5511            }
5512            // An existing writable own property keeps its attributes: only the value
5513            // moves. Redefining instead would reset them, which is how a
5514            // non-configurable global `var` used to become deletable.
5515            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5516                return Ok(());
5517            }
5518        }
5519        // No own data property: create one, shadowing whatever the prototype holds.
5520        object.define_data_key(key, value);
5521        Ok(())
5522    }
5523
5524    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5525    ///
5526    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5527    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5528    /// a virtual accessor gets its setter run without implementing `set_property` at all.
5529    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5530    /// the prototype, so the walk resumes above the object.
5531    fn lookup_for_write(
5532        &mut self,
5533        object: &Gc<JsObject>,
5534        key: &PropertyKey,
5535    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5536        let Some(exotic) = object.exotic() else {
5537            return Ok(lookup_key(object, key));
5538        };
5539        Ok(match exotic.get_own_property(self, object, key)? {
5540            Some(Some(property)) => Some((object.clone(), property)),
5541            Some(None) => lookup_key_above(object, key),
5542            None => lookup_key(object, key),
5543        })
5544    }
5545
5546    /// Delete `object[key]`.
5547    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5548        self.delete_property_key(object, &PropertyKey::from(key))
5549    }
5550
5551    /// [`Interp::delete_property`] with a key that may be a symbol.
5552    pub fn delete_property_key(
5553        &mut self,
5554        object: &Gc<JsObject>,
5555        key: &PropertyKey,
5556    ) -> JsResult<bool> {
5557        // A proxy decides for itself, and may even throw; the invariant checks live in
5558        // `proxy_delete`.
5559        if let Some(answer) = self.proxy_delete(object, key)? {
5560            return Ok(answer);
5561        }
5562        // A host class's `delete_property` trap decides; `false` is a refusal, which the
5563        // caller reports as a failed delete.
5564        if let Some(exotic) = object.exotic()
5565            && let Some(answer) = exotic.delete_property(self, object, key)?
5566        {
5567            return Ok(answer);
5568        }
5569        if let Some(index) = key.as_str().and_then(array_index)
5570            && let Some(length) = object.array_length()
5571            && (index as usize) < length
5572        {
5573            // An accessor defined on an index lives in the property table rather than the
5574            // element vector, so both have to be cleared: `delete` after
5575            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5576            object.delete_key(key);
5577            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5578            // index stops answering `in`.
5579            if object.element_is_undeletable(index) {
5580                return Ok(false);
5581            }
5582            object.array_set(self.heap, index as usize, Value::Hole);
5583            return Ok(true);
5584        }
5585        Ok(object.delete_key(key))
5586    }
5587
5588    // -- proxy traps --------------------------------------------------------
5589    //
5590    // A proxy's internal methods all look the same: ask the handler for the trap, call it
5591    // with the target and the operation's own arguments, then check the answer against
5592    // the target. The checks are not decoration — they are what stops a proxy from
5593    // reporting a `non-configurable` property as missing, which would let a frozen object
5594    // be rewritten by standing in front of it.
5595
5596    /// The target and handler of `object`, or `None` when it is not a proxy.
5597    ///
5598    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5599    /// one has to fail: the slots the traps would have been read from are gone.
5600    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5601        let Some(state) = object.proxy_state() else {
5602            return Ok(None);
5603        };
5604        let state = state.borrow();
5605        match (&state.target, &state.handler) {
5606            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5607            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5608        }
5609    }
5610
5611    /// Call `handler[name]`, or answer `None` when the trap is absent.
5612    ///
5613    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5614    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5615    /// back to the target.
5616    fn proxy_trap(
5617        &mut self,
5618        handler: &Value,
5619        name: &str,
5620        args: Vec<Value>,
5621    ) -> JsResult<Option<Value>> {
5622        let Value::Object(table) = handler else {
5623            return Err(self.type_error("proxy handler is not an object"));
5624        };
5625        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5626        match trap {
5627            Value::Undefined => Ok(None),
5628            Value::Object(function) if function.is_callable() => {
5629                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5630                Ok(Some(answer))
5631            }
5632            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5633        }
5634    }
5635
5636    /// Whether `object`'s own property `key` is one the target refuses to lose.
5637    ///
5638    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5639    /// its value behind the target's back. This goes through
5640    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5641    /// elements and its `length` — both fixed, both outside the table — are covered.
5642    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5643        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5644    }
5645
5646    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5647    fn proxy_get(
5648        &mut self,
5649        object: &Gc<JsObject>,
5650        receiver: &Value,
5651        key: &PropertyKey,
5652    ) -> JsResult<Option<Value>> {
5653        let Some((target, handler)) = self.proxy_parts(object)? else {
5654            return Ok(None);
5655        };
5656        let key_value = self.key_value(key);
5657        let Some(result) = self.proxy_trap(
5658            &handler,
5659            "get",
5660            vec![Value::Object(target.clone()), key_value, receiver.clone()],
5661        )?
5662        else {
5663            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5664            // inherited getter still sees the proxy.
5665            return Ok(Some(
5666                self.get_property_key_for(&target, Some(receiver), key)?
5667                    .unwrap_or(Value::Undefined),
5668            ));
5669        };
5670        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5671            if fixed.is_accessor() {
5672                // A fixed accessor with no getter must read as `undefined`.
5673                let has_getter = fixed
5674                    .getter
5675                    .as_ref()
5676                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
5677                if !has_getter && !matches!(result, Value::Undefined) {
5678                    return Err(self.type_error(format!(
5679                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
5680                    )));
5681                }
5682            } else if !fixed.writable {
5683                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5684                if !fixed_value.same_value(&result) {
5685                    return Err(self.type_error(format!(
5686                        "proxy 'get' disagrees with the non-configurable property '{key}'"
5687                    )));
5688                }
5689            }
5690        }
5691        Ok(Some(result))
5692    }
5693
5694    /// `[[Set]]` on a proxy.
5695    ///
5696    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5697    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5698    /// read-only store has.
5699    fn proxy_set(
5700        &mut self,
5701        object: &Gc<JsObject>,
5702        key: &PropertyKey,
5703        value: Value,
5704        receiver: &Value,
5705    ) -> JsResult<Option<bool>> {
5706        let Some((target, handler)) = self.proxy_parts(object)? else {
5707            return Ok(None);
5708        };
5709        let key_value = self.key_value(key);
5710        let Some(result) = self.proxy_trap(
5711            &handler,
5712            "set",
5713            vec![
5714                Value::Object(target.clone()),
5715                key_value,
5716                value.clone(),
5717                receiver.clone(),
5718            ],
5719        )?
5720        else {
5721            // No trap: store on the target, which is where an ordinary proxy write lands.
5722            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5723            return Ok(Some(true));
5724        };
5725        if !result.to_boolean() {
5726            return Ok(Some(false));
5727        }
5728        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5729            if fixed.is_accessor() {
5730                let has_setter = fixed
5731                    .setter
5732                    .as_ref()
5733                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
5734                if !has_setter {
5735                    return Err(self.type_error(format!(
5736                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5737                    )));
5738                }
5739            } else if !fixed.writable {
5740                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5741                if !fixed_value.same_value(&value) {
5742                    return Err(self.type_error(format!(
5743                        "proxy 'set' changed the non-configurable property '{key}'"
5744                    )));
5745                }
5746            }
5747        }
5748        // A new property cannot appear on a target that refuses new properties.
5749        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5750            return Err(self.type_error(format!(
5751                "proxy 'set' added '{key}' to a non-extensible target"
5752            )));
5753        }
5754        Ok(Some(true))
5755    }
5756
5757    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5758    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5759        let Some((target, handler)) = self.proxy_parts(object)? else {
5760            return Ok(None);
5761        };
5762        let key_value = self.key_value(key);
5763        let Some(result) = self.proxy_trap(
5764            &handler,
5765            "has",
5766            vec![Value::Object(target.clone()), key_value],
5767        )?
5768        else {
5769            return Ok(Some(self.has_own_or_inherited(&target, key)?));
5770        };
5771        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5772            return Err(self.type_error(format!(
5773                "proxy 'has' denied the non-configurable property '{key}'"
5774            )));
5775        }
5776        // A non-extensible target cannot grow, so every own property it *has* is fixed.
5777        if !result.to_boolean()
5778            && !target.is_extensible()
5779            && Self::ordinary_own_property(&target, key).is_some()
5780        {
5781            return Err(self.type_error(format!(
5782                "proxy 'has' denied the own property '{key}' of a non-extensible target"
5783            )));
5784        }
5785        Ok(Some(result.to_boolean()))
5786    }
5787
5788    /// `[[Delete]]` on a proxy.
5789    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5790        let Some((target, handler)) = self.proxy_parts(object)? else {
5791            return Ok(None);
5792        };
5793        let key_value = self.key_value(key);
5794        let Some(result) = self.proxy_trap(
5795            &handler,
5796            "deleteProperty",
5797            vec![Value::Object(target.clone()), key_value],
5798        )?
5799        else {
5800            return Ok(Some(self.delete_property_key(&target, key)?));
5801        };
5802        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5803            return Err(self.type_error(format!(
5804                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5805            )));
5806        }
5807        if result.to_boolean()
5808            && !target.is_extensible()
5809            && Self::ordinary_own_property(&target, key).is_some()
5810        {
5811            return Err(self.type_error(format!(
5812                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5813            )));
5814        }
5815        Ok(Some(result.to_boolean()))
5816    }
5817
5818    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5819    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5820        let Some((target, handler)) = self.proxy_parts(object)? else {
5821            return Ok(None);
5822        };
5823        let Some(result) =
5824            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5825        else {
5826            // No trap: the target's own keys, already in the order an object reports.
5827            return Ok(Some(self.object_own_property_keys(&target)?));
5828        };
5829        // `CreateListFromArrayLike` with the string-or-symbol restriction.
5830        let list = self.list_from_array_like(&result, true)?;
5831        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5832        for value in list {
5833            let key = self.propkey(&value)?;
5834            if keys.contains(&key) {
5835                return Err(self.type_error(format!(
5836                    "proxy 'ownKeys' returned the duplicate key '{key}'"
5837                )));
5838            }
5839            keys.push(key);
5840        }
5841        for (key, property) in target.property_entries() {
5842            if !property.configurable && !keys.contains(&key) {
5843                return Err(self.type_error(format!(
5844                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5845                )));
5846            }
5847            if !target.is_extensible() && !keys.contains(&key) {
5848                return Err(self.type_error(format!(
5849                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5850                )));
5851            }
5852        }
5853        if !target.is_extensible() {
5854            let own = target.property_entries().len();
5855            if keys.len() != own {
5856                return Err(
5857                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5858                );
5859            }
5860        }
5861        Ok(Some(keys))
5862    }
5863
5864    /// `[[GetOwnProperty]]` on a proxy.
5865    fn proxy_get_own_property(
5866        &mut self,
5867        object: &Gc<JsObject>,
5868        key: &PropertyKey,
5869    ) -> JsResult<Option<Option<Property>>> {
5870        let Some((target, handler)) = self.proxy_parts(object)? else {
5871            return Ok(None);
5872        };
5873        let key_value = self.key_value(key);
5874        let Some(result) = self.proxy_trap(
5875            &handler,
5876            "getOwnPropertyDescriptor",
5877            vec![Value::Object(target.clone()), key_value],
5878        )?
5879        else {
5880            // No trap: the target's own descriptor is the answer. This has to go through
5881            // the same synthesis an ordinary object gets, because a proxy's own property
5882            // table is empty by design — reading it directly reported `undefined` for
5883            // every key, including an array's indices and `length`.
5884            return Ok(Some(Self::ordinary_own_property(&target, key)));
5885        };
5886        let answer = if matches!(result, Value::Undefined) {
5887            None
5888        } else {
5889            Some(self.property_from_descriptor(&result)?)
5890        };
5891        let fixed = Self::is_fixed_property(&target, key);
5892        match (&answer, &fixed) {
5893            // A non-configurable property cannot be reported as absent.
5894            (None, Some(_)) => {
5895                return Err(self.type_error(format!(
5896                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5897                )));
5898            }
5899            (Some(descriptor), Some(fixed)) => {
5900                if descriptor.configurable {
5901                    return Err(self.type_error(format!(
5902                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5903                    )));
5904                }
5905                if fixed.is_accessor() != descriptor.is_accessor() {
5906                    return Err(self.type_error(format!(
5907                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5908                    )));
5909                }
5910                if !fixed.is_accessor() && !fixed.writable {
5911                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5912                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5913                    if !fixed_value.same_value(&reported) {
5914                        return Err(self.type_error(format!(
5915                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5916                        )));
5917                    }
5918                }
5919            }
5920            _ => {}
5921        }
5922        Ok(Some(answer))
5923    }
5924
5925    /// `[[DefineOwnProperty]]` on a proxy.
5926    fn proxy_define_property(
5927        &mut self,
5928        object: &Gc<JsObject>,
5929        key: &PropertyKey,
5930        property: Property,
5931    ) -> JsResult<Option<bool>> {
5932        let Some((target, handler)) = self.proxy_parts(object)? else {
5933            return Ok(None);
5934        };
5935        let key_value = self.key_value(key);
5936        let descriptor = self.descriptor_from_property(&property);
5937        let Some(result) = self.proxy_trap(
5938            &handler,
5939            "defineProperty",
5940            vec![Value::Object(target.clone()), key_value, descriptor],
5941        )?
5942        else {
5943            return Ok(None);
5944        };
5945        if !result.to_boolean() {
5946            return Ok(Some(false));
5947        }
5948        let fixed = Self::is_fixed_property(&target, key);
5949        let creating = Self::ordinary_own_property(&target, key).is_none();
5950        if creating && !target.is_extensible() {
5951            return Err(self.type_error(format!(
5952                "proxy 'defineProperty' added '{key}' to a non-extensible target"
5953            )));
5954        }
5955        if let Some(fixed) = fixed {
5956            if property.configurable {
5957                return Err(self.type_error(format!(
5958                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
5959                )));
5960            }
5961            if !fixed.writable && property.writable && !fixed.is_accessor() {
5962                return Err(self.type_error(format!(
5963                    "proxy 'defineProperty' made the read-only '{key}' writable"
5964                )));
5965            }
5966        }
5967        Ok(Some(true))
5968    }
5969
5970    /// `[[GetPrototypeOf]]` on a proxy.
5971    fn proxy_get_prototype_of(
5972        &mut self,
5973        object: &Gc<JsObject>,
5974    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
5975        let Some((target, handler)) = self.proxy_parts(object)? else {
5976            return Ok(None);
5977        };
5978        let Some(result) = self.proxy_trap(
5979            &handler,
5980            "getPrototypeOf",
5981            vec![Value::Object(target.clone())],
5982        )?
5983        else {
5984            return Ok(Some(target.proto()));
5985        };
5986        let proto = match &result {
5987            Value::Null => None,
5988            Value::Object(proto) => Some(proto.clone()),
5989            _ => {
5990                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
5991            }
5992        };
5993        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
5994            return Err(self.type_error(
5995                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
5996            ));
5997        }
5998        Ok(Some(proto))
5999    }
6000
6001    /// `[[SetPrototypeOf]]` on a proxy.
6002    fn proxy_set_prototype_of(
6003        &mut self,
6004        object: &Gc<JsObject>,
6005        proto: Option<Gc<JsObject>>,
6006    ) -> JsResult<Option<bool>> {
6007        let Some((target, handler)) = self.proxy_parts(object)? else {
6008            return Ok(None);
6009        };
6010        let proto_value = match &proto {
6011            Some(proto) => Value::Object(proto.clone()),
6012            None => Value::Null,
6013        };
6014        let Some(result) = self.proxy_trap(
6015            &handler,
6016            "setPrototypeOf",
6017            vec![Value::Object(target.clone()), proto_value],
6018        )?
6019        else {
6020            target.set_proto(proto);
6021            return Ok(Some(true));
6022        };
6023        if result.to_boolean()
6024            && !target.is_extensible()
6025            && !same_proto(proto.as_ref(), target.proto().as_ref())
6026        {
6027            return Err(self.type_error(
6028                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6029            ));
6030        }
6031        Ok(Some(result.to_boolean()))
6032    }
6033
6034    /// `[[IsExtensible]]` on a proxy.
6035    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6036        let Some((target, handler)) = self.proxy_parts(object)? else {
6037            return Ok(None);
6038        };
6039        let Some(result) = self.proxy_trap(
6040            &handler,
6041            "isExtensible",
6042            vec![Value::Object(target.clone())],
6043        )?
6044        else {
6045            return Ok(Some(target.is_extensible()));
6046        };
6047        // The answer is not the proxy's to invent: it must agree with the target, or a
6048        // script could learn `false` while the target keeps accepting new properties.
6049        if result.to_boolean() != target.is_extensible() {
6050            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6051        }
6052        Ok(Some(result.to_boolean()))
6053    }
6054
6055    /// `[[PreventExtensions]]` on a proxy.
6056    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6057        let Some((target, handler)) = self.proxy_parts(object)? else {
6058            return Ok(None);
6059        };
6060        let Some(result) = self.proxy_trap(
6061            &handler,
6062            "preventExtensions",
6063            vec![Value::Object(target.clone())],
6064        )?
6065        else {
6066            target.set_extensible(false);
6067            return Ok(Some(true));
6068        };
6069        if result.to_boolean() && target.is_extensible() {
6070            return Err(self.type_error(
6071                "proxy 'preventExtensions' reported success but the target is still extensible",
6072            ));
6073        }
6074        Ok(Some(result.to_boolean()))
6075    }
6076
6077    /// `[[Call]]` on a proxy, through the `apply` trap.
6078    fn proxy_apply(
6079        &mut self,
6080        object: &Gc<JsObject>,
6081        this: Value,
6082        args: Vec<Value>,
6083    ) -> JsResult<Option<Value>> {
6084        let Some((target, handler)) = self.proxy_parts(object)? else {
6085            return Ok(None);
6086        };
6087        // The trap gets the arguments as one array, which is the shape the spec passes
6088        // and the shape `apply` traps are written against (`args[0]` is the first one).
6089        let arguments = self.new_array(args.clone());
6090        let this_for_trap = this.clone();
6091        let Some(result) = self.proxy_trap(
6092            &handler,
6093            "apply",
6094            vec![
6095                Value::Object(target.clone()),
6096                this_for_trap,
6097                Value::Object(arguments),
6098            ],
6099        )?
6100        else {
6101            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6102        };
6103        Ok(Some(result))
6104    }
6105
6106    /// `[[Construct]]` on a proxy, through the `construct` trap.
6107    fn proxy_construct(
6108        &mut self,
6109        object: &Gc<JsObject>,
6110        args: Vec<Value>,
6111        new_target: &Value,
6112    ) -> JsResult<Option<Value>> {
6113        let Some((target, handler)) = self.proxy_parts(object)? else {
6114            return Ok(None);
6115        };
6116        if !target.is_callable() {
6117            return Err(self.type_error("proxy target is not a constructor"));
6118        }
6119        let arguments = self.new_array(args.clone());
6120        let Some(result) = self.proxy_trap(
6121            &handler,
6122            "construct",
6123            vec![
6124                Value::Object(target.clone()),
6125                Value::Object(arguments),
6126                new_target.clone(),
6127            ],
6128        )?
6129        else {
6130            return Ok(Some(self.construct(
6131                Value::Object(target),
6132                new_target.clone(),
6133                args,
6134            )?));
6135        };
6136        if !matches!(result, Value::Object(_)) {
6137            return Err(self.type_error("proxy 'construct' must return an object"));
6138        }
6139        Ok(Some(result))
6140    }
6141
6142    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6143    pub(crate) fn has_own_or_inherited(
6144        &mut self,
6145        object: &Gc<JsObject>,
6146        key: &PropertyKey,
6147    ) -> JsResult<bool> {
6148        // The object itself first: it may be a proxy, and then the answer is its trap's.
6149        if let Some(answer) = self.proxy_has(object, key)? {
6150            return Ok(answer);
6151        }
6152        // An integer-indexed exotic object answers a canonical numeric index from
6153        // `IsValidIntegerIndex` alone (§10.4.5.4 step 1.b.i) — **without** walking the
6154        // prototype chain. That is observable: a view the buffer has been resized away from
6155        // has no indices, so `2 in view` is `false` even when
6156        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
6157        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
6158        // The `[[HasProperty]]` that `in` compiles to goes through here, which is why the
6159        // same rule is repeated in `has_property_key` rather than living only there.
6160        if object.typed_array_parts().is_some()
6161            && let Some(index) = key.as_str().and_then(array_index)
6162        {
6163            return Ok(object
6164                .typed_array_length()
6165                .is_some_and(|length| (index as usize) < length));
6166        }
6167        // A host class answers `in` for its own keys, which may live nowhere in a property
6168        // table — `"x" in point` is true because the class says so, not because a property
6169        // exists.
6170        if let Some(exotic) = object.exotic()
6171            && let Some(answer) = exotic.has_property(self, object, key)?
6172        {
6173            return Ok(answer);
6174        }
6175        // `has_own` rather than `own_property_key`: an array's elements and its derived
6176        // `length` are invisible to the property table, and `Array.prototype` is an array.
6177        // A host class's `get_own_property` counts too, because the reference's
6178        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6179        // lives — a class with only `get_own_property` answers `in` through it.
6180        if self.exotic_has_own(object, key)? {
6181            return Ok(true);
6182        }
6183        // A hole is *not* the end of the search: the chain may still have the key, which
6184        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6185        for ancestor in object.chain() {
6186            // A proxy further up the chain answers for itself.
6187            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6188                return Ok(answer);
6189            }
6190            // Same for a host class: a prototype may be one, and `in` reaches it.
6191            if let Some(exotic) = ancestor.exotic()
6192                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6193            {
6194                return Ok(answer);
6195            }
6196            if self.exotic_has_own(&ancestor, key)? {
6197                return Ok(true);
6198            }
6199        }
6200        Ok(false)
6201    }
6202
6203    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6204    /// trap included.
6205    ///
6206    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6207    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6208    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6209        if let Some(exotic) = object.exotic()
6210            && let Some(answer) = exotic.get_own_property(self, object, key)?
6211        {
6212            return Ok(answer.is_some());
6213        }
6214        Ok(has_own(object, key))
6215    }
6216
6217    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6218    ///
6219    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6220    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6221    /// `TypeError` instead of a property named `"1.5"`.
6222    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6223        let object = self.object_from(value)?;
6224        let length = self
6225            .get_property(&object, "length")?
6226            .map(|value| value.to_number())
6227            .unwrap_or(0.0);
6228        if !length.is_finite() || length < 0.0 {
6229            return Err(self.type_error("invalid array-like length"));
6230        }
6231        let length = length as usize;
6232        let mut items = Vec::with_capacity(length.min(1024));
6233        for index in 0..length {
6234            let item = self
6235                .get_property(&object, &index.to_string())?
6236                .unwrap_or(Value::Undefined);
6237            if keys_only && matches!(&item, Value::Symbol(_)) {
6238                items.push(item);
6239                continue;
6240            }
6241            if keys_only && !matches!(&item, Value::String(_)) {
6242                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6243            }
6244            items.push(item);
6245        }
6246        Ok(items)
6247    }
6248
6249    /// A `Property` from the descriptor object a trap returned.
6250    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6251        let object = self.object_from(value)?;
6252        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6253            interp.get_property(&object, name)
6254        };
6255        let getter = field(self, "get")?;
6256        let setter = field(self, "set")?;
6257        let accessor = getter.is_some() || setter.is_some();
6258        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6259            Ok(interp
6260                .get_property(&object, name)?
6261                .is_some_and(|value| value.to_boolean()))
6262        };
6263        let enumerable = boolean(self, "enumerable")?;
6264        let configurable = boolean(self, "configurable")?;
6265        if accessor {
6266            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6267                return Err(
6268                    self.type_error("a descriptor cannot be both a data property and an accessor")
6269                );
6270            }
6271            Ok(Property {
6272                getter: getter.or(Some(Value::Undefined)),
6273                setter: setter.or(Some(Value::Undefined)),
6274                enumerable,
6275                configurable,
6276                writable: false,
6277                value: None,
6278            })
6279        } else {
6280            Ok(Property {
6281                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6282                writable: boolean(self, "writable")?,
6283                enumerable,
6284                configurable,
6285                getter: None,
6286                setter: None,
6287            })
6288        }
6289    }
6290
6291    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6292    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6293        let object = self.new_object(None);
6294        if property.is_accessor() {
6295            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6296            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6297            object.define_data("get", getter);
6298            object.define_data("set", setter);
6299        } else {
6300            let value = property.value.clone().unwrap_or(Value::Undefined);
6301            object.define_data("value", value);
6302            object.define_data("writable", Value::Bool(property.writable));
6303        }
6304        object.define_data("enumerable", Value::Bool(property.enumerable));
6305        object.define_data("configurable", Value::Bool(property.configurable));
6306        Value::Object(object)
6307    }
6308
6309    // -- calling ------------------------------------------------------------
6310
6311    /// Call `callee` with `this` and `args`.
6312    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6313        let Value::Object(function) = &callee else {
6314            // `typeof x === "function"` is not enough to make `x()` legal: only a
6315            // callable object is. `null` and `undefined` need no special wording
6316            // here — their `ToString` already reads the way the reference's does.
6317            let what = format!("{} is not a function", callee.to_js_string());
6318            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6319        };
6320        // A proxy of a function is called through its `apply` trap. It has no
6321        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6322        // below, and a proxy of a non-function has nothing to forward to.
6323        if function.proxy_state().is_some() {
6324            return match self.proxy_apply(function, this, args)? {
6325                Some(result) => Ok(result),
6326                None => Err(Signal::Throw(
6327                    self.make_error("TypeError", "proxy target is not callable"),
6328                )),
6329            };
6330        }
6331        let callable = function.with(|data| match &data.kind {
6332            ObjectKind::Function(callable) => match callable {
6333                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6334                // The `Rc` is cloned out so the borrow of this object's data is released
6335                // before the closure runs: the closure may touch the same object.
6336                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6337                Callable::Bound {
6338                    target,
6339                    this,
6340                    args: leading,
6341                } => Some(NativeCall::Bound {
6342                    target: target.clone(),
6343                    this: this.clone(),
6344                    leading: leading.clone(),
6345                }),
6346                Callable::Bytecode { code, env } => {
6347                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
6348                }
6349                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6350                Callable::PromiseResolve(promise) => {
6351                    Some(NativeCall::PromiseResolve(promise.clone()))
6352                }
6353                Callable::PromiseReject(promise) => {
6354                    Some(NativeCall::PromiseReject(promise.clone()))
6355                }
6356                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6357                    state: state.clone(),
6358                }),
6359                Callable::ThenShim {
6360                    handler,
6361                    resolve,
6362                    reject,
6363                    fulfilled,
6364                } => Some(NativeCall::ThenShim {
6365                    handler: handler.clone(),
6366                    resolve: resolve.clone(),
6367                    reject: reject.clone(),
6368                    fulfilled: *fulfilled,
6369                }),
6370                Callable::AwaitResume {
6371                    coroutine,
6372                    promise,
6373                    kind,
6374                } => Some(NativeCall::AwaitResume {
6375                    coroutine: coroutine.clone(),
6376                    promise: promise.clone(),
6377                    kind: *kind,
6378                }),
6379                Callable::CombinatorSettle {
6380                    state,
6381                    index,
6382                    fulfilled,
6383                } => Some(NativeCall::CombinatorSettle {
6384                    state: state.clone(),
6385                    index: *index,
6386                    fulfilled: *fulfilled,
6387                }),
6388                Callable::FinallyShim {
6389                    callback,
6390                    fulfilled,
6391                    constructor,
6392                } => Some(NativeCall::FinallyShim {
6393                    callback: callback.clone(),
6394                    fulfilled: *fulfilled,
6395                    constructor: constructor.clone(),
6396                }),
6397                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6398                Callable::CompletedReturn {
6399                    generator,
6400                    promise,
6401                    rejected,
6402                } => Some(NativeCall::CompletedReturn {
6403                    generator: generator.clone(),
6404                    promise: promise.clone(),
6405                    rejected: *rejected,
6406                }),
6407                Callable::YieldResult {
6408                    generator,
6409                    promise,
6410                    done,
6411                } => Some(NativeCall::YieldResult {
6412                    generator: generator.clone(),
6413                    promise: promise.clone(),
6414                    done: *done,
6415                }),
6416                Callable::DisposeStep {
6417                    remaining,
6418                    promise,
6419                    error,
6420                    rejected,
6421                } => Some(NativeCall::DisposeStep {
6422                    remaining: remaining.clone(),
6423                    promise: promise.clone(),
6424                    error: error.clone(),
6425                    rejected: *rejected,
6426                }),
6427                Callable::GeneratorResume {
6428                    generator,
6429                    promise,
6430                    kind,
6431                } => Some(NativeCall::GeneratorResume {
6432                    generator: generator.clone(),
6433                    promise: promise.clone(),
6434                    kind: *kind,
6435                }),
6436                Callable::SettlePromise {
6437                    promise,
6438                    value,
6439                    rejected,
6440                } => Some(NativeCall::SettlePromise {
6441                    promise: promise.clone(),
6442                    value: value.clone(),
6443                    rejected: *rejected,
6444                }),
6445            },
6446            _ => None,
6447        });
6448        match callable {
6449            Some(NativeCall::Host(func)) => {
6450                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6451                // function by name rather than stopping at the caller.
6452                let frame_less = function
6453                    .own_property("_frame_less")
6454                    .and_then(|property| property.value)
6455                    .is_some_and(|value| value.to_boolean());
6456                let outer = if frame_less {
6457                    None
6458                } else {
6459                    self.native_frames
6460                        .push((function.clone(), self.frames.len()));
6461                    Some(self.current_native.replace(function.clone()))
6462                };
6463                let result = {
6464                    let mut body = func.borrow_mut();
6465                    body(self, this, &args)
6466                };
6467                if !frame_less {
6468                    self.native_frames.pop();
6469                    self.current_native = outer.flatten();
6470                }
6471                result
6472            }
6473            Some(NativeCall::Native(func)) => {
6474                // A function marked `_frame_less` is one the reference implements
6475                // without a call frame — `eval` is the only one so far.
6476                let frame_less = function
6477                    .own_property("_frame_less")
6478                    .and_then(|property| property.value)
6479                    .is_some_and(|value| value.to_boolean());
6480                let outer = if frame_less {
6481                    None
6482                } else {
6483                    self.native_frames
6484                        .push((function.clone(), self.frames.len()));
6485                    Some(self.current_native.replace(function.clone()))
6486                };
6487                let result = func(self, this, &args);
6488                if !frame_less {
6489                    self.native_frames.pop();
6490                    self.current_native = outer.flatten();
6491                }
6492                result
6493            }
6494            Some(NativeCall::Revoker(slots)) => {
6495                // Idempotent: revoking twice answers `undefined` again rather than
6496                // complaining, which is what the spec says and what a `finally` block
6497                // relies on.
6498                let mut state = slots.borrow_mut();
6499                state.target = None;
6500                state.handler = None;
6501                Ok(Value::Undefined)
6502            }
6503            Some(NativeCall::PromiseResolve(promise)) => {
6504                // One-shot: a second call is silently ignored, which
6505                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6506                let value = args.first().cloned().unwrap_or(Value::Undefined);
6507                self.resolve_promise_with(&promise, value)?;
6508                Ok(Value::Undefined)
6509            }
6510            Some(NativeCall::PromiseReject(promise)) => {
6511                let reason = args.first().cloned().unwrap_or(Value::Undefined);
6512                self.reject_promise(&promise, reason);
6513                Ok(Value::Undefined)
6514            }
6515            Some(NativeCall::ThenShim {
6516                handler,
6517                resolve,
6518                reject,
6519                fulfilled,
6520            }) => {
6521                // `PerformPromiseThen` with a capability: run the handler, then settle
6522                // through the capability's own pair. A throw from the handler is the
6523                // rejection, and a throw from the capability's `resolve` is not caught —
6524                // exactly the spec's `?`.
6525                let value = args.first().cloned().unwrap_or(Value::Undefined);
6526                match handler {
6527                    Some(handler) => {
6528                        match self.call_value(handler, Value::Undefined, vec![value]) {
6529                            Ok(result) => {
6530                                self.call_value(resolve, Value::Undefined, vec![result])?;
6531                            }
6532                            Err(Signal::Throw(reason)) => {
6533                                self.call_value(reject, Value::Undefined, vec![reason])?;
6534                            }
6535                            Err(signal) => return Err(signal),
6536                        }
6537                    }
6538                    None => {
6539                        let handler = if fulfilled { resolve } else { reject };
6540                        self.call_value(handler, Value::Undefined, vec![value])?;
6541                    }
6542                }
6543                Ok(Value::Undefined)
6544            }
6545            Some(NativeCall::CapabilityExecutor { state }) => {
6546                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6547                // slot holds a value yet. The test is on the *values*, not on a call count —
6548                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6549                // called-twice`'s first case does exactly that), while a second call after a
6550                // real pair is the `TypeError`.
6551                let defined = |name: &str| {
6552                    state
6553                        .own_property(name)
6554                        .and_then(|property| property.value)
6555                        .is_some_and(|value| !matches!(value, Value::Undefined))
6556                };
6557                if defined("resolve") || defined("reject") {
6558                    return Err(self.type_error("promise capability executor called twice"));
6559                }
6560                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6561                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6562                state.define_data("resolve", resolve);
6563                state.define_data("reject", reject);
6564                Ok(Value::Undefined)
6565            }
6566            Some(NativeCall::CombinatorSettle {
6567                state,
6568                index,
6569                fulfilled,
6570            }) => {
6571                let value = args.first().cloned().unwrap_or(Value::Undefined);
6572                self.settle_combinator(&state, index, fulfilled, value)?;
6573                Ok(Value::Undefined)
6574            }
6575            Some(NativeCall::AwaitResume {
6576                coroutine,
6577                promise,
6578                kind,
6579            }) => {
6580                // Resume *inline*, in the reaction that delivered the value. Deferring it
6581                // by another job inserts a tick between every `await` and its
6582                // continuation, which reorders `await` against unrelated `then` chains —
6583                // `f().then(g)` then runs before `f`'s own next statement.
6584                self.drive_async(
6585                    &coroutine,
6586                    &promise,
6587                    kind,
6588                    args.first().cloned().unwrap_or(Value::Undefined),
6589                )
6590                .map(|()| Value::Undefined)
6591            }
6592            Some(NativeCall::FinallyShim {
6593                callback,
6594                fulfilled,
6595                constructor,
6596            }) => {
6597                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6598                // that settles with the *original* outcome once the callback's result has
6599                // settled. The callback's own value is discarded — that is the whole
6600                // difference between `finally` and `then`.
6601                let original = args.first().cloned().unwrap_or(Value::Undefined);
6602                let result = match &callback {
6603                    Some(callback) => {
6604                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6605                    }
6606                    None => Value::Undefined,
6607                };
6608                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6609                // already a promise of this constructor is reused rather than rewrapped.
6610                let resolved = self.promise_resolve_for(&constructor, result)?;
6611                let Value::Object(resolved) = resolved else {
6612                    return Ok(original);
6613                };
6614                // The wait is a chained promise rather than a bare return, so a callback
6615                // that returns a slow promise really does delay the continuation.
6616                let waiting = self.new_promise();
6617                let pass = JsObject::function(
6618                    self.heap,
6619                    Some(self.realm.function_proto.clone()),
6620                    Callable::SettlePromise {
6621                        promise: waiting.clone(),
6622                        value: original,
6623                        rejected: !fulfilled,
6624                    },
6625                );
6626                let pass = Value::Object(pass);
6627                // Whichever way the callback's promise settles, the original outcome wins.
6628                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6629                Ok(Value::Object(waiting))
6630            }
6631            Some(NativeCall::DisposeStep {
6632                remaining,
6633                promise,
6634                error,
6635                rejected,
6636            }) => {
6637                let error = if rejected {
6638                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
6639                    self.merge_dispose_error(reason, error)
6640                } else {
6641                    error
6642                };
6643                self.dispose_step(&remaining, &promise, error)?;
6644                Ok(Value::Undefined)
6645            }
6646            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6647            Some(NativeCall::CompletedReturn {
6648                generator,
6649                promise,
6650                rejected,
6651            }) => {
6652                let value = args.first().cloned().unwrap_or(Value::Undefined);
6653                let outcome = if rejected {
6654                    AsyncOutcome::Error(value)
6655                } else {
6656                    AsyncOutcome::Value(self.iterator_result(value, true)?)
6657                };
6658                self.settle_async_request(&generator, &promise, outcome)?;
6659                Ok(Value::Undefined)
6660            }
6661            Some(NativeCall::YieldResult {
6662                generator,
6663                promise,
6664                done,
6665            }) => {
6666                let value = args.first().cloned().unwrap_or(Value::Undefined);
6667                let result = self.iterator_result(value, done)?;
6668                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6669                Ok(Value::Undefined)
6670            }
6671            Some(NativeCall::GeneratorResume {
6672                generator,
6673                promise,
6674                kind,
6675            }) => {
6676                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6677                // tick and reorders the generator against other chains.
6678                self.step_async_generator(
6679                    &generator,
6680                    &promise,
6681                    kind,
6682                    args.first().cloned().unwrap_or(Value::Undefined),
6683                )
6684                .map(|()| Value::Undefined)
6685            }
6686            Some(NativeCall::SettlePromise {
6687                promise,
6688                value,
6689                rejected,
6690            }) => {
6691                if rejected {
6692                    self.reject_promise(&promise, value);
6693                } else {
6694                    self.fulfill_promise(&promise, value);
6695                }
6696                Ok(Value::Undefined)
6697            }
6698            Some(NativeCall::Bound {
6699                target,
6700                this: bound_this,
6701                leading,
6702            }) => {
6703                let mut all = leading;
6704                all.extend(args);
6705                self.call_value(target, bound_this, all)
6706            }
6707            Some(NativeCall::Bytecode(code, env)) => {
6708                if code.code.kind.is_generator() {
6709                    return self.new_generator(callee, this, args);
6710                }
6711                if code.code.kind.is_async() {
6712                    // Same coroutine machinery as a generator; the difference is only in
6713                    // what the completion does — see `new_async_function`.
6714                    return self.new_async_function(callee, this, args);
6715                }
6716                self.execute(code, env, this, args, callee)
6717            }
6718            None => Err(Signal::Throw(
6719                self.make_error("TypeError", "not a function"),
6720            )),
6721        }
6722    }
6723
6724    /// Give a freshly built function its own `prototype` object.
6725    ///
6726    /// Every function that can be used with `new` carries one, and its
6727    /// `constructor` points back at the function — a reference cycle, which is
6728    /// exactly what the collector's cycle pass exists to reclaim.
6729    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6730        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6731        let constructor = Value::Object(function.clone());
6732        prototype.define(
6733            "constructor",
6734            Property::with_attributes(constructor, true, false),
6735        );
6736        let value = Value::Object(prototype);
6737        function.define("prototype", Property::prototype_of(value, true));
6738    }
6739
6740    /// The object `special_object` builds.
6741    ///
6742    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6743    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6744    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6745    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6746    /// write through `arguments` does not reach the parameter.
6747    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6748        match magic {
6749            0 | 1 => {
6750                let args = self.frame().passed().to_vec();
6751                let proto = self.realm.object_proto.clone();
6752                let object = self.new_object(Some(proto));
6753                // The marker `Object.prototype.toString` needs: an arguments object is an
6754                // ordinary object apart from reporting `[object Arguments]`, and that has
6755                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6756                // show up ahead of them in a key listing anyway — it is non-enumerable.
6757                self.internal_set(&object, "_class", self.string("Arguments"));
6758                // `length` is writable and configurable but neither enumerable nor a
6759                // plain data property: `Object.keys(arguments)` lists the indices only,
6760                // which is how `{...arguments}` copies them without the length.
6761                object.define(
6762                    "length",
6763                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
6764                );
6765                for (index, value) in args.into_iter().enumerate() {
6766                    object.define_data(&index.to_string(), value);
6767                }
6768                // An arguments object is iterable: `[...arguments]` and
6769                // `for (const a of arguments)` both work, through the *array* iterator
6770                // because the object is array-like. Without this the whole spread form
6771                // reported "not iterable".
6772                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6773                let values = self
6774                    .realm
6775                    .array_proto
6776                    .own_property("values")
6777                    .and_then(|property| property.value);
6778                if let Some(values) = values {
6779                    object.define_key(
6780                        &iterator_key,
6781                        Property::with_attributes(values, true, false),
6782                    );
6783                }
6784                Ok(Value::Object(object))
6785            }
6786            // `this.active_func`: the constructor `super()` resolves against.
6787            //
6788            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
6789            // own, so it inherits this from the function it was written in along with `this`
6790            // — and that is a lexical relationship, not a stack one: an arrow that escaped
6791            // the constructor and is called back later (`iter.return = () => super()`) has
6792            // the constructor nowhere on the stack. The compiler therefore reads it out of
6793            // a closure variable of the enclosing function, exactly as the reference does
6794            // with its `this_active_func` local.
6795            2 => Ok(self
6796                .current_callee()
6797                .map_or(Value::Undefined, Value::Object)),
6798            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6799            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6800            // its own either, so the lookup walks out to the nearest non-arrow frame for
6801            // the same reason as `this.active_func` above — without that, `super()` inside
6802            // an arrow passed `undefined` as the new target and the parent constructor was
6803            // then rejected for being invoked without `new`.
6804            3 => Ok(self
6805                .eval_new_target
6806                .clone()
6807                .unwrap_or_else(|| self.frame().new_target.clone())),
6808            // `[[HomeObject]]` of the function being run: what `super` is relative to.
6809            // An arrow has none of its own, so the lookup walks out to the enclosing
6810            // method — which is why `super` works inside an arrow inside a method.
6811            4 => Ok(self
6812                .frames
6813                .iter()
6814                .rev()
6815                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6816                .map_or(Value::Undefined, Value::Object)),
6817            // `import.meta`: the innermost module body's meta object. Outside a module
6818            // the compiler never emits this, so an empty fallback is unreachable rather
6819            // than permissive.
6820            6 => {
6821                let name = self.module_stack.last().cloned();
6822                let meta = name
6823                    .and_then(|name| self.modules.get(&name).cloned())
6824                    .and_then(|module| module.with(|r| r.import_meta.clone()));
6825                Ok(meta.map_or(Value::Undefined, Value::Object))
6826            }
6827            other => Err(Signal::Throw(self.make_error(
6828                "InternalError",
6829                &format!("special_object {other} is not implemented yet"),
6830            ))),
6831        }
6832    }
6833
6834    /// `[[HomeObject]]` of the innermost function that has one, if any.
6835    ///
6836    /// An arrow has none, so the search walks out to the enclosing method — the same
6837    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
6838    /// inside a method.
6839    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
6840        self.frames
6841            .iter()
6842            .rev()
6843            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6844    }
6845
6846    /// The dispose method a `using` declaration should snapshot, or an error.
6847    ///
6848    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
6849    /// is what makes a resource that only knows the synchronous protocol usable in both
6850    /// forms.
6851    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
6852        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
6853        if value.is_nullish() {
6854            return Ok(Value::Undefined);
6855        }
6856        let Some(object) = value.as_object() else {
6857            return Err(self.type_error("not an object"));
6858        };
6859        let mut method = if await_form {
6860            let found = self.get_property_key(
6861                object,
6862                &self.realm.well_known_key(WellKnown::AsyncDisposable),
6863            )?;
6864            match found {
6865                Some(found) if !found.is_nullish() => Some(found),
6866                _ => self
6867                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
6868            }
6869        } else {
6870            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
6871        };
6872        let Some(found) = method.take() else {
6873            return Err(self.type_error("value is not disposable"));
6874        };
6875        if found.is_nullish() {
6876            return Err(self.type_error("value is not disposable"));
6877        }
6878        let callable = found.as_object().is_some_and(|object| object.is_callable());
6879        if !callable {
6880            return Err(self.type_error("dispose method is not a function"));
6881        }
6882        Ok(found)
6883    }
6884
6885    /// Call one resource's disposer, folding a failure into `error_state`.
6886    ///
6887    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
6888    /// because a captured `using` binding lives in its reference cell and the local slot is
6889    /// stale — a closure over the resource is legal and must not change what is disposed.
6890    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
6891        let value = self.get_loc(slot);
6892        let method = self.get_loc(slot + 1);
6893        // A resource that was never initialised — its declaration threw — or that is
6894        // `null`/`undefined` has nothing to dispose.
6895        if value.is_nullish() || matches!(value, Value::Uninitialized) {
6896            return Ok(error_state);
6897        }
6898        if matches!(method, Value::Undefined | Value::Uninitialized) {
6899            return Ok(error_state);
6900        }
6901        match self.call_value(method, value, Vec::new()) {
6902            Ok(_) => Ok(error_state),
6903            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
6904            Err(other) => Err(other),
6905        }
6906    }
6907
6908    /// Combine a disposal failure with whatever was already going wrong.
6909    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
6910        if matches!(error_state, Value::Uninitialized) {
6911            return new_error;
6912        }
6913        self.new_suppressed_error(new_error, error_state)
6914    }
6915
6916    /// A `SuppressedError` instance built straight from its prototype.
6917    ///
6918    /// Not through the constructor: a script that rewrites
6919    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
6920    /// error wrapping.
6921    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
6922        let proto = self
6923            .realm
6924            .suppressed_error_proto
6925            .clone()
6926            .unwrap_or_else(|| self.realm.error_proto.clone());
6927        let object = self.new_object(Some(proto));
6928        object.define("error", Property::with_attributes(error, true, true));
6929        object.define(
6930            "suppressed",
6931            Property::with_attributes(suppressed, true, true),
6932        );
6933        object.define(
6934            "message",
6935            Property::with_attributes(self.string("SuppressedError"), true, true),
6936        );
6937        self.internal_set(&object, "_class", self.string("Error"));
6938        self.add_stack(&object);
6939        Value::Object(object)
6940    }
6941
6942    /// Call `callee`, or push its frame and let the main loop run it.
6943    ///
6944    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
6945    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
6946    /// continues, so `function f(){ return f() }` costs heap and stops at
6947    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
6948    /// is entered directly, and natives do not re-enter JavaScript in this
6949    /// milestone.
6950    ///
6951    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
6952    /// because the returning frame will.
6953    /// The elements of an array-like value, as a call argument list.
6954    ///
6955    /// `apply` accepts any array-like, not only a real array: the reference reads
6956    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
6957    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
6958        let Some(object) = value.as_object().cloned() else {
6959            if value.is_nullish() {
6960                // `f.apply(this, null)` passes no arguments at all.
6961                return Ok(Vec::new());
6962            }
6963            return Err(self.type_error("createListFromArrayLike called on non-object"));
6964        };
6965        let length = match self.get_property(&object, "length")? {
6966            Some(length) => length.to_number(),
6967            None => 0.0,
6968        };
6969        if !length.is_finite() || length <= 0.0 {
6970            return Ok(Vec::new());
6971        }
6972        let length = (length as usize).min(1_000_000);
6973        let mut args = Vec::with_capacity(length);
6974        for index in 0..length {
6975            let element = self.get_property(&object, &index.to_string())?;
6976            args.push(element.unwrap_or(Value::Undefined));
6977        }
6978        Ok(args)
6979    }
6980
6981    /// Turn a call to a generator function into a generator object.
6982    ///
6983    /// The frame is built exactly as an ordinary call would build it, then detached and
6984    /// stored in the generator before any body instruction runs — which is what makes
6985    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
6986    /// is `initial_yield`, the first instruction of every suspending body.
6987    pub fn new_generator(
6988        &mut self,
6989        function: Value,
6990        this: Value,
6991        args: Vec<Value>,
6992    ) -> JsResult<Value> {
6993        let Some(object) = function.as_object().cloned() else {
6994            return Err(self.type_error("not a generator function"));
6995        };
6996        let Some((code, env)) = bytecode_of(&object) else {
6997            return Err(self.type_error("not a generator function"));
6998        };
6999        let is_async = code.code.kind.is_async();
7000        self.push_frame(code, env, this, args, function)?;
7001        let frame = self.frames.pop().expect("push_frame just pushed it");
7002        // A fresh generator is *suspended at start*: the body has not run, so a
7003        // `return`/`throw` on it finishes without executing anything.
7004        let mut state = GeneratorState {
7005            frame: Some(frame),
7006            phase: GeneratorPhase::SuspendedStart,
7007            parked_on_await: false,
7008            parked_on_yield_star: false,
7009            requests: std::collections::VecDeque::new(),
7010            async_busy: false,
7011        };
7012        // Run to the first suspension. For a generator that is `initial_yield`, so no
7013        // body code runs; for a malformed body it would be the first `yield`.
7014        // An `async function*` answers an async generator: same coroutine, but its
7015        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7016        let proto = if is_async {
7017            self.realm
7018                .async_generator_proto
7019                .clone()
7020                .unwrap_or_else(|| self.realm.generator_proto.clone())
7021        } else {
7022            self.realm.generator_proto.clone()
7023        };
7024        let generator = self.new_object(Some(proto));
7025        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7026            Ok(_) => {}
7027            Err(error) => return Err(error),
7028        }
7029        generator.with_mut(|data| {
7030            data.kind = ObjectKind::Generator(Box::new(state));
7031        });
7032        Ok(Value::Object(generator))
7033    }
7034
7035    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7036    ///
7037    /// Returns the `{value, done}` object itself rather than the pair, because a
7038    /// `yield*` suspension already has one — the inner iterator's own result — and the
7039    /// protocol says to hand that straight through rather than nest it.
7040    /// Advance a generator and report *why* it parked.
7041    ///
7042    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7043    /// "hand this value to the caller" — but an async generator does: an `await` has to
7044    /// settle before it can answer, while a `yield` is the answer.
7045    fn resume_generator_detailed(
7046        &mut self,
7047        generator: &Gc<JsObject>,
7048        kind: ResumeKind,
7049        value: Value,
7050    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7051        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7052            ObjectKind::Generator(state) => Some(std::mem::replace(
7053                state.as_mut(),
7054                GeneratorState {
7055                    frame: None,
7056                    phase: GeneratorPhase::Executing,
7057                    parked_on_await: false,
7058                    parked_on_yield_star: false,
7059                    requests: std::collections::VecDeque::new(),
7060                    async_busy: false,
7061                },
7062            )),
7063            _ => None,
7064        }) else {
7065            return Err(self.type_error("not a generator"));
7066        };
7067        let result = self.step_generator(&mut state, kind, value);
7068        generator.with_mut(|data| {
7069            data.kind = ObjectKind::Generator(Box::new(state));
7070        });
7071        result
7072    }
7073
7074    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7075    ///
7076    /// Returns the `{value, done}` object itself rather than the pair, because a
7077    /// `yield*` suspension already has one — the inner iterator's own result — and the
7078    /// protocol says to hand that straight through rather than nest it.
7079    pub fn resume_generator(
7080        &mut self,
7081        generator: &Gc<JsObject>,
7082        kind: ResumeKind,
7083        value: Value,
7084    ) -> JsResult<Value> {
7085        let (value, done, ready, _reason) =
7086            self.resume_generator_detailed(generator, kind, value)?;
7087        if ready {
7088            return Ok(value);
7089        }
7090        self.iterator_result(value, done)
7091    }
7092
7093    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7094    ///
7095    /// The body is the same coroutine a sync generator runs; what changes is that an
7096    /// `await` inside it has to settle before the method can answer, so the step is
7097    /// driven off the job queue rather than returning inline.
7098    pub fn resume_async_generator(
7099        &mut self,
7100        generator: &Gc<JsObject>,
7101        kind: ResumeKind,
7102        value: Value,
7103    ) -> JsResult<Value> {
7104        let promise = self.new_promise();
7105        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7106        // that order, and the second value must reach the *second* `yield`.
7107        let idle = generator.with_mut(|data| match &mut data.kind {
7108            ObjectKind::Generator(state) => {
7109                state.requests.push_back(AsyncRequest {
7110                    kind,
7111                    value,
7112                    promise: promise.clone(),
7113                });
7114                !state.async_busy
7115            }
7116            _ => false,
7117        });
7118        if idle {
7119            self.next_async_request(generator)?;
7120        }
7121        Ok(Value::Object(promise))
7122    }
7123
7124    /// Serve the front queued request, if the generator is free to run one.
7125    ///
7126    /// A finished generator answers from the queue without running anything:
7127    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7128    /// first, and `throw(e)` rejects.
7129    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7130        enum Front {
7131            Idle,
7132            Run(ResumeKind, Value, Gc<JsObject>),
7133            Finished(ResumeKind, Value, Gc<JsObject>),
7134        }
7135        let front = generator.with_mut(|data| match &mut data.kind {
7136            ObjectKind::Generator(state) => {
7137                let Some(request) = state.requests.front() else {
7138                    return Front::Idle;
7139                };
7140                // Busy means a request is still in flight — awaiting inside the body, not
7141                // finished. Serving another now would interleave two requests.
7142                if state.async_busy && state.phase != GeneratorPhase::Completed {
7143                    return Front::Idle;
7144                }
7145                let kind = request.kind;
7146                let value = request.value.clone();
7147                let promise = request.promise.clone();
7148                state.async_busy = true;
7149                if state.phase == GeneratorPhase::Completed {
7150                    Front::Finished(kind, value, promise)
7151                } else {
7152                    Front::Run(kind, value, promise)
7153                }
7154            }
7155            _ => Front::Idle,
7156        });
7157        match front {
7158            Front::Idle => Ok(()),
7159            Front::Run(kind, value, promise) => {
7160                self.step_async_generator(generator, &promise, kind, value)
7161            }
7162            Front::Finished(kind, value, promise) => match kind {
7163                ResumeKind::Throw => {
7164                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7165                }
7166                ResumeKind::Next | ResumeKind::Start => {
7167                    let result = self.iterator_result(Value::Undefined, true)?;
7168                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7169                }
7170                ResumeKind::Return => {
7171                    // `js_async_generator_completed_return`: the value is awaited before it
7172                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7173                    // finished generator answers `1`, not a promise.
7174                    let resolved = match self.promise_resolve_value(value) {
7175                        Ok(resolved) => resolved,
7176                        Err(Signal::Throw(reason)) => {
7177                            return self.settle_async_request(
7178                                generator,
7179                                &promise,
7180                                AsyncOutcome::Error(reason),
7181                            );
7182                        }
7183                        Err(other) => return Err(other),
7184                    };
7185                    let done = JsObject::function(
7186                        self.heap,
7187                        Some(self.realm.function_proto.clone()),
7188                        Callable::CompletedReturn {
7189                            generator: generator.clone(),
7190                            promise: promise.clone(),
7191                            rejected: false,
7192                        },
7193                    );
7194                    let failed = JsObject::function(
7195                        self.heap,
7196                        Some(self.realm.function_proto.clone()),
7197                        Callable::CompletedReturn {
7198                            generator: generator.clone(),
7199                            promise: promise.clone(),
7200                            rejected: true,
7201                        },
7202                    );
7203                    let Value::Object(resolved) = resolved else {
7204                        return self.settle_async_request(
7205                            generator,
7206                            &promise,
7207                            AsyncOutcome::Error(Value::Undefined),
7208                        );
7209                    };
7210                    self.perform_then(
7211                        &resolved,
7212                        Some(Value::Object(done)),
7213                        Some(Value::Object(failed)),
7214                    )?;
7215                    Ok(())
7216                }
7217            },
7218        }
7219    }
7220
7221    /// Settle the front request and start the next one.
7222    ///
7223    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7224    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7225    /// generator would strand every later request.
7226    fn settle_async_request(
7227        &mut self,
7228        generator: &Gc<JsObject>,
7229        promise: &Gc<JsObject>,
7230        outcome: AsyncOutcome,
7231    ) -> JsResult<()> {
7232        let settled = generator.with_mut(|data| match &mut data.kind {
7233            ObjectKind::Generator(state) => {
7234                let front = state.requests.front();
7235                debug_assert!(
7236                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7237                    "a request settled outside its turn"
7238                );
7239                state.requests.pop_front();
7240                state.async_busy = false;
7241                true
7242            }
7243            _ => false,
7244        });
7245        if settled {
7246            match outcome {
7247                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7248                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7249            }
7250        }
7251        self.next_async_request(generator)
7252    }
7253
7254    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7255    ///
7256    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7257    /// disposer runs **synchronously** — the reference starts it before returning, which
7258    /// a test can observe by logging after the call — and the rest follow once their
7259    /// predecessor settles.
7260    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7261        let promise = self.new_promise();
7262        let mut pairs = Vec::with_capacity(resources.len());
7263        for (value, method) in resources {
7264            let pair = self.new_array(vec![value, method]);
7265            pairs.push(Value::Object(pair));
7266        }
7267        let remaining = self.new_array(pairs);
7268        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7269        Ok(Value::Object(promise))
7270    }
7271
7272    /// One link of the `disposeAsync` chain.
7273    ///
7274    /// Loops while the disposers finish synchronously, and parks on the first thenable it
7275    /// meets — pushing itself back in as the continuation, with the accumulated error
7276    /// carried along so a later failure can still be folded into the `SuppressedError`.
7277    fn dispose_step(
7278        &mut self,
7279        remaining: &Gc<JsObject>,
7280        promise: &Gc<JsObject>,
7281        mut error: Value,
7282    ) -> JsResult<()> {
7283        loop {
7284            let length = remaining.array_length().unwrap_or(0);
7285            if length == 0 {
7286                if matches!(error, Value::Uninitialized) {
7287                    self.fulfill_promise(promise, Value::Undefined);
7288                } else {
7289                    self.reject_promise(promise, error);
7290                }
7291                return Ok(());
7292            }
7293            let Some(Value::Object(pair)) = remaining
7294                .array_get(length - 1)
7295                .filter(|v| !matches!(v, Value::Hole))
7296            else {
7297                remaining.array_truncate(self.heap, length - 1);
7298                continue;
7299            };
7300            remaining.array_truncate(self.heap, length - 1);
7301            let value = pair.array_get(0).unwrap_or(Value::Undefined);
7302            let Some(Value::Object(method)) = pair.array_get(1) else {
7303                continue;
7304            };
7305            if !method.is_callable() {
7306                continue;
7307            }
7308            match self.call_value(Value::Object(method), value, Vec::new()) {
7309                Ok(result) => {
7310                    if !self.is_thenable(&result)? {
7311                        // Finished synchronously; the next disposer is the next iteration.
7312                        continue;
7313                    }
7314                    let awaited = match self.promise_resolve_value(result) {
7315                        Ok(awaited) => awaited,
7316                        Err(Signal::Throw(reason)) => {
7317                            self.reject_promise(promise, reason);
7318                            return Ok(());
7319                        }
7320                        Err(other) => return Err(other),
7321                    };
7322                    let Value::Object(awaited) = awaited else {
7323                        continue;
7324                    };
7325                    let ok = JsObject::function(
7326                        self.heap,
7327                        Some(self.realm.function_proto.clone()),
7328                        Callable::DisposeStep {
7329                            remaining: remaining.clone(),
7330                            promise: promise.clone(),
7331                            error: error.clone(),
7332                            rejected: false,
7333                        },
7334                    );
7335                    let failed = JsObject::function(
7336                        self.heap,
7337                        Some(self.realm.function_proto.clone()),
7338                        Callable::DisposeStep {
7339                            remaining: remaining.clone(),
7340                            promise: promise.clone(),
7341                            error,
7342                            rejected: true,
7343                        },
7344                    );
7345                    self.perform_then(
7346                        &awaited,
7347                        Some(Value::Object(ok)),
7348                        Some(Value::Object(failed)),
7349                    )?;
7350                    return Ok(());
7351                }
7352                Err(Signal::Throw(thrown)) => {
7353                    error = self.merge_dispose_error(thrown, error);
7354                }
7355                Err(other) => return Err(other),
7356            }
7357        }
7358    }
7359
7360    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7361    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7362        let Value::Object(object) = value else {
7363            return Ok(false);
7364        };
7365        Ok(matches!(
7366            self.get_property(object, "then")?,
7367            Some(Value::Object(then)) if then.is_callable()
7368        ))
7369    }
7370
7371    /// One step of an async generator, settling `promise` with an `{value, done}` result.
7372    fn step_async_generator(
7373        &mut self,
7374        generator: &Gc<JsObject>,
7375        promise: &Gc<JsObject>,
7376        kind: ResumeKind,
7377        value: Value,
7378    ) -> JsResult<()> {
7379        let stepped = self.resume_generator_detailed(generator, kind, value);
7380        let (value, done, ready, reason) = match stepped {
7381            Ok(stepped) => stepped,
7382            Err(Signal::Throw(reason)) => {
7383                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7384            }
7385            Err(other) => return Err(other),
7386        };
7387        // Only an `await` has to wait before the method can answer.
7388        if !done && reason == Some(SuspendKind::Await) {
7389            let awaited = match self.promise_resolve_value(value) {
7390                Ok(awaited) => awaited,
7391                Err(Signal::Throw(reason)) => {
7392                    return self.settle_async_request(
7393                        generator,
7394                        promise,
7395                        AsyncOutcome::Error(reason),
7396                    );
7397                }
7398                Err(other) => return Err(other),
7399            };
7400            let Value::Object(awaited) = awaited else {
7401                return Ok(());
7402            };
7403            let resumed = JsObject::function(
7404                self.heap,
7405                Some(self.realm.function_proto.clone()),
7406                Callable::GeneratorResume {
7407                    generator: generator.clone(),
7408                    promise: promise.clone(),
7409                    kind: ResumeKind::Next,
7410                },
7411            );
7412            let raised = JsObject::function(
7413                self.heap,
7414                Some(self.realm.function_proto.clone()),
7415                Callable::GeneratorResume {
7416                    generator: generator.clone(),
7417                    promise: promise.clone(),
7418                    kind: ResumeKind::Throw,
7419                },
7420            );
7421            self.perform_then(
7422                &awaited,
7423                Some(Value::Object(resumed)),
7424                Some(Value::Object(raised)),
7425            )?;
7426            return Ok(());
7427        }
7428        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7429        // completes it — both arrive as the settled value rather than as the promise
7430        // object. A plain value skips the round trip, which is also what keeps `yield 1`
7431        // from costing an extra tick.
7432        let awaits_value = self.is_thenable(&value)?;
7433        if awaits_value {
7434            let awaited = match self.promise_resolve_value(value) {
7435                Ok(awaited) => awaited,
7436                Err(Signal::Throw(reason)) => {
7437                    return self.settle_async_request(
7438                        generator,
7439                        promise,
7440                        AsyncOutcome::Error(reason),
7441                    );
7442                }
7443                Err(other) => return Err(other),
7444            };
7445            let Value::Object(awaited) = awaited else {
7446                return Ok(());
7447            };
7448            // A rejected yield throws *at the yield* inside the body, so the rejection
7449            // resumes the generator rather than the method's promise.
7450            let answer = JsObject::function(
7451                self.heap,
7452                Some(self.realm.function_proto.clone()),
7453                Callable::YieldResult {
7454                    generator: generator.clone(),
7455                    promise: promise.clone(),
7456                    done,
7457                },
7458            );
7459            let raise = JsObject::function(
7460                self.heap,
7461                Some(self.realm.function_proto.clone()),
7462                Callable::GeneratorResume {
7463                    generator: generator.clone(),
7464                    promise: promise.clone(),
7465                    kind: ResumeKind::Throw,
7466                },
7467            );
7468            self.perform_then(
7469                &awaited,
7470                Some(Value::Object(answer)),
7471                Some(Value::Object(raise)),
7472            )?;
7473            return Ok(());
7474        }
7475        let result = if ready {
7476            // `yield*` handed back the inner iterator's own result object.
7477            value
7478        } else {
7479            self.iterator_result(value, done)?
7480        };
7481        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7482    }
7483
7484    /// The `{value, done}` object an iterator method answers with.
7485    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7486        let result = self.new_object(Some(self.realm.object_proto.clone()));
7487        result.define_data("value", value);
7488        result.define_data("done", Value::Bool(done));
7489        Ok(Value::Object(result))
7490    }
7491
7492    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7493    fn step_generator(
7494        &mut self,
7495        state: &mut GeneratorState,
7496        kind: ResumeKind,
7497        value: Value,
7498    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7499        match state.phase {
7500            GeneratorPhase::Executing => {
7501                return Err(self.type_error("cannot invoke a running generator"));
7502            }
7503            GeneratorPhase::Completed => {
7504                // A finished generator answers every resumption without running.
7505                return Ok(match kind {
7506                    ResumeKind::Throw => return Err(Signal::Throw(value)),
7507                    ResumeKind::Return => (value, true, false, None),
7508                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7509                });
7510            }
7511            GeneratorPhase::SuspendedStart => {
7512                if kind != ResumeKind::Next && kind != ResumeKind::Start {
7513                    // The body never started, so there is nothing to unwind or return
7514                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7515                    state.frame = None;
7516                    state.phase = GeneratorPhase::Completed;
7517                    return Ok(match kind {
7518                        ResumeKind::Throw => return Err(Signal::Throw(value)),
7519                        _ => (value, true, false, None),
7520                    });
7521                }
7522            }
7523            GeneratorPhase::SuspendedYield => {}
7524        }
7525
7526        let Some(mut frame) = state.frame.take() else {
7527            return Ok((Value::Undefined, true, false, None));
7528        };
7529        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7530        // number that says which method resumed it; the emitted `if_false` branches on
7531        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7532        let mut raised = None;
7533        match kind {
7534            ResumeKind::Next | ResumeKind::Start => {
7535                if state.phase == GeneratorPhase::SuspendedYield {
7536                    frame.stack.push(value);
7537                    // An `await` resumes with its value alone; only a `yield` gets the
7538                    // magic number that says which of `next`/`return` resumed it.
7539                    if !state.parked_on_await {
7540                        frame.stack.push(Value::Int(RESUME_NEXT));
7541                    }
7542                }
7543            }
7544            ResumeKind::Return => {
7545                // A `return` on a not-yet-started generator is handled above, so this is
7546                // always a real resumption.
7547                frame.stack.push(value);
7548                frame.stack.push(Value::Int(RESUME_RETURN));
7549            }
7550            ResumeKind::Throw => {
7551                // At a `yield*` the exception is *data* for the delegation: the compiled
7552                // code resumes with the value and magic `2` and calls the inner iterator's
7553                // `throw`. Everywhere else it is raised at the suspension point, so the
7554                // body's own handler sees it.
7555                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7556                    frame.stack.push(value);
7557                    frame.stack.push(Value::Int(RESUME_THROW));
7558                } else {
7559                    raised = Some(value);
7560                }
7561            }
7562        }
7563        state.phase = GeneratorPhase::Executing;
7564
7565        let depth = self.frames.len();
7566        self.frames.push(frame);
7567        // A `throw` unwinds from where the frame parked, exactly as if the exception had
7568        // happened at the `yield`.
7569        if let Some(exception) = raised {
7570            if self.catch_here(exception.clone()).is_none() {
7571                self.pop_frame();
7572                state.phase = GeneratorPhase::Completed;
7573                return Err(Signal::Throw(exception));
7574            }
7575        }
7576
7577        // Only the generator's *own* frame ends the generator. The body may call ordinary
7578        // functions, and those push frames of their own: a `Step::Return` from one of them
7579        // is a nested call finishing, not the generator completing. Miscounting that is
7580        // silent — the generator reports the callee's value as its own result and marks
7581        // itself done — so the depth comparison is load-bearing, not defensive.
7582        let own_frame = depth + 1;
7583        loop {
7584            match self.step() {
7585                Ok(Step::Continue) => {}
7586                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7587                    let mut frame = self.frames.pop().expect("a frame is live");
7588                    // `yield` left the value on the stack; `initial_yield` left nothing.
7589                    let yielded = if reason == SuspendKind::Initial {
7590                        Value::Undefined
7591                    } else {
7592                        frame.stack.pop().unwrap_or(Value::Undefined)
7593                    };
7594                    state.frame = Some(frame);
7595                    state.parked_on_await = reason == SuspendKind::Await;
7596                    state.parked_on_yield_star =
7597                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7598                    state.phase = if reason == SuspendKind::Initial {
7599                        GeneratorPhase::SuspendedStart
7600                    } else {
7601                        GeneratorPhase::SuspendedYield
7602                    };
7603                    // `yield*` hands the inner iterator's own result object straight
7604                    // back, so the caller sees one `{value, done}` rather than a nested
7605                    // one — which is why the third field says "already a result".
7606                    return Ok((
7607                        yielded,
7608                        false,
7609                        reason == SuspendKind::YieldStar,
7610                        Some(reason),
7611                    ));
7612                }
7613                Ok(Step::Suspend(_)) => {
7614                    // A `yield` in a frame other than the generator's would mean a
7615                    // generator body entered as an ordinary call, which
7616                    // `call_or_push` prevents.
7617                    self.unwind_to(depth);
7618                    state.phase = GeneratorPhase::Completed;
7619                    return Err(Signal::Throw(self.make_error(
7620                        "InternalError",
7621                        "a generator body ran as an ordinary call",
7622                    )));
7623                }
7624                Ok(Step::Return(value)) => {
7625                    self.pop_frame();
7626                    if self.frames.len() > depth {
7627                        // A nested call finished: hand the value back to its caller and
7628                        // keep running the generator body.
7629                        self.frames
7630                            .last_mut()
7631                            .expect("a caller is live")
7632                            .stack
7633                            .push(value);
7634                        continue;
7635                    }
7636                    state.phase = GeneratorPhase::Completed;
7637                    // The reference closes the generator's closure variables here; ours
7638                    // live in cells the frame owned, which the drop below releases.
7639                    return Ok((value, true, false, None));
7640                }
7641                Err(Signal::Throw(exception)) => {
7642                    // The frame that threw gets the first chance to catch, exactly as in
7643                    // the ordinary call loop; a frame above the generator's is popped and
7644                    // the exception carries on down.
7645                    let exception = exception;
7646                    loop {
7647                        if self.frames.len() <= depth {
7648                            // The generator's own frame is gone, so nothing here caught it.
7649                            state.phase = GeneratorPhase::Completed;
7650                            return Err(Signal::Throw(exception));
7651                        }
7652                        if self.catch_here(exception.clone()).is_some() {
7653                            break;
7654                        }
7655                        self.pop_frame();
7656                    }
7657                }
7658                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7659            }
7660        }
7661    }
7662
7663    /// Pop frames until `depth` are left, keeping their buffers.
7664    fn unwind_to(&mut self, depth: usize) {
7665        while self.frames.len() > depth {
7666            self.pop_frame();
7667        }
7668    }
7669    fn call_or_push(
7670        &mut self,
7671        callee: Value,
7672        this: Value,
7673        args: Vec<Value>,
7674    ) -> JsResult<Option<Value>> {
7675        if let Value::Object(function) = &callee
7676            && let Some((code, env)) = bytecode_of(function)
7677        {
7678            // Calling a generator function does not run anything: it captures the
7679            // arguments in a frame and hands back the generator object.
7680            if code.code.kind.is_generator() {
7681                return self.new_generator(callee, this, args).map(Some);
7682            }
7683            // An async function answers a promise and runs its body as a coroutine, so it
7684            // takes the same path as a plain call into it.
7685            if code.code.kind.is_async() {
7686                return self.new_async_function(callee, this, args).map(Some);
7687            }
7688            self.push_frame(code, env, this, args, callee)?;
7689            return Ok(None);
7690        }
7691        self.call_value(callee, this, args).map(Some)
7692    }
7693
7694    /// `new callee(args)`.
7695    ///
7696    /// A constructor differs from a plain call in three ways: it gets a fresh object
7697    /// as `this` whose prototype is the constructor's `prototype` property, its
7698    /// return value is *replaced* by that object unless it returns an object itself,
7699    /// and a native constructor is expected to initialise the object it is given
7700    /// rather than build one.
7701    pub fn construct(
7702        &mut self,
7703        callee: Value,
7704        new_target: Value,
7705        args: Vec<Value>,
7706    ) -> JsResult<Value> {
7707        // `new` on a bound function constructs its *target*, prepending the arguments
7708        // the bind fixed and ignoring the bound `this` — a bound function is a
7709        // constructor only when its target is one, and `new` always makes a fresh
7710        // object of the target's prototype rather than reusing the bound receiver.
7711        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7712        // ran the body with `this === null` and threw on `this.x = a`.
7713        let mut callee = callee;
7714        let mut new_target = new_target;
7715        let mut args = args;
7716        loop {
7717            let Some(object) = callee.as_object().cloned() else {
7718                return Err(Signal::Throw(
7719                    self.make_error("TypeError", "not a constructor"),
7720                ));
7721            };
7722            // A proxy of a function constructs through its `construct` trap, and the
7723            // trap's answer is the result directly — no fresh object is made here.
7724            if object.proxy_state().is_some() {
7725                return match self.proxy_construct(&object, args, &new_target)? {
7726                    Some(result) => Ok(result),
7727                    None => Err(Signal::Throw(
7728                        self.make_error("TypeError", "proxy target is not a constructor"),
7729                    )),
7730                };
7731            }
7732            // A generator function has no `[[Construct]]`, and the reference names it in
7733            // the message: `new (function* G(){})()` reports "G is not a constructor".
7734            if object.with(|data| match &data.kind {
7735                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7736                    code.code.kind.is_generator()
7737                }
7738                _ => false,
7739            }) {
7740                let name = object
7741                    .own_property("name")
7742                    .and_then(|property| property.value)
7743                    .map(|value| value.to_js_string())
7744                    .unwrap_or_default();
7745                return Err(Signal::Throw(
7746                    self.make_error("TypeError", &format!("{name} is not a constructor")),
7747                ));
7748            }
7749            let bound = object.with(|data| match &data.kind {
7750                ObjectKind::Function(Callable::Bound {
7751                    target,
7752                    args: leading,
7753                    ..
7754                }) => Some((target.clone(), leading.clone())),
7755                _ => None,
7756            });
7757            let Some((target, leading)) = bound else {
7758                // Not a bound function, so this object is the callee. §7.2.4
7759                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7760                // refusals above cover only the built-ins the reference also refuses by
7761                // name. Everything else — a method, an arrow, an async function — has no
7762                // `[[Construct]]` either, and answering "yes" here made
7763                // `new (Array.prototype.map)` build an object instead of throwing.
7764                if !object.is_constructor() {
7765                    let name = object
7766                        .own_property("name")
7767                        .and_then(|property| property.value)
7768                        .map(|value| value.to_js_string())
7769                        .unwrap_or_default();
7770                    return Err(Signal::Throw(
7771                        self.make_error("TypeError", &format!("{name} is not a constructor")),
7772                    ));
7773                }
7774                break;
7775            };
7776            let mut all = leading;
7777            all.extend(args);
7778            args = all;
7779            // A bound function that is its own `new.target` stands in for its target:
7780            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
7781            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
7782            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
7783                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
7784                _ => false,
7785            };
7786            if same_wrapper {
7787                new_target = target.clone();
7788            }
7789            callee = target;
7790        }
7791        let Value::Object(function) = &callee else {
7792            unreachable!("the loop above only breaks on an object");
7793        };
7794        // The fresh object's prototype comes from `new.target`, not from the callee: a
7795        // derived constructor reaches here through `super()`, and the instance must be a
7796        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7797        // an object inheriting `D.prototype` rather than `C.prototype`.
7798        let prototype_source = match new_target.as_object() {
7799            Some(target) => target.clone(),
7800            None => function.clone(),
7801        };
7802        // A native constructor builds its own instance, through `new_ctor_instance`, once it
7803        // has validated its arguments. Pre-building one here would read
7804        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7805        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7806        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7807        let is_native = function.native_creates_own_instance();
7808        let this = if is_native {
7809            Value::Undefined
7810        } else {
7811            let prototype = self.get_property(&prototype_source, "prototype")?;
7812            let prototype = match prototype {
7813                Some(Value::Object(proto)) => Some(proto),
7814                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7815                // object, the answer is the realm's *intrinsic* prototype for this
7816                // constructor, not `%Object.prototype%`.
7817                _ => {
7818                    let fallback = self.get_property(function, "prototype")?;
7819                    match fallback {
7820                        Some(Value::Object(proto)) => Some(proto),
7821                        _ => Some(self.realm.object_proto.clone()),
7822                    }
7823                }
7824            };
7825            Value::Object(self.new_object(prototype))
7826        };
7827        // `new.target` inside the body is the constructor that was written, so a bound
7828        // function's target sees itself rather than the bound wrapper.
7829        //
7830        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7831        // `?`, so assigning `None` after the call would be skipped and the failed
7832        // `new.target` would stay visible to every later native call. The symptom was a
7833        // native constructor refusing a plain call — `var s = Symbol(); new
7834        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
7835        // "FinalizationRegistry is not a constructor".
7836        let outer_new_target = self.pending_new_target.replace(new_target);
7837        let result = self.call_value(callee, this.clone(), args);
7838        self.pending_new_target = outer_new_target;
7839        let result = result?;
7840        // A constructor that returns an object overrides `this`; any other return
7841        // value (including `undefined`) is ignored.
7842        Ok(match result {
7843            Value::Object(_) => result,
7844            _ => this,
7845        })
7846    }
7847
7848    /// `new.target` for the call currently being made.
7849    ///
7850    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
7851    /// it as `this`), but a *host* constructor that builds its own instance is handed
7852    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
7853    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
7854    /// it here.
7855    ///
7856    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
7857    /// receives for a plain call.
7858    pub fn current_new_target(&self) -> Value {
7859        self.pending_new_target.clone().unwrap_or(Value::Undefined)
7860    }
7861
7862    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
7863    ///
7864    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
7865    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
7866    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
7867        let constructor = self.realm.errors.get("AggregateError").cloned();
7868        let Some(constructor) = constructor else {
7869            return self.make_error("AggregateError", message);
7870        };
7871        let list = self.new_array(errors);
7872        match self.construct(
7873            Value::Object(constructor.clone()),
7874            Value::Object(constructor),
7875            vec![Value::Object(list), self.string(message)],
7876        ) {
7877            Ok(value) => value,
7878            // A user could have replaced `AggregateError` with something that throws; the
7879            // engine still owes the caller a rejection, so it falls back rather than
7880            // turning `Promise.any`'s rejection into a throw.
7881            Err(_) => self.make_error("AggregateError", message),
7882        }
7883    }
7884
7885    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
7886    ///
7887    /// The error classes themselves arrive with the builtins milestone; what
7888    /// matters here is that the thrown value stringifies the way a script printing
7889    /// the caught value expects.
7890    ///
7891    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
7892    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
7893    /// rely on when they print a caught value.
7894    pub fn make_error(&self, name: &str, message: &str) -> Value {
7895        let proto = self
7896            .realm
7897            .errors
7898            .get(name)
7899            .map(|constructor| self.prototype_of(constructor))
7900            .unwrap_or_else(|| self.realm.error_proto.clone());
7901        let error = self.new_object(Some(proto));
7902        // `name` and `message` are own properties of the instance, which is what
7903        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
7904        // `Error`.
7905        error.define(
7906            "name",
7907            Property::with_attributes(self.string(name), true, false),
7908        );
7909        error.define(
7910            "message",
7911            Property::with_attributes(self.string(message), true, false),
7912        );
7913        // The internal class, which is what tells a printer this is an error rather than a
7914        // plain object with `name` and `message` properties. The constructor path sets it
7915        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
7916        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
7917        // literally `"Error"` in both places — the *name* is read from `name`, which is why
7918        // a `RangeError` still prints as `RangeError`.
7919        self.internal_set(&error, "_class", self.string("Error"));
7920        // The trace is captured where the error is *made*, which is where the reference
7921        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
7922        // way out, so a caught engine error already has its stack even if the handler
7923        // never rethrows it.
7924        self.add_stack(&error);
7925        Value::Object(error)
7926    }
7927
7928    /// Give an error object its `stack` property, from the current frame stack.
7929    ///
7930    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
7931    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
7932    /// `stack` a script set, is not rewritten.
7933    pub fn add_stack(&self, object: &Gc<JsObject>) {
7934        self.add_stack_skipping(object, 0);
7935    }
7936
7937    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
7938    ///
7939    /// An `Error` constructor passes 1: the reference builds those traces with
7940    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
7941    /// constructor itself, while a `RangeError` raised inside `toISOString` does
7942    /// report `at toISOString (native)`.
7943    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
7944        if object.has_own("stack") {
7945            return;
7946        }
7947        let trace = self.stack_trace_skipping(skip);
7948        let text = self.string(trace);
7949        object.define("stack", Property::with_attributes(text, true, true));
7950    }
7951
7952    /// The function object currently being called, if any.
7953    ///
7954    /// A native function is a bare `fn` pointer, so it cannot capture which class
7955    /// it belongs to; it reads that from the callee instead. This is also what a
7956    /// stack trace would use.
7957    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
7958        match &self.frames.last()?.callee {
7959            Value::Object(object) => Some(object.clone()),
7960            _ => None,
7961        }
7962    }
7963
7964    /// The `prototype` property of a constructor, falling back to
7965    /// `Object.prototype` for anything that is not shaped like one.
7966    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
7967        constructor
7968            .own_property("prototype")
7969            .and_then(|property| property.value)
7970            .and_then(|value| value.as_object().cloned())
7971            .unwrap_or_else(|| self.realm.object_proto.clone())
7972    }
7973
7974    /// Throw a `TypeError` carrying `message`.
7975    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
7976        Signal::Throw(self.make_error("TypeError", message.as_ref()))
7977    }
7978
7979    /// Throw a `RangeError` carrying `message`.
7980    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
7981        Signal::Throw(self.make_error("RangeError", message.as_ref()))
7982    }
7983
7984    /// The `ReferenceError` a read of an uninitialised binding raises.
7985    /// The name of the binding `slot` refers to, for an error message.
7986    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
7987        match kind {
7988            VarSlot::Loc => self
7989                .frame()
7990                .code
7991                .code
7992                .vars
7993                .get(slot)
7994                .map(|v| v.name.clone()),
7995            VarSlot::Closure => self
7996                .frame()
7997                .code
7998                .code
7999                .closure_vars
8000                .get(slot)
8001                .map(|c| c.name.clone()),
8002        }
8003        .unwrap_or_default()
8004    }
8005
8006    /// Whether `slot` names a `const` binding, which rejects every store after its
8007    /// initialiser.
8008    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8009        match kind {
8010            VarSlot::Loc => self
8011                .frame()
8012                .code
8013                .code
8014                .vars
8015                .get(slot)
8016                .is_some_and(|v| v.is_const),
8017            VarSlot::Closure => self
8018                .frame()
8019                .code
8020                .code
8021                .closure_vars
8022                .get(slot)
8023                .is_some_and(|c| c.is_const),
8024        }
8025    }
8026
8027    /// The `TypeError` a store to a `const` binding raises.
8028    ///
8029    /// `const` is enforced here rather than at compile time because the binding can be
8030    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8031    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8032    /// both halves of what "checked store" means: the dead zone is over, and the
8033    /// binding is writable.
8034    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8035        let name = self.binding_name(slot, kind);
8036        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8037    }
8038
8039    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8040        let name = match kind {
8041            VarSlot::Loc => self
8042                .frame()
8043                .code
8044                .code
8045                .vars
8046                .get(slot)
8047                .map(|v| v.name.clone()),
8048            VarSlot::Closure => self
8049                .frame()
8050                .code
8051                .code
8052                .closure_vars
8053                .get(slot)
8054                .map(|c| c.name.clone()),
8055        }
8056        .unwrap_or_default();
8057        Signal::Throw(self.make_error(
8058            "ReferenceError",
8059            &format!("cannot access '{name}' before initialization"),
8060        ))
8061    }
8062
8063    fn throw_reference(&self, name: &str) -> Signal {
8064        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8065    }
8066
8067    // -- the instruction loop -----------------------------------------------
8068
8069    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8070    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8071    // measured at 16% of a tight arithmetic loop's total time.
8072    #[inline(always)]
8073    fn step(&mut self) -> JsResult<Step> {
8074        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8075        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8076        // borrow lives across the boundary; nothing is cloned.
8077        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8078        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8079        // write, and once more inside the handler), and each is a bounds check plus an
8080        // `Option` unwrap — on the one path every instruction takes.
8081        let Some((insn, next)) = ({
8082            let frame = self
8083                .frames
8084                .last_mut()
8085                .expect("step() is only called with a live frame");
8086            // Past the last instruction is a normal return: the compiler ends a function
8087            // with `return`, and a jump to the end of a block lands here.
8088            let insn = frame.insns().get(frame.pc).copied();
8089            match insn {
8090                None => None,
8091                Some(insn) => {
8092                    // A fused record stands for the next few instructions, so the next
8093                    // `pc` is its width ahead — the instructions it replaces are never
8094                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8095                    // an offset because the line table is keyed by bytes.
8096                    frame.at = insn.offset as usize;
8097                    frame.pc += insn.width();
8098                    Some((insn, frame.pc))
8099                }
8100            }
8101        }) else {
8102            return Ok(Step::Return(Value::Undefined));
8103        };
8104        self.check_memory()?;
8105        self.check_interrupt()?;
8106        if insn.fused == crate::insn::Fused::None {
8107            self.execute_instruction(insn.op, insn.a, insn.b, next)
8108        } else {
8109            self.execute_fused(insn)
8110        }
8111    }
8112
8113    /// Run a fused instruction: several bytecode instructions in one dispatch.
8114    ///
8115    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8116    /// it cannot throw and cannot allocate — and anything else falls back to the real
8117    /// instructions, in their real order, so an exception leaves the operand stack
8118    /// exactly as it would have been.
8119    #[inline]
8120    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8121        use crate::insn::Fused;
8122        let slot = insn.a as usize;
8123        match insn.fused {
8124            // `x = k`: `push k; put_loc x`.
8125            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8126            // `x += k`: `get_loc x; push k; add; put_loc x`.
8127            Fused::AddImmLoc => {
8128                let delta = insn.b as i32;
8129                match self.get_loc(slot) {
8130                    Value::Int(left) => {
8131                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8132                        // that built two `Value`s, called a function, and matched on them
8133                        // again to reach this same `checked_add`. It is the innermost
8134                        // operation of every accumulator in every program.
8135                        let answer = match left.checked_add(delta) {
8136                            Some(sum) => Value::Int(sum),
8137                            None => Value::Float(left as f64 + delta as f64),
8138                        };
8139                        self.put_loc(slot, answer);
8140                    }
8141                    other => {
8142                        self.push(other);
8143                        self.push(Value::Int(delta));
8144                        self.binary_add()?;
8145                        let value = self.pop();
8146                        self.put_loc(slot, value);
8147                    }
8148                }
8149            }
8150            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8151            Fused::AddAtomLoc => {
8152                let text = self.atom_wtf8(insn.b as usize);
8153                let right = self.string_wtf8(text);
8154                self.add_into_loc(slot, right)?;
8155            }
8156            Fused::AddLocLoc => {
8157                let source = (insn.a & 0xFFFF) as usize;
8158                let target = (insn.a >> 16) as usize;
8159                let right = self.get_loc(source);
8160                self.add_into_loc(target, right)?;
8161            }
8162            Fused::AddArgLoc => {
8163                let source = (insn.a & 0xFFFF) as usize;
8164                let target = (insn.a >> 16) as usize;
8165                let right = self.get_arg(source);
8166                self.add_into_loc(target, right)?;
8167            }
8168            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8169            Fused::PostIncLoc => match self.get_loc(slot) {
8170                Value::Int(left) => {
8171                    let answer = match left.checked_add(1) {
8172                        Some(sum) => Value::Int(sum),
8173                        None => Value::Float(left as f64 + 1.0),
8174                    };
8175                    self.put_loc(slot, answer);
8176                }
8177                other => {
8178                    self.push(other);
8179                    let raw = self.pop();
8180                    let (old, updated) = self.advance_numeric(raw, true)?;
8181                    self.push(old);
8182                    self.push(updated);
8183                    let value = self.pop();
8184                    self.put_loc(slot, value);
8185                    self.pop();
8186                }
8187            },
8188            // `if (!(x < arg)) goto target`: a loop header.
8189            //
8190            // The comparison is computed rather than replayed on the operand stack. That
8191            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8192            // that throws: the effects happen in the same order, and a handler truncates
8193            // the stack down to its marker, so the intermediate values are unobservable.
8194            Fused::LtLocArgJump => {
8195                let loc = (insn.a >> 16) as usize;
8196                let arg = (insn.a & 0xFFFF) as usize;
8197                let left = self.get_loc(loc);
8198                let right = self.get_arg(arg);
8199                let taken = match (&left, &right) {
8200                    (Value::Int(left), Value::Int(right)) => !(left < right),
8201                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8202                };
8203                if taken {
8204                    self.frame_mut().pc = insn.b as usize;
8205                }
8206            }
8207            // `i < k` in a loop header, where `k` is an integer literal.
8208            Fused::LtLocImmJump => {
8209                let left = self.get_loc(insn.a as usize);
8210                let right = Value::Int(insn.imm as i32);
8211                let taken = match &left {
8212                    Value::Int(left) => !(*left < insn.imm as i32),
8213                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8214                };
8215                if taken {
8216                    self.frame_mut().pc = insn.b as usize;
8217                }
8218            }
8219            Fused::None => unreachable!("only called for a fused record"),
8220        }
8221        Ok(Step::Continue)
8222    }
8223
8224    /// Run records that cannot call script, cannot throw and cannot change frames.
8225    ///
8226    /// Returns `Some(value)` when the function ran off the end of its instructions (a
8227    /// normal return), and `None` when it stopped in front of an instruction the slow path
8228    /// has to handle — `pc` is written back either way, so `step` resumes at the right
8229    /// place.
8230    ///
8231    /// **The invariant is the whole point.** Every arm here is restricted to work that
8232    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8233    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8234    /// that the memory limit has to see. An opcode whose operands turn out to need any of
8235    /// that **stops the loop** instead of trying, so the slow path gets the instruction
8236    /// untouched and with its operands still on the stack. That is why the fallback is a
8237    /// `break` and not a duplicated slow arm: a second implementation of the same
8238    /// semantics is how a wrong answer gets in with no test noticing.
8239    ///
8240    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8241    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8242    fn run_fast(&mut self) -> JsResult<Option<Value>> {
8243        use crate::insn::Fused;
8244        // The outer loop exists only so a `Call` can come back through here: once a
8245        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8246        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8247        // frame. Re-entering re-reads both from whichever frame is now on top. Every
8248        // other exit from the inner loop returns, so this costs one loop per call.
8249        'outer: loop {
8250            // One reference-count bump per *slow* instruction (a call, an allocation, a
8251            // property access), never one per instruction — that distinction is worth
8252            // two orders of magnitude and was measured as such.
8253            let (code, mut pc) = {
8254                let frame = self.frame();
8255                (frame.code.clone(), frame.pc)
8256            };
8257            let insns = &code.insns;
8258            loop {
8259                let Some(insn) = insns.get(pc).copied() else {
8260                    self.frame_mut().pc = pc;
8261                    return Ok(Some(Value::Undefined));
8262                };
8263                match insn.fused {
8264                    // `x = k`
8265                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8266                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8267                    // object — stops the loop so `binary_add` can decide.
8268                    Fused::AddImmLoc => {
8269                        let slot = insn.a as usize;
8270                        let delta = insn.b as i32;
8271                        let Value::Int(left) = self.get_loc(slot) else {
8272                            return Ok(self.stop(pc));
8273                        };
8274                        let sum = match left.checked_add(delta) {
8275                            Some(sum) => Value::Int(sum),
8276                            None => Value::Float(left as f64 + delta as f64),
8277                        };
8278                        self.put_loc(slot, sum);
8279                    }
8280                    // `x += "literal"` / `x += y`: the operand is a string, so the append
8281                    // either allocates one or grows one. Both are the slow path's business;
8282                    // the fusion's job is only to make the *slot* the sole owner, which is what
8283                    // `execute_fused` needs and what `get_loc` alone destroys.
8284                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8285                        return Ok(self.stop(pc));
8286                    }
8287                    // `x++` on an integer, old value dropped.
8288                    Fused::PostIncLoc => {
8289                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8290                        // value is read in place and overwritten in place, so the reference
8291                        // count it held is released by the same assignment that stores the
8292                        // new one. `get_loc` plus `put_loc` did two borrows, two table
8293                        // lookups and a clone, and this arm is the whole body of a counting
8294                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8295                        let slot = insn.a as usize;
8296                        let frame = self.frames.last_mut().expect("a frame is live");
8297                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8298                        let target = if cell < 0 {
8299                            frame.locals.get_mut(slot)
8300                        } else {
8301                            None
8302                        };
8303                        let Some(target) = target else {
8304                            return Ok(self.stop(pc));
8305                        };
8306                        let Value::Int(left) = *target else {
8307                            return Ok(self.stop(pc));
8308                        };
8309                        *target = match left.checked_add(1) {
8310                            Some(sum) => Value::Int(sum),
8311                            None => Value::Float(left as f64 + 1.0),
8312                        };
8313                    }
8314                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
8315                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8316                    // bound stayed small integers.
8317                    Fused::LtLocArgJump => {
8318                        let loc = (insn.a >> 16) as usize;
8319                        let arg = (insn.a & 0xFFFF) as usize;
8320                        // One borrow for both slots: this arm *is* the whole loop of a
8321                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
8322                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
8323                        // `dispatch:empty-loop`.
8324                        let (left, right) = {
8325                            let frame = self.frame();
8326                            (frame.read_loc(loc), frame.read_arg(arg))
8327                        };
8328                        // Heavily measured: the bound is very often a `Float` even when the
8329                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8330                        // `JSON.parse` or a division is one — so requiring both sides to be
8331                        // `Int` sent every iteration of those loops down the slow path. The
8332                        // comparison below is the same one `relational` makes for two numbers.
8333                        if !is_number(&left) || !is_number(&right) {
8334                            return Ok(self.stop(pc));
8335                        }
8336                        // `if_false` branches on the comparison being false, which is **not**
8337                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8338                        // `>=` is also false and would keep it running forever. Clippy wants the
8339                        // negation folded; that would be a wrong answer.
8340                        let ordered = left.to_number() < right.to_number();
8341                        let take_branch = !ordered;
8342                        if take_branch {
8343                            pc = insn.b as usize;
8344                            continue;
8345                        }
8346                    }
8347                    // The same header with a literal bound: `if (!(x < k)) goto target`.
8348                    // The bound is an immediate, so only the counter needs a type test.
8349                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
8350                    Fused::LtLocImmJump => {
8351                        let left = self.get_loc(insn.a as usize);
8352                        if !is_number(&left) {
8353                            return Ok(self.stop(pc));
8354                        }
8355                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8356                        if take_branch {
8357                            pc = insn.b as usize;
8358                            continue;
8359                        }
8360                    }
8361                    Fused::None => match insn.op {
8362                        // -- branches ---------------------------------------------------
8363                        // A jump is an assignment now, because the target is an instruction
8364                        // index. No arithmetic, no resolution table.
8365                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8366                            let target = insn.a as usize;
8367                            // A **back-edge** is a loop, and it is the only place an
8368                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
8369                            // to a jump to itself and never leaves this loop, so the
8370                            // per-instruction checks in `step` never run. That is exactly the
8371                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
8372                            // nothing to a `for(;;){}` until it did, which is what
8373                            // `tests/c/embed.c` is for.
8374                            //
8375                            // Polling here rather than on every instruction in this loop is
8376                            // also the reference's choice (`OP_goto` calls
8377                            // `js_poll_interrupts`), and it costs one compare per branch
8378                            // instead of one decrement per instruction.
8379                            if target <= pc {
8380                                self.frame_mut().pc = target;
8381                                self.check_memory()?;
8382                                self.check_interrupt()?;
8383                            }
8384                            pc = target;
8385                            continue;
8386                        }
8387                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8388                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8389                            let taken = self.pop().to_boolean();
8390                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8391                            if taken == want {
8392                                pc = insn.a as usize;
8393                                continue;
8394                            }
8395                        }
8396                        // -- slot access -------------------------------------------------
8397                        // A load's slot is already an operand (see `insn::implicit_operand`);
8398                        // a captured one goes through its cell, which runs no script.
8399                        Opcode::GetLoc
8400                        | Opcode::GetLoc8
8401                        | Opcode::GetLoc0
8402                        | Opcode::GetLoc1
8403                        | Opcode::GetLoc2
8404                        | Opcode::GetLoc3 => {
8405                            let value = self.get_loc(insn.a as usize);
8406                            self.push(value);
8407                        }
8408                        Opcode::PutLoc
8409                        | Opcode::PutLoc8
8410                        | Opcode::PutLoc0
8411                        | Opcode::PutLoc1
8412                        | Opcode::PutLoc2
8413                        | Opcode::PutLoc3 => {
8414                            let value = self.pop();
8415                            self.put_loc(insn.a as usize, value);
8416                        }
8417                        Opcode::GetArg
8418                        | Opcode::GetArg0
8419                        | Opcode::GetArg1
8420                        | Opcode::GetArg2
8421                        | Opcode::GetArg3 => {
8422                            let value = self.get_arg(insn.a as usize);
8423                            self.push(value);
8424                        }
8425                        Opcode::PutArg
8426                        | Opcode::PutArg0
8427                        | Opcode::PutArg1
8428                        | Opcode::PutArg2
8429                        | Opcode::PutArg3 => {
8430                            let value = self.pop();
8431                            self.put_arg(insn.a as usize, value);
8432                        }
8433                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
8434                        // for why a non-hole own element is exactly the slow path's answer.
8435                        // The two operands are *peeked*, so a miss leaves the stack as the
8436                        // slow path expects to find it.
8437                        Opcode::GetArrayEl => {
8438                            // One lookup, not two. The guard used `if …is_some()` and the arm
8439                            // then called it again to get the value — two `peek`s, two
8440                            // `array_get`s and two `Value` clones for one element.
8441                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
8442                            // double call was the first version of the `get_field` fast path.
8443                            let Some(value) = self.fast_array_get() else {
8444                                return Ok(self.stop(pc));
8445                            };
8446                            // `a[i]` consumes both operands and leaves the element in their
8447                            // place: one `truncate` and one write, no `pop`/`push` pair.
8448                            let frame = self.frame_mut();
8449                            frame.stack.truncate(frame.stack.len() - 2);
8450                            frame.stack.push(value);
8451                        }
8452                        // `a[i] = v` on a dense array with an integer index: see
8453                        // `fast_array_set` for why the whole store is one step.
8454                        Opcode::PutArrayEl if self.fast_array_set() => {}
8455                        // `o.x` resolved from the inline cache without leaving the loop.
8456                        //
8457                        // The cache is keyed by `(receiver identity, atom, site)` and a
8458                        // monomorphic read re-validates the same chain every iteration, so
8459                        // each one used to cost a `stop(pc)` — a write of `pc` into the
8460                        // frame, a return out of this loop, a re-dispatch through `step` and
8461                        // a re-entry. `property:monomorphic` spent 18% in
8462                        // `read_field_cached` and 21% in `push`, both across that boundary.
8463                        //
8464                        // The site is `pc + width`, which is exactly the `next` the slow arm
8465                        // passes — the two must agree or every fast lookup misses and
8466                        // re-records the same entry forever.
8467                        //
8468                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8469                        // slow arm finds the receiver where it expects it.
8470                        // `name` resolved from the global-variable cache inside the loop.
8471                        //
8472                        // Same shape as `get_field` above and for the same reason: `get_var`
8473                        // was not in the fast loop, so reading a global — which `fib` does
8474                        // once per recursive call, for its own name — cost a `stop(pc)`, a
8475                        // return out of the loop, a `step` re-dispatch and a re-entry, before
8476                        // `get_global` even started its `scopes_are_plain` checks.
8477                        //
8478                        // Everything here is exactly `get_global`'s first branch: not lexical,
8479                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
8480                        // and lets the slow arm decide.
8481                        Opcode::GetVar => {
8482                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8483                                return Ok(self.stop(pc));
8484                            };
8485                            self.push(value);
8486                        }
8487                        Opcode::GetField | Opcode::GetField2 => {
8488                            let Some(value) =
8489                                self.fast_field_get(insn.a as usize, pc + insn.width())
8490                            else {
8491                                return Ok(self.stop(pc));
8492                            };
8493                            if insn.op == Opcode::GetField2 {
8494                                // `get_field2` keeps the receiver for the `call_method` that
8495                                // follows.
8496                                self.push(value);
8497                            } else {
8498                                // `get_field` replaces the receiver, so this is one store over
8499                                // the top slot rather than a `pop` and a `push`: the length
8500                                // never changes, so neither `Vec` arm has a capacity check or a
8501                                // drop to run beyond the one the overwrite itself does.
8502                                let frame = self.frame_mut();
8503                                match frame.stack.last_mut() {
8504                                    Some(slot) => *slot = value,
8505                                    None => return Ok(self.stop(pc)),
8506                                }
8507                            }
8508                        }
8509                        // -- constants ---------------------------------------------------
8510                        Opcode::PushMinus1
8511                        | Opcode::Push0
8512                        | Opcode::Push1
8513                        | Opcode::Push2
8514                        | Opcode::Push3
8515                        | Opcode::Push4
8516                        | Opcode::Push5
8517                        | Opcode::Push6
8518                        | Opcode::Push7
8519                        | Opcode::PushI8
8520                        | Opcode::PushI16
8521                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8522                        // -- stack shuffling ---------------------------------------------
8523                        Opcode::Drop => {
8524                            self.pop();
8525                        }
8526                        // -- arithmetic on two integers ----------------------------------
8527                        //
8528                        // The operands are *looked at* before they are popped, so a non-integer
8529                        // pair leaves the stack exactly as the slow path expects to find it.
8530                        Opcode::Add if self.numeric_pair() => {
8531                            let right = self.pop();
8532                            let left = self.pop();
8533                            // Exactly [`add_numbers`], which is what the slow arm reaches.
8534                            let answer = match (&left, &right) {
8535                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8536                                    Some(sum) => Value::Int(sum),
8537                                    None => Value::Float(*a as f64 + *b as f64),
8538                                },
8539                                _ => Value::Float(left.to_number() + right.to_number()),
8540                            };
8541                            self.push(answer);
8542                        }
8543                        Opcode::Sub
8544                        | Opcode::And
8545                        | Opcode::Or
8546                        | Opcode::Xor
8547                        | Opcode::Shl
8548                        | Opcode::Sar
8549                        | Opcode::Shr
8550                            if self.numeric_pair() =>
8551                        {
8552                            let right = self.pop();
8553                            let left = self.pop();
8554                            let answer =
8555                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
8556                            self.push(answer);
8557                        }
8558                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8559                            if self.numeric_pair() =>
8560                        {
8561                            let right = self.pop();
8562                            let left = self.pop();
8563                            let answer = self
8564                                .relational(insn.op, left, right)
8565                                .expect("numbers cannot throw");
8566                            self.push(answer);
8567                        }
8568                        // -- calls -------------------------------------------------------
8569                        //
8570                        // A plain call: `callee(arg0, …, argN) -> result`.
8571                        //
8572                        // This arm exists because of one measurement. `call:recursion` had
8573                        // **20.4% of its profile in `execute_instruction`** — the *slow*
8574                        // executor — and `fib`'s recursive call is the only thing in that
8575                        // function which is not a fast arm. Every call therefore left this
8576                        // loop via `stop()`, went through `step()`'s dispatch and
8577                        // `execute_instruction`'s match over every opcode, and came back here
8578                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8579                        //
8580                        // Two things make it safe to do here rather than only in the slow path:
8581                        //
8582                        // * the caller's `pc` is stored *before* the call, which is what
8583                        //   `step` does too — so when the callee returns, the caller resumes
8584                        //   after the call and not at it;
8585                        // * `check_memory` runs, because `step` calls it once per instruction
8586                        //   and a call allocates a frame, its locals and its cells. Skipping
8587                        //   the checkpoint here would let a `--memory-limit` script overshoot
8588                        //   by one call per instruction.
8589                        Opcode::Call
8590                        | Opcode::Call0
8591                        | Opcode::Call1
8592                        | Opcode::Call2
8593                        | Opcode::Call3 => {
8594                            let argc = self.argc_operand(insn.op, insn.a);
8595                            let next = pc + insn.width();
8596                            {
8597                                let frame = self
8598                                    .frames
8599                                    .last_mut()
8600                                    .expect("run_fast() is only called with a live frame");
8601                                // `at` is what a stack trace reports for this frame, so a throw
8602                                // inside the callee has to see the call site and not whatever
8603                                // the last `stop()` left there.
8604                                frame.at = insn.offset as usize;
8605                                frame.pc = next;
8606                            }
8607                            self.check_memory()?;
8608                            self.check_interrupt()?;
8609                            let args = self.pop_n(argc);
8610                            let callee = self.pop();
8611                            // A plain call has no receiver; the callee decides what to do with
8612                            // `undefined` (a sloppy function substitutes the global object).
8613                            if let Some(result) =
8614                                self.call_or_push(callee, Value::Undefined, args)?
8615                            {
8616                                // Native, host, generator, async, bound — no frame was pushed,
8617                                // so this loop is still describing the right function. `pc`
8618                                // is advanced by the loop tail like every other arm; only the
8619                                // frame's copy had to be written here, and it already was.
8620                                self.push(result);
8621                            } else {
8622                                // A bytecode callee: its frame is on top now, and `insns` and
8623                                // `pc` both belong to the caller. Start over on the new frame.
8624                                continue 'outer;
8625                            }
8626                        }
8627                        // -- return ------------------------------------------------------
8628                        Opcode::Return => {
8629                            let value = self.pop();
8630                            self.frame_mut().pc = pc + insn.width();
8631                            return Ok(Some(value));
8632                        }
8633                        Opcode::ReturnUndef => {
8634                            self.frame_mut().pc = pc + insn.width();
8635                            return Ok(Some(Value::Undefined));
8636                        }
8637                        // Everything else needs the slow path.
8638                        _ => return Ok(self.stop(pc)),
8639                    },
8640                }
8641                pc += insn.width();
8642            }
8643        }
8644    }
8645
8646    /// Whether the top two operand-stack values are both numbers.
8647    ///
8648    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8649    /// cannot run script, so the arm may not throw and may not change frames.
8650    fn numeric_pair(&self) -> bool {
8651        is_number(&self.peek(0)) && is_number(&self.peek(1))
8652    }
8653
8654    /// `a[i]` for a dense array and an integer index, without the string round trip.
8655    ///
8656    /// The slow path answers this by turning `i` into a string (`propkey` →
8657    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8658    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8659    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8660    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8661    /// without even the cheap `Int` formatting.
8662    ///
8663    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8664    /// unambiguously the one the slow path would give:
8665    ///
8666    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8667    ///   `2^32-1` is the length, not an index),
8668    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8669    ///   typed array or an ordinary object, all of which have their own rules),
8670    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8671    ///   starts walking the prototype chain, and `a[i]` on a hole must find
8672    ///   `Array.prototype[i]` if it exists rather than `undefined`.
8673    ///
8674    /// The last condition is the one that makes this safe rather than merely fast: an own
8675    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8676    /// `get_var` answered from the global-variable cache, or `None`.
8677    ///
8678    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8679    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8680    /// records nothing — the slow arm is about to walk the chain and record it.
8681    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8682        let frame = self.frame();
8683        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8684        // "Lexical" is presence in the realm's table, not the closure var's flag: a
8685        // `GlobalRef` forwarded through a nested function has its flags cleared.
8686        if self.realm.globals.contains_key(name) {
8687            return None;
8688        }
8689        if !self.scopes_are_plain() {
8690            return None;
8691        }
8692        let object = &self.realm.global;
8693        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8694        let cached = self.global_cache[site].as_ref()?;
8695        if !object.upgrades_to(&cached.object) {
8696            return None;
8697        }
8698        object.data_property_at(cached.index, name)
8699    }
8700
8701    /// `o.x` answered entirely from the inline cache, or `None`.
8702    ///
8703    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8704    /// about to do exactly that and recording it twice would rebuild the chain for every
8705    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8706    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8707    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8708        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8709        // an object receiver is a reference-count bump that the answer never needs.
8710        let frame = self.frame();
8711        let object = frame.stack.last()?;
8712        let Value::Object(target) = object else {
8713            return None;
8714        };
8715        // A proxy traps the lookup, so no cache entry ever describes it.
8716        if target.proxy_state().is_some() {
8717            return None;
8718        }
8719        let key = frame.code.atom_keys.get(atom)?;
8720        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8721        if cached.key != *key {
8722            return None;
8723        }
8724        Self::cached_hit(target, cached)
8725    }
8726
8727    fn fast_array_get(&self) -> Option<Value> {
8728        let Value::Int(index) = self.peek(0) else {
8729            return None;
8730        };
8731        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8732        // set for an `i32`.
8733        if index < 0 {
8734            return None;
8735        }
8736        let Value::Object(object) = self.peek(1) else {
8737            return None;
8738        };
8739        match object.array_get(index as usize) {
8740            Some(value) if !matches!(value, Value::Hole) => Some(value),
8741            _ => None,
8742        }
8743    }
8744
8745    /// `a[i] = v` on a dense array with an integer index, as one store.
8746    ///
8747    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8748    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8749    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8750    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8751    /// reference at the time it was measured (14.7x).
8752    ///
8753    /// Every condition here is one the slow path would also have to satisfy before
8754    /// storing into the element vector:
8755    ///
8756    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8757    ///   accepts as an index;
8758    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8759    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8760    ///   one inside a recorded descriptor, reports `false` and the caller stops.
8761    ///
8762    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8763    /// writes the own element too once `array_set` says it did.
8764    fn fast_array_set(&mut self) -> bool {
8765        // Every test runs *before* anything is popped: a refusal has to leave the stack
8766        // exactly as the slow path expects to find it. Popping first and reporting the
8767        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8768        // then ran the slow path with nothing to write.
8769        let Value::Int(index) = self.peek(1) else {
8770            return false;
8771        };
8772        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8773        if index < 0 {
8774            return false;
8775        }
8776        // Only a real array: a typed array's elements live in its buffer, a string-like
8777        // object has no element vector, and `array_set` on either does nothing.
8778        let Value::Object(object) = self.peek(2) else {
8779            return false;
8780        };
8781        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
8782            return false;
8783        }
8784        // A non-extensible array reports `false` here, but the *slow* path has to decide
8785        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
8786        // that with the key and the stack still intact.
8787        if !object.is_extensible() {
8788            return false;
8789        }
8790        // Inside the logical length, so the store cannot change `length`. Combined with
8791        // extensibility above, the only growth left for `array_set` is filling a hole in
8792        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
8793        // shape this fast path exists for. A store past the length would grow the array,
8794        // and whether that is allowed is the slow path's question.
8795        if index as usize >= object.array_length().unwrap_or(0) {
8796            return false;
8797        }
8798        // The bound `array_set` refuses past. Checking it here keeps that arm from having
8799        // to report a failure after the operands are gone.
8800        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
8801            return false;
8802        }
8803        let value = self.pop();
8804        self.pop();
8805        self.pop();
8806        object.array_store(self.heap, index as usize, value)
8807    }
8808
8809    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
8810    fn stop(&mut self, pc: usize) -> Option<Value> {
8811        self.frame_mut().pc = pc;
8812        None
8813    }
8814
8815    fn push(&mut self, value: Value) {
8816        self.frame_mut().stack.push(value);
8817    }
8818
8819    fn pop(&mut self) -> Value {
8820        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
8821    }
8822
8823    fn pop_n(&mut self, count: usize) -> Vec<Value> {
8824        let frame = self.frame_mut();
8825        let start = frame.stack.len().saturating_sub(count);
8826        frame.stack.split_off(start)
8827    }
8828
8829    fn peek(&self, back: usize) -> Value {
8830        let frame = self.frame();
8831        frame
8832            .stack
8833            .get(frame.stack.len().wrapping_sub(1 + back))
8834            .cloned()
8835            .unwrap_or(Value::Undefined)
8836    }
8837
8838    #[allow(clippy::too_many_lines)]
8839    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
8840        use Opcode::*;
8841        match op {
8842            // -- constants and stack shuffling -----------------------------
8843            Nop => {}
8844            PushMinus1 => self.push(Value::Int(-1)),
8845            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
8846                let value = match op {
8847                    Push0 => 0,
8848                    Push1 => 1,
8849                    Push2 => 2,
8850                    Push3 => 3,
8851                    Push4 => 4,
8852                    Push5 => 5,
8853                    Push6 => 6,
8854                    _ => 7,
8855                };
8856                self.push(Value::Int(value));
8857            }
8858            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
8859            PushBigintI32 => {
8860                // The immediate form of a `BigInt` literal; the reference has the same
8861                // split between this and a constant-pool entry.
8862                let value = crate::bigint::BigInt::from_i64(a as i64);
8863                self.push(self.bigint(value));
8864            }
8865            PushTrue => self.push(Value::Bool(true)),
8866            PushFalse => self.push(Value::Bool(false)),
8867            PushEmptyString => self.push(self.string("")),
8868            Undefined => self.push(Value::Undefined),
8869            Null => self.push(Value::Null),
8870            Object => {
8871                let proto = self.realm.object_proto.clone();
8872                self.push(Value::Object(self.new_object(Some(proto))));
8873            }
8874            PushThis => {
8875                let this = self.frame().this.clone();
8876                self.push(this);
8877            }
8878            PushConst | PushConst8 => {
8879                let value = self.constant(a as usize)?;
8880                self.push(value);
8881            }
8882            PushAtomValue => {
8883                let text = self.atom_wtf8(a as usize);
8884                self.push(self.string_wtf8(text));
8885            }
8886            Dup => {
8887                let value = self.peek(0);
8888                self.push(value);
8889            }
8890            Dup2 => {
8891                // `a b -> a b a b`
8892                let b = self.peek(0);
8893                let a = self.peek(1);
8894                self.push(a);
8895                self.push(b);
8896            }
8897            Dup3 => {
8898                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
8899                // prototype and key while reading the current value through them.
8900                let c = self.peek(0);
8901                let b = self.peek(1);
8902                let a = self.peek(2);
8903                self.push(a);
8904                self.push(b);
8905                self.push(c);
8906            }
8907            Swap => {
8908                // `a b -> b a`
8909                let bottom = self.pop();
8910                let top = self.pop();
8911                self.push(bottom);
8912                self.push(top);
8913            }
8914            Perm3 => {
8915                // `a b c -> b a c`, the reference's reordering for a spread method
8916                // call: `obj func array` becomes the `func this array` that `apply`
8917                // takes.
8918                let c = self.pop();
8919                let b = self.pop();
8920                let a = self.pop();
8921                self.push(b);
8922                self.push(a);
8923                self.push(c);
8924            }
8925            Dup1 => {
8926                let value = self.peek(1);
8927                self.push(value);
8928            }
8929            Drop => {
8930                self.pop();
8931            }
8932            Nip => {
8933                // `a b -> b`
8934                let top = self.pop();
8935                self.pop();
8936                self.push(top);
8937            }
8938            Perm4 => {
8939                // `obj prop a b -> a obj prop b`, the reference's reordering for a
8940                // postfix update of a computed element: it puts the *old* value
8941                // underneath the receiver and key so `put_array_el` can consume them
8942                // and leave the old value as the expression's result.
8943                let d = self.pop();
8944                let c = self.pop();
8945                let b = self.pop();
8946                let a = self.pop();
8947                self.push(c);
8948                self.push(a);
8949                self.push(b);
8950                self.push(d);
8951            }
8952            Insert2 => {
8953                // `obj a -> a obj a`
8954                let value = self.pop();
8955                let object = self.pop();
8956                self.push(value.clone());
8957                self.push(object);
8958                self.push(value);
8959            }
8960            Insert3 => {
8961                // `obj prop a -> a obj prop a`
8962                let value = self.pop();
8963                let key = self.pop();
8964                let object = self.pop();
8965                self.push(value.clone());
8966                self.push(object);
8967                self.push(key);
8968                self.push(value);
8969            }
8970            Insert4 => {
8971                // `this obj prop a -> a this obj prop a`
8972                //
8973                // `put_super_value` consumes all four and yields nothing, so the copy
8974                // underneath is what leaves the assignment an expression value.
8975                let value = self.pop();
8976                let key = self.pop();
8977                let object = self.pop();
8978                let receiver = self.pop();
8979                self.push(value.clone());
8980                self.push(receiver);
8981                self.push(object);
8982                self.push(key);
8983                self.push(value);
8984            }
8985            Swap2 => {
8986                // `a b c d -> c d a b`
8987                let d = self.pop();
8988                let c = self.pop();
8989                let b = self.pop();
8990                let a = self.pop();
8991                self.push(c);
8992                self.push(d);
8993                self.push(a);
8994                self.push(b);
8995            }
8996            Rot3l => {
8997                // `x a b -> a b x`
8998                let b = self.pop();
8999                let a = self.pop();
9000                let x = self.pop();
9001                self.push(a);
9002                self.push(b);
9003                self.push(x);
9004            }
9005            Rot3r => {
9006                // `a b c -> c a b`
9007                let c = self.pop();
9008                let b = self.pop();
9009                let a_value = self.pop();
9010                self.push(c);
9011                self.push(a_value);
9012                self.push(b);
9013            }
9014
9015            Rest => {
9016                // `...rest` in a parameter list: the arguments from index `a` on, as a
9017                // real array. It takes nothing off the stack — the arguments are in the
9018                // frame, not on it.
9019                let frame = self.frame();
9020                let from = a as usize;
9021                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9022                let array = self.new_array(collected);
9023                self.push(Value::Object(array));
9024            }
9025
9026            // -- slots ------------------------------------------------------
9027            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9028                let slot = self.slot_operand(op, a);
9029                let value = self.get_loc(slot);
9030                self.push(value);
9031            }
9032            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9033                let slot = self.slot_operand(op, a);
9034                let value = self.pop();
9035                self.put_loc(slot, value);
9036            }
9037            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9038                let slot = self.slot_operand(op, a);
9039                let value = self.pop();
9040                self.put_loc(slot, value.clone());
9041                self.push(value);
9042            }
9043            // The `_check` forms are the temporal dead zone: they throw when the
9044            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9045            // *reads*, so only the two writes may pop — mishandling that quietly
9046            // consumes the value the caller pushed just before.
9047            GetLocCheck => {
9048                let slot = self.slot_operand(op, a);
9049                let value = self.get_loc(slot);
9050                if matches!(value, Value::Uninitialized) {
9051                    return Err(self.dead_zone(slot, VarSlot::Loc));
9052                }
9053                self.push(value);
9054            }
9055            PutLocCheck | SetLocCheck => {
9056                let slot = self.slot_operand(op, a);
9057                let value = self.pop();
9058                if matches!(value, Value::Uninitialized) {
9059                    return Err(self.dead_zone(slot, VarSlot::Loc));
9060                }
9061                // The initialiser goes through `put_loc`, not this, so any store that
9062                // reaches here is a later assignment — which a `const` refuses.
9063                if self.is_read_only(slot, VarSlot::Loc) {
9064                    return Err(self.read_only(slot, VarSlot::Loc));
9065                }
9066                if op == SetLocCheck {
9067                    self.put_loc(slot, value.clone());
9068                    self.push(value);
9069                } else {
9070                    self.put_loc(slot, value);
9071                }
9072            }
9073            PutLocCheckInit => {
9074                // The one store that *initialises* a lexical slot: `this` in a derived
9075                // constructor, which only exists after `super()` has run. A second
9076                // initialisation is the error the reference reports as
9077                // "'this' can be initialized only once".
9078                let slot = self.slot_operand(op, a);
9079                let value = self.pop();
9080                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9081                    return Err(Signal::Throw(self.make_error(
9082                        "ReferenceError",
9083                        "'this' can be initialized only once",
9084                    )));
9085                }
9086                self.put_loc(slot, value);
9087            }
9088            CheckCtor => {
9089                // A class constructor may only run under `new`, which is what makes
9090                // `class A {}; A()` a TypeError.
9091                if matches!(self.frame().new_target, Value::Undefined) {
9092                    return Err(Signal::Throw(self.make_error(
9093                        "TypeError",
9094                        "class constructors must be invoked with 'new'",
9095                    )));
9096                }
9097            }
9098            InitCtor => {
9099                // The body a derived class gets when it declares no constructor:
9100                // forward every argument to the parent constructor, keeping `new.target`.
9101                if matches!(self.frame().new_target, Value::Undefined) {
9102                    return Err(Signal::Throw(self.make_error(
9103                        "TypeError",
9104                        "class constructors must be invoked with 'new'",
9105                    )));
9106                }
9107                let Some(callee) = self.current_callee() else {
9108                    return Err(Signal::Throw(
9109                        self.make_error("TypeError", "no constructor to inherit from"),
9110                    ));
9111                };
9112                let parent = callee.proto().map_or(Value::Null, Value::Object);
9113                let new_target = self.frame().new_target.clone();
9114                let args = self.frame().passed().to_vec();
9115                let result = self.construct(parent, new_target, args)?;
9116                self.push(result);
9117            }
9118            SetLocUninitialized => {
9119                let slot = self.slot_operand(op, a);
9120                self.put_loc(slot, Value::Uninitialized);
9121            }
9122            CloseLoc => {
9123                // "Close" a binding: give it a *fresh* cell holding the current
9124                // value. Closures created before this point keep the old cell and the
9125                // ones created after see the new one, which is what makes every
9126                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9127                // a block-scoped binding when the block ends.
9128                //
9129                // Clearing the slot instead (which this used to do) broke both: a
9130                // closure over a captured block variable read `undefined`, and a loop
9131                // terminated after one iteration.
9132                let slot = self.slot_operand(op, a);
9133                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9134                if index >= 0 {
9135                    let current = self.frame().cells[index as usize].get();
9136                    let fresh = self.new_cell(current);
9137                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9138                        *cell = fresh;
9139                    }
9140                }
9141            }
9142            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9143                let slot = self.slot_operand(op, a);
9144                let value = self.get_arg(slot);
9145                self.push(value);
9146            }
9147            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9148                let slot = self.slot_operand(op, a);
9149                let value = self.pop();
9150                self.put_arg(slot, value);
9151            }
9152            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9153                let slot = self.slot_operand(op, a);
9154                let value = self.pop();
9155                self.put_arg(slot, value.clone());
9156                self.push(value);
9157            }
9158
9159            // -- closure variables ------------------------------------------
9160            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9161                let slot = self.slot_operand(op, a);
9162                // A name a direct `eval` created shadows the binding the compiler chose.
9163                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9164                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9165                // and only a runtime lookup can know that.
9166                if let Some(cell) = self.eval_created_local(slot) {
9167                    self.push(cell.get());
9168                    return self.step();
9169                }
9170                let value = self.cell_value(slot)?;
9171                self.push(value);
9172            }
9173            GetVarRefCheck => {
9174                let slot = self.slot_operand(op, a);
9175                let value = self.cell_value(slot)?;
9176                if matches!(value, Value::Uninitialized) {
9177                    return Err(self.dead_zone(slot, VarSlot::Closure));
9178                }
9179                self.push(value);
9180            }
9181            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9182                let slot = self.slot_operand(op, a);
9183                let value = self.pop();
9184                if let Some(cell) = self.eval_created_local(slot) {
9185                    cell.set(value);
9186                    return self.step();
9187                }
9188                // Same rule as `PutLocCheck`: a checked store to a captured binding
9189                // refuses a `const` once its initialiser has run.
9190                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9191                    return Err(self.read_only(slot, VarSlot::Closure));
9192                }
9193                self.set_cell(slot, value)?;
9194            }
9195            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9196                let slot = self.slot_operand(op, a);
9197                let value = self.pop();
9198                if let Some(cell) = self.eval_created_local(slot) {
9199                    cell.set(value.clone());
9200                    self.push(value);
9201                    return self.step();
9202                }
9203                self.set_cell(slot, value.clone())?;
9204                self.push(value);
9205            }
9206
9207            // -- globals ----------------------------------------------------
9208            GetVar => {
9209                let value = self.get_global(a as usize)?;
9210                self.push(value);
9211            }
9212            GetVarUndef => {
9213                let value = self
9214                    .get_global(a as usize)
9215                    .or_else(|_| Ok(Value::Undefined))?;
9216                self.push(value);
9217            }
9218            DeleteVar => {
9219                // `delete name` for a name that is not a declared binding. A lexical
9220                // global lives in the reference table and cannot be deleted; anything
9221                // reachable only as a property of the global object is *implicit* —
9222                // `x = 1` with no declaration — and goes away if it is configurable,
9223                // which is what `delete` on an implicit global answers.
9224                let name = self.atom_text(a as usize);
9225                let global = self.realm.global.clone();
9226                let deleted = if self.realm.globals.contains_key(&name) {
9227                    false
9228                } else if global.own_property(&name).is_some() {
9229                    self.delete_property(&global, &name)?
9230                } else {
9231                    true
9232                };
9233                self.push(Value::Bool(deleted));
9234            }
9235            PutVar => {
9236                let value = self.pop();
9237                self.put_global(a as usize, value)?;
9238            }
9239            PutVarInit => {
9240                let slot = a as usize;
9241                let value = self.pop();
9242                self.init_global(slot, value)?;
9243            }
9244
9245            // -- arithmetic -------------------------------------------------
9246            Add => self.binary_add()?,
9247            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9248                let raw_right = self.pop();
9249                let raw_left = self.pop();
9250                // BigInt arithmetic is a separate path, and not only for the type of the
9251                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9252                // rather than a silent conversion.
9253                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9254                    let left = self.primitive_of(raw_left)?;
9255                    let right = self.primitive_of(raw_right)?;
9256                    let value = self.bigint_arithmetic(op, left, right)?;
9257                    self.push(value);
9258                } else {
9259                    let right = self.numeric(raw_right)?;
9260                    let left = self.numeric(raw_left)?;
9261                    self.push(arithmetic(op, left, right)?);
9262                }
9263            }
9264            Neg => {
9265                let raw = self.pop();
9266                match raw {
9267                    // A bigint negates exactly, however wide it is.
9268                    Value::BigInt(big) => {
9269                        let negated = big.negate();
9270                        self.push(self.bigint(negated));
9271                    }
9272                    other => {
9273                        let value = self.numeric(other)?;
9274                        self.push(negate(value));
9275                    }
9276                }
9277            }
9278            Plus => {
9279                let value = self.pop();
9280                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9281                // unary plus is defined to produce a *number*, which a bigint cannot
9282                // become without loss. It used to fall through to `NaN`.
9283                if matches!(value, Value::BigInt(_)) {
9284                    return Err(self.type_error("cannot convert bigint to number"));
9285                }
9286                let numeric = self.numeric_of(value)?;
9287                self.push(numeric);
9288            }
9289            Inc => {
9290                let raw = self.pop();
9291                let (_, updated) = self.advance_numeric(raw, true)?;
9292                self.push(updated);
9293            }
9294            Dec => {
9295                let raw = self.pop();
9296                let (_, updated) = self.advance_numeric(raw, false)?;
9297                self.push(updated);
9298            }
9299            PostInc | PostDec => {
9300                // `x -> x x+1`: the *new* value ends up on top, so the store the
9301                // compiler emits right after (`put_var`) writes the incremented
9302                // one, while the old value stays underneath for the expression's
9303                // own result. Getting this backwards makes `i++` a no-op, which
9304                // turns `while (i < 3)` into an infinite loop.
9305                let raw = self.pop();
9306                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9307                self.push(old);
9308                self.push(updated);
9309            }
9310            Not => {
9311                let raw = self.pop();
9312                match raw {
9313                    // `~x` on a bigint is `-x - 1`, exact at any width.
9314                    Value::BigInt(big) => {
9315                        let inverted = big.bitnot();
9316                        self.push(self.bigint(inverted));
9317                    }
9318                    other => {
9319                        let value = self.numeric(other)?;
9320                        self.push(Value::Int(!value.to_int32()));
9321                    }
9322                }
9323            }
9324            Lnot => {
9325                let value = self.pop();
9326                self.push(Value::Bool(!value.to_boolean()));
9327            }
9328
9329            // -- comparison -------------------------------------------------
9330            Lt | Lte | Gt | Gte => {
9331                let right = self.pop();
9332                let left = self.pop();
9333                let answer = self.relational(op, left, right)?;
9334                self.push(answer);
9335            }
9336            Eq | Neq => {
9337                let right = self.pop();
9338                let left = self.pop();
9339                let equal = self.abstract_equals(left, right)?;
9340                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9341            }
9342            StrictEq => {
9343                let right = self.pop();
9344                let left = self.pop();
9345                self.push(Value::Bool(left.strict_equals(&right)));
9346            }
9347            StrictNeq => {
9348                let right = self.pop();
9349                let left = self.pop();
9350                self.push(Value::Bool(!left.strict_equals(&right)));
9351            }
9352            IsUndefined => {
9353                // `=== undefined`, which is what a destructuring default tests. It is
9354                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9355                let value = self.pop();
9356                self.push(Value::Bool(matches!(value, Value::Undefined)));
9357            }
9358            IsUndefinedOrNull => {
9359                let value = self.pop();
9360                self.push(Value::Bool(value.is_nullish()));
9361            }
9362            Typeof => {
9363                let value = self.pop();
9364                self.push(self.string(value.type_of()));
9365            }
9366            ToObject => {
9367                // A destructuring *object* pattern starts here, which is why
9368                // `var {} = null` throws. Only `undefined` and `null` are refused; a
9369                // primitive is boxed.
9370                let value = self.pop();
9371                let object = self.object_from(&value)?;
9372                self.push(Value::Object(object));
9373            }
9374            Instanceof => {
9375                let constructor = self.pop();
9376                let object = self.pop();
9377                let answer = self.instance_of(&object, &constructor)?;
9378                self.push(Value::Bool(answer));
9379            }
9380            In => {
9381                let object = self.pop();
9382                let key = self.pop();
9383                let answer = self.has_property(&key, &object)?;
9384                self.push(Value::Bool(answer));
9385            }
9386
9387            // -- control flow -----------------------------------------------
9388            Goto | Goto8 | Goto16 => {
9389                self.frame_mut().pc = a as usize;
9390            }
9391            IfTrue | IfTrue8 => {
9392                let value = self.pop();
9393                if value.to_boolean() {
9394                    self.frame_mut().pc = a as usize;
9395                }
9396            }
9397            IfFalse | IfFalse8 => {
9398                let value = self.pop();
9399                if !value.to_boolean() {
9400                    self.frame_mut().pc = a as usize;
9401                }
9402            }
9403            Catch => {
9404                // Pushes the handler target onto the value stack; `unwind` finds it.
9405                self.push(Value::CatchOffset(a));
9406            }
9407            Gosub => {
9408                self.push(Value::ReturnAddress(next as u32));
9409                self.frame_mut().pc = a as usize;
9410            }
9411            Ret => {
9412                let value = self.pop();
9413                match value {
9414                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9415                    _ => {
9416                        return Err(Signal::Throw(
9417                            self.make_error("InternalError", "invalid return address"),
9418                        ));
9419                    }
9420                }
9421            }
9422            NipCatch => {
9423                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9424                // including the marker, keeping the top value.
9425                let top = self.pop();
9426                loop {
9427                    match self.pop() {
9428                        Value::CatchOffset(_) | Value::Undefined => break,
9429                        _ => {}
9430                    }
9431                    if self.frame().stack.is_empty() {
9432                        break;
9433                    }
9434                }
9435                self.push(top);
9436            }
9437            Throw => {
9438                let value = self.pop();
9439                return Err(Signal::Throw(value));
9440            }
9441            ThrowError => {
9442                let name = self.atom_text(a as usize);
9443                let (class, message) = match b {
9444                    0 => ("TypeError", format!("'{name}' is read-only")),
9445                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9446                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
9447                    // `delete super.x` is a syntax-level mistake the reference reports
9448                    // with this wording, not a property-access failure.
9449                    3 => (
9450                        "ReferenceError",
9451                        "unsupported reference to 'super'".to_string(),
9452                    ),
9453                    4 => (
9454                        "TypeError",
9455                        "iterator does not have a throw method".to_string(),
9456                    ),
9457                    5 => (
9458                        "ReferenceError",
9459                        "invalid assignment left-hand side".to_string(),
9460                    ),
9461                    _ => ("TypeError", format!("invalid operation on '{name}'")),
9462                };
9463                return Err(Signal::Throw(self.make_error(class, &message)));
9464            }
9465            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9466            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9467            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9468            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9469            Await => return Ok(Step::Suspend(SuspendKind::Await)),
9470            ReturnAsync => {
9471                // The reference's `return_async` returns `undefined` and lets the resume
9472                // machinery pick the real value off `sp[-1]`, which is how it tells a
9473                // completion from a suspension. Carrying the value explicitly says the
9474                // same thing without the implicit stack slot.
9475                let value = self.pop();
9476                return Ok(Step::Return(value));
9477            }
9478            Return => {
9479                let value = self.pop();
9480                return Ok(Step::Return(value));
9481            }
9482            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9483
9484            // -- calls ------------------------------------------------------
9485            Call | Call0 | Call1 | Call2 | Call3 => {
9486                let argc = self.argc_operand(op, a);
9487                let args = self.pop_n(argc);
9488                let callee = self.pop();
9489                // A plain call has no receiver; the callee decides what to do with
9490                // `undefined` (a sloppy function substitutes the global object).
9491                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9492                    self.push(result);
9493                }
9494            }
9495            CallConstructor => {
9496                // `constructor this_obj args… -> object`. The duplicated
9497                // constructor is `new.target`; this milestone does not expose it,
9498                // so the extra copy is simply consumed here.
9499                let argc = a as usize;
9500                let args = self.pop_n(argc);
9501                let new_target = self.pop();
9502                let callee = self.pop();
9503                let result = self.construct(callee, new_target, args)?;
9504                self.push(result);
9505            }
9506            CallMethod => {
9507                let argc = a as usize;
9508                let args = self.pop_n(argc);
9509                let callee = self.pop();
9510                let this = self.pop();
9511                if let Some(result) = self.call_or_push(callee, this, args)? {
9512                    self.push(result);
9513                }
9514            }
9515            Apply => {
9516                // `func this array -> result`, the spread-call form: the compiler
9517                // builds one array of arguments, and all that is left here is to
9518                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9519                let array = self.pop();
9520                let this = self.pop();
9521                let callee = self.pop();
9522                let args = self.array_like_to_args(&array)?;
9523                if a & 1 != 0 {
9524                    let result = self.construct(callee, this, args)?;
9525                    self.push(result);
9526                } else if let Some(result) = self.call_or_push(callee, this, args)? {
9527                    self.push(result);
9528                }
9529            }
9530            TailCall | TailCallMethod => {
9531                // `tail_call` is `call` whose result is returned immediately — the
9532                // reference jumps straight to `done` instead of storing the value and
9533                // running on. The callee still gets its own frame, so deep tail
9534                // recursion hits the stack limit exactly like plain recursion does;
9535                // marking this frame lets the return path unwind without needing
9536                // instructions after the call.
9537                let argc = if op == TailCallMethod {
9538                    a as usize
9539                } else {
9540                    self.argc_operand(op, a)
9541                };
9542                let args = self.pop_n(argc);
9543                let callee = self.pop();
9544                let this = if op == TailCallMethod {
9545                    self.pop()
9546                } else {
9547                    Value::Undefined
9548                };
9549                if let Value::Object(function) = &callee
9550                    && let Some((code, env)) = bytecode_of(function)
9551                {
9552                    // A generator or async body is not run here at all: calling it only
9553                    // *creates* the generator/coroutine, so it must not inherit this
9554                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
9555                    // onto `f`'s frame, and the first `yield`/`await` then reported
9556                    // "a generator body ran as an ordinary call".
9557                    if code.code.kind.is_generator() || code.code.kind.is_async() {
9558                        let value = self.call_value(callee, this, args)?;
9559                        return Ok(Step::Return(value));
9560                    }
9561                    self.frame_mut().tail = true;
9562                    self.push_frame(code, env, this, args, callee)?;
9563                    return Ok(Step::Continue);
9564                }
9565                // A native callee has no frame to reuse, so its value is simply
9566                // returned.
9567                let value = self.call_value(callee, this, args)?;
9568                return Ok(Step::Return(value));
9569            }
9570
9571            // -- objects ----------------------------------------------------
9572            SpecialObject => {
9573                let value = self.special_object(a)?;
9574                self.push(value);
9575            }
9576            PrivateSymbol => {
9577                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9578                // symbol each time it is evaluated, which is why the compiler evaluates it
9579                // once (at class definition) and stores it in a class-scope binding.
9580                let name = self.atom_text(a as usize);
9581                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9582                self.push(Value::Symbol(symbol));
9583            }
9584            GetPrivateField => {
9585                // `obj symbol -> value`. A missing private field is a TypeError, which is what
9586                // makes `#x` inaccessible on any object not built by this class.
9587                let symbol = self.pop();
9588                let object = self.pop();
9589                let value = self.read_private_field(&object, &symbol)?;
9590                self.push(value);
9591            }
9592            PutPrivateField => {
9593                // `obj value symbol ->`, and the store is a plain assignment to a property the
9594                // class already created, so there is no setter to consult.
9595                let symbol = self.pop();
9596                let value = self.pop();
9597                let object = self.pop();
9598                self.write_private_field(&object, &symbol, value)?;
9599            }
9600            DefinePrivateField => {
9601                // `obj symbol value -> obj`: a field initialiser creates the property, and
9602                // redefining one is a TypeError ("already exists").
9603                let value = self.pop();
9604                let symbol = self.pop();
9605                let object = self.pop();
9606                self.define_private_field(&object, &symbol, value)?;
9607                self.push(object);
9608            }
9609            PrivateIn => {
9610                // `obj key -> bool`: `#x in o`. The second operand decides which question is
9611                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9612                // is a field, so this is an own-property test; a *function* is a method or
9613                // accessor, so this is a brand check.
9614                let key = self.pop();
9615                let object = self.pop();
9616                let Some(target) = object.as_object() else {
9617                    return Err(Signal::Throw(
9618                        self.make_error("TypeError", "invalid 'in' operand"),
9619                    ));
9620                };
9621                let present = match &key {
9622                    Value::Object(_) => self.check_brand(target, &key)?,
9623                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9624                };
9625                self.push(Value::Bool(present));
9626            }
9627            AddBrand => {
9628                // `obj home ->`: create the class brand on `home` if it has none, then give
9629                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9630                // class definition: only the prototype's copy of the symbol is wanted.
9631                let home = self.pop();
9632                let object = self.pop();
9633                self.add_brand(&object, &home)?;
9634            }
9635            CheckBrand => {
9636                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9637                // Both stay, because the caller needs them — `nip` halves a read into its
9638                // value and `call_method` uses the pair as receiver and callee.
9639                let function = self.peek(0);
9640                let object = self.peek(1);
9641                let Some(target) = object.as_object() else {
9642                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9643                };
9644                if !self.check_brand(target, &function)? {
9645                    return Err(Signal::Throw(
9646                        self.make_error("TypeError", "invalid brand on object"),
9647                    ));
9648                }
9649            }
9650            GetLength => {
9651                // `get_length` is the `.length` read; an array and a string answer
9652                // from their own length, anything else from the property.
9653                let target = self.pop();
9654                let value = match &target {
9655                    Value::Object(object) => match object.array_length() {
9656                        Some(length) => crate::object::length_value(length),
9657                        None => self.read_field(&target, "length")?,
9658                    },
9659                    Value::String(text) => Value::Int(text.utf16_len() as i32),
9660                    _ => self.read_field(&target, "length")?,
9661                };
9662                self.push(value);
9663            }
9664            GetField | GetField2 => {
9665                let object = self.pop();
9666                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9667                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9668                // just below is what lets the borrow outlive the `&mut self` the lookup
9669                // needs — one refcount bump instead of a key clone plus its drop, on the
9670                // hottest property path there is: every `o.x` and every `o.m()` receiver.
9671                let code = self.frame().code.clone();
9672                let key = &code.atom_keys[a as usize];
9673                let value = self.read_field_cached(&object, key, next)?;
9674                if op == GetField2 {
9675                    self.push(object);
9676                }
9677                self.push(value);
9678            }
9679            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9680                let key = self.pop();
9681                let object = self.pop();
9682                let key = self.propkey(&key)?;
9683                let value = self.read_field_key(&object, &key)?;
9684                if matches!(op, GetArrayEl2 | GetArrayEl3) {
9685                    self.push(object);
9686                }
9687                if op == GetArrayEl3 {
9688                    // The key goes back in its *value* form, which the compiler stores
9689                    // into the target of a destructuring assignment.
9690                    self.push(match &key {
9691                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9692                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
9693                    });
9694                }
9695                self.push(value);
9696            }
9697            PutField => {
9698                let value = self.pop();
9699                let object = self.pop();
9700                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9701                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9702                // only reads. `this.value = …` is the write half of the hottest loop in
9703                // `property:method-call`, and `own_property_key` was 4.8% of the case.
9704                let code = self.frame().code.clone();
9705                let key = &code.atom_keys[a as usize];
9706                self.write_field_key(&object, key, value)?;
9707            }
9708            PutArrayEl => {
9709                let value = self.pop();
9710                let key = self.pop();
9711                let object = self.pop();
9712                let key = self.propkey(&key)?;
9713                self.write_field_key(&object, &key, value)?;
9714            }
9715            DefineField => {
9716                let value = self.pop();
9717                let object = self.pop();
9718                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9719                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9720                // three U+FFFD — a property under a different name from the one
9721                // `o["\uD800"]` reads.
9722                let code = self.frame().code.clone();
9723                let key = code.atom_keys[a as usize].clone();
9724                // No naming here. `{m: function(){}}` is named by the *compiler*, which
9725                // emits `set_name` — and only where `NamedEvaluation` applies, so
9726                // `{m: (0, function(){})}` stays anonymous. Naming every function that
9727                // reaches a property definition got that case wrong, and the compiler is
9728                // the only place that can tell the two apart.
9729                if let Some(target) = object.as_object() {
9730                    // Only an *array* stores into the element vector. A numeric key
9731                    // on an ordinary object is an ordinary property, which is what
9732                    // makes `{1: 'a'}` iterate as a key rather than disappear.
9733                    let stored = target.is_array()
9734                        && key.as_str().and_then(array_index).is_some_and(|index| {
9735                            target.array_set(self.heap, index as usize, value.clone())
9736                        });
9737                    if !stored {
9738                        target.define_data_key(&key, value);
9739                    }
9740                }
9741                self.push(object);
9742            }
9743            DefineArrayEl => {
9744                // `obj key value -> obj key`. The *value* form of the key is what goes
9745                // back on the stack — the compiler stores it into the pattern's binding —
9746                // so the symbol is not stringified on the way through.
9747                let value = self.pop();
9748                let key_value = self.pop();
9749                let object = self.peek(0);
9750                let key = self.propkey(&key_value)?;
9751                self.write_field_key(&object, &key, value)?;
9752                self.push(key_value);
9753            }
9754            SetHomeObject => {
9755                // `obj func -> obj func`: records the object a method was defined on so
9756                // `super` inside it resolves against that object's prototype.
9757                let function = self.peek(0);
9758                let home = self.peek(1);
9759                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9760                    function.set_home_object(Some(home.clone()));
9761                }
9762            }
9763            Regexp => {
9764                // `pattern flags -> regexp`. A literal compiles here rather than through the
9765                // constructor, which is both what the reference's dedicated opcode is for
9766                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9767                let flags = self.pop();
9768                let pattern = self.pop();
9769                let pattern = self.to_js_string(&pattern)?;
9770                let flags = self.to_js_string(&flags)?;
9771                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9772                self.push(Value::Object(object));
9773            }
9774            UsingDisposeInit => {
9775                // The error state a disposal accumulates into. Uninitialised means "no
9776                // failure yet"; anything else is the exception being propagated.
9777                self.push(Value::Uninitialized);
9778            }
9779            UsingCheck => {
9780                // `value -> value, method`: validate and snapshot the disposer now, so a
9781                // later change to `Symbol.dispose` cannot change what gets called, and so a
9782                // value that is not disposable fails before the body runs.
9783                let value = self.pop();
9784                let method = self.using_method_for(&value, a as u8 == 1)?;
9785                self.push(value);
9786                self.push(method);
9787            }
9788            UsingDispose => {
9789                // `error_state -> error_state'`: dispose the variable at `slot` — its value
9790                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
9791                // the pending error.
9792                let slot = self.slot_operand(op, a);
9793                let error_state = self.pop();
9794                let merged = self.using_dispose_once(slot, error_state)?;
9795                self.push(merged);
9796            }
9797            UsingDisposeMerge => {
9798                let new_error = self.pop();
9799                let error_state = self.pop();
9800                let merged = self.merge_dispose_error(new_error, error_state);
9801                self.push(merged);
9802            }
9803            UsingDisposeEnd => {
9804                // A disposal that failed replaces the block's normal completion, so the
9805                // error state becomes a real throw here rather than at the call site.
9806                let error_state = self.pop();
9807                if !matches!(error_state, Value::Uninitialized) {
9808                    return Err(Signal::Throw(error_state));
9809                }
9810            }
9811            UsingDisposeAsync => {
9812                // `await using` needs a promise to await and this runtime has no
9813                // `Promise` builtin, so the disposer is called synchronously and its result
9814                // discarded. That is correct for a disposer that returns nothing and is
9815                // reported as a gap rather than silently skipped.
9816                let slot = self.slot_operand(op, a);
9817                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
9818                self.push(error_state);
9819            }
9820            GetSuper => {
9821                // `obj -> obj's prototype`: the starting point of a `super` lookup.
9822                let object = self.pop();
9823                let proto = match &object {
9824                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
9825                    _ => Value::Null,
9826                };
9827                self.push(proto);
9828            }
9829            GetSuperValue => {
9830                // `receiver proto key -> value`, searching from `proto` but reporting to
9831                // `receiver`, which is what `super.g` must do for a getter to see `this`.
9832                //
9833                // Three values in, one out: the receiver is *consumed*, not left under the
9834                // result. Leaving it there was invisible for `super.x` in `return` or
9835                // statement position (the result is what gets popped) and corrupted the
9836                // frame everywhere else — `print(super.x)` left the class where the call
9837                // opcode looks for the receiver and called the class itself.
9838                let key = self.pop();
9839                let proto = self.pop();
9840                let receiver = self.pop();
9841                let value = self.super_read(&receiver, &proto, &key)?;
9842                self.push(value);
9843            }
9844            PutSuperValue => {
9845                // `receiver proto key value ->`: a store that starts at `proto` but
9846                // assigns to `receiver`.
9847                let value = self.pop();
9848                let key = self.pop();
9849                let proto = self.pop();
9850                let receiver = self.pop();
9851                self.super_write(&receiver, &proto, &key, value)?;
9852            }
9853            DefineClass => {
9854                // `parent ctor -> ctor proto`: the constructor becomes the class and a
9855                // fresh prototype object lands on top for the methods to go on.
9856                let name = self.atom_text(a as usize);
9857                let (ctor, proto) = self.define_class(&name, b)?;
9858                self.push(ctor);
9859                self.push(Value::Object(proto));
9860            }
9861            DefineClassComputed => {
9862                // `parent ctor key -> ctor proto key`: the computed name stays put so
9863                // `define_field`-style consumers can still read it.
9864                let key = self.pop();
9865                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9866                let (ctor, proto) = self.define_class(&name, b)?;
9867                self.push(ctor);
9868                self.push(Value::Object(proto));
9869                self.push(key);
9870            }
9871            DefineMethod => {
9872                let function = self.pop();
9873                let object = self.pop();
9874                // The exact key, like `define_field`: a quoted method key may hold an
9875                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
9876                // that `o["\uD800"]` finds.
9877                let code = self.frame().code.clone();
9878                let key = code.atom_keys[a as usize].clone();
9879                // A method's `[[HomeObject]]` is the object it was defined on, which is
9880                // what `super` inside it resolves against.
9881                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9882                    function.set_home_object(Some(object.clone()));
9883                }
9884                if let Some(text) = key.as_wtf8() {
9885                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
9886                } else {
9887                    self.set_function_name(
9888                        &function,
9889                        &key_with_accessor_prefix(&key.to_string(), b),
9890                    );
9891                }
9892                if let Some(array) = object.as_object() {
9893                    define_function_property(array, &key, function, b);
9894                }
9895                self.push(object);
9896            }
9897            DefineMethodComputed => {
9898                let function = self.pop();
9899                let key = self.pop();
9900                let object = self.pop();
9901                let key = self.propkey(&key)?;
9902                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
9903                // the name: `super` inside a computed method resolves through it. Without
9904                // this, `class B extends A { [k]() { return super.m() } }` read the
9905                // home object as null and threw.
9906                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9907                    function.set_home_object(Some(object.clone()));
9908                }
9909                match key.as_wtf8() {
9910                    Some(text) => {
9911                        let name = accessor_prefixed(text, a);
9912                        self.set_function_name_wtf8(&function, &name);
9913                    }
9914                    None => self.set_function_name(
9915                        &function,
9916                        &key_with_accessor_prefix(&key.to_string(), a),
9917                    ),
9918                }
9919                if let Some(array) = object.as_object() {
9920                    define_function_property(array, &key, function, a);
9921                }
9922                self.push(object);
9923            }
9924            SetProto => {
9925                let proto = self.pop();
9926                let object = self.pop();
9927                if let Some(target) = object.as_object() {
9928                    target.set_proto(proto.as_object().cloned());
9929                }
9930                self.push(object);
9931            }
9932            CopyDataProperties => {
9933                let exclusion = self.pop();
9934                let source = self.pop();
9935                let target = self.peek(0);
9936                self.copy_properties(&target, &source, &exclusion)?;
9937                self.push(source);
9938                self.push(exclusion);
9939            }
9940            ToPropkey => {
9941                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
9942                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
9943                // ordinary `"Symbol(b)"` property.
9944                let value = self.pop();
9945                let key = match self.propkey(&value)? {
9946                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
9947                    PropertyKey::String(text) => self.string_wtf8(text),
9948                };
9949                self.push(key);
9950            }
9951            SetName => {
9952                let function = self.peek(0);
9953                let name = self.atom_wtf8(a as usize);
9954                self.set_function_name_wtf8(&function, &name);
9955            }
9956            SetNameComputed => {
9957                let key = self.peek(1);
9958                let function = self.peek(0);
9959                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9960                self.set_function_name(&function, &name);
9961            }
9962
9963            // -- arrays -----------------------------------------------------
9964            ArrayFrom => {
9965                let count = a as usize;
9966                let elements = self.pop_n(count);
9967                let array = self.new_array(elements);
9968                self.push(Value::Object(array));
9969            }
9970            Append => {
9971                // `array index iterable -> array new_index`
9972                let iterable = self.pop();
9973                self.pop();
9974                let array = self.peek(0);
9975                let added = self.append_enumerate(&array, &iterable)?;
9976                self.push(Value::Int(added));
9977            }
9978
9979            // -- iteration --------------------------------------------------
9980            ForInStart => {
9981                let value = self.pop();
9982                let record = self.for_in_record(&value)?;
9983                self.push(Value::Object(record));
9984            }
9985            ForInNext => {
9986                // `record -> record key done`. The flag is *done*, not "found":
9987                // the compiler tests it with `if_false` to jump back into the body,
9988                // so reporting `true` while keys remain would end the loop at once.
9989                let record = self.peek(0);
9990                match self.for_in_advance(&record)? {
9991                    Some(key) => {
9992                        let text = self.string(key);
9993                        self.push(text);
9994                        self.push(Value::Bool(false));
9995                    }
9996                    None => {
9997                        self.push(Value::Undefined);
9998                        self.push(Value::Bool(true));
9999                    }
10000                }
10001            }
10002            ForOfStart => {
10003                let value = self.pop();
10004                let iterator = self.get_iterator(&value)?;
10005                self.push(iterator.object);
10006                self.push(iterator.next);
10007                self.push(Value::CatchOffset(0));
10008            }
10009            ForOfNext => {
10010                // `iter next catch_offset -> iter next catch_offset value done`.
10011                //
10012                // The operand is how many values sit *above* the iterator triple: a
10013                // destructuring rest element keeps its target array and running index
10014                // there while draining the iterator, so the triple is not at the top.
10015                let extra = a as usize;
10016                let iterator_slot = 2 + extra;
10017                // An exhausted iterator is replaced by `undefined` (see below), so a
10018                // second step must not call `next` again — `Array.from` and a
10019                // destructuring pattern both keep stepping past the end.
10020                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10021                    (Value::Undefined, true)
10022                } else {
10023                    let iterator = Iterator {
10024                        object: self.peek(iterator_slot),
10025                        next: self.peek(1 + extra),
10026                    };
10027                    self.iterator_step(&iterator)?
10028                };
10029                if done {
10030                    // The result's `value` is meaningless once the iterator is done:
10031                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10032                    // rather than binding the generator's return value.
10033                    let top = self.frame().stack.len() - 1 - iterator_slot;
10034                    self.frame_mut().stack[top] = Value::Undefined;
10035                    self.push(Value::Undefined);
10036                    self.push(Value::Bool(true));
10037                } else {
10038                    self.push(value);
10039                    self.push(Value::Bool(false));
10040                }
10041            }
10042            IteratorNext => {
10043                // `iter next catch val -> iter next catch val'`: replace the argument with
10044                // the result of `next(val)`. The triple below stays put, which is why the
10045                // three instructions of the `yield*` loop all address the stack the same way.
10046                let value = self.pop();
10047                let object = self.peek(2);
10048                let next = self.peek(1);
10049                let result = self.call_value(next, object, vec![value])?;
10050                self.push(result);
10051            }
10052            IteratorCall => {
10053                // `iter next catch val -> iter next catch val' flag`.
10054                //
10055                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10056                // The flag is `true` when the method was missing, which is how the
10057                // caller learns that the inner iterator cannot take part in the
10058                // unwinding.
10059                let value = self.pop();
10060                let object = self.peek(2);
10061                let key = if a & 1 != 0 { "throw" } else { "return" };
10062                let method = self.read_field(&object, key)?;
10063                if matches!(method, Value::Undefined | Value::Null) {
10064                    self.push(value);
10065                    self.push(Value::Bool(true));
10066                } else {
10067                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10068                    let result = self.call_value(method, object, argument)?;
10069                    self.push(result);
10070                    self.push(Value::Bool(false));
10071                }
10072            }
10073            IteratorCheckObject => {
10074                if !matches!(self.peek(0), Value::Object(_)) {
10075                    return Err(Signal::Throw(
10076                        self.make_error("TypeError", "iterator must return an object"),
10077                    ));
10078                }
10079            }
10080            IteratorClose => {
10081                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10082                // calling the iterator's `return` so it can release whatever it holds.
10083                //
10084                // The catch offset goes first, so an exception from `return` is not caught
10085                // by the loop being abandoned. This used to pop the three operands and call
10086                // nothing at all, which made `break` out of a `for of` invisible to an
10087                // iterator with a `return` method.
10088                self.pop();
10089                self.pop();
10090                let iterator = self.pop();
10091                if !matches!(iterator, Value::Undefined) {
10092                    let method = self.read_field(&iterator, "return")?;
10093                    if !matches!(method, Value::Undefined | Value::Null) {
10094                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10095                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10096                        if !matches!(result, Value::Object(_)) {
10097                            return Err(Signal::Throw(
10098                                self.make_error("TypeError", "iterator must return an object"),
10099                            ));
10100                        }
10101                    }
10102                }
10103            }
10104            Import => {
10105                // `import(specifier)`: the options slot is on top and is not read yet.
10106                let _options = self.pop();
10107                let specifier = self.pop();
10108                let promise = self.dynamic_import(specifier)?;
10109                self.push(promise);
10110            }
10111            ForAwaitOfStart => {
10112                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10113                // `Symbol.iterator` fallback.
10114                let value = self.pop();
10115                let iterator = self.get_async_iterator(&value)?;
10116                self.push(iterator.object);
10117                self.push(iterator.next);
10118                self.push(Value::CatchOffset(0));
10119            }
10120            ForAwaitOfNext => {
10121                // `for await` steps the iterator and leaves the *result* wrapped in a
10122                // promise, so the `await` the compiler emits right after this can suspend
10123                // on it. Unwrapping happens in `iterator_get_value_done`.
10124                let extra = a as usize;
10125                let iterator_slot = 2 + extra;
10126                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10127                    Value::Undefined
10128                } else {
10129                    let iterator = Iterator {
10130                        object: self.peek(iterator_slot),
10131                        next: self.peek(1 + extra),
10132                    };
10133                    let next = iterator.next.clone();
10134                    self.call_value(next, iterator.object, Vec::new())?
10135                };
10136                let promise = self.promise_resolve_value(result)?;
10137                self.push(promise);
10138            }
10139            IteratorGetValueDone => {
10140                // `result -> value done`. A missing result object means the iterator was
10141                // already exhausted, which the loop treats as `done`.
10142                let result = self.pop();
10143                let done = match &result {
10144                    Value::Object(object) => self
10145                        .get_property(object, "done")?
10146                        .is_some_and(|value| value.to_boolean()),
10147                    _ => true,
10148                };
10149                if done {
10150                    // Clear the iterator object so the `iterator_close` the loop emits on
10151                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10152                    // on normal completion, and this is where a normal completion is
10153                    // recognised — the same trick `for_of_next` uses, which also replaces
10154                    // the slot with `undefined`.
10155                    //
10156                    // The layout is fixed because only `for await` emits this opcode:
10157                    // `iter next catch [result]`, so the iterator is three below the top.
10158                    let depth = self.frame().stack.len();
10159                    if depth >= 3 {
10160                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10161                    }
10162                    self.push(Value::Undefined);
10163                    self.push(Value::Bool(true));
10164                } else {
10165                    let Value::Object(object) = &result else {
10166                        self.push(Value::Undefined);
10167                        self.push(Value::Bool(true));
10168                        return Ok(Step::Continue);
10169                    };
10170                    let value = self
10171                        .get_property(object, "value")?
10172                        .unwrap_or(Value::Undefined);
10173                    self.push(value);
10174                    self.push(Value::Bool(false));
10175                }
10176            }
10177
10178            Delete => {
10179                // `delete obj[key]`, where the key was just pushed. Deleting an array
10180                // index leaves a *hole* rather than closing the gap, and a
10181                // non-configurable property answers `false` and stays.
10182                let key = self.pop();
10183                let target = self.pop();
10184                let key = self.propkey(&key)?;
10185                let text_label = key.as_str().unwrap_or("").to_string();
10186                let deleted = match &target {
10187                    Value::Object(object) => {
10188                        let object = object.clone();
10189                        self.delete_property_key(&object, &key)?
10190                    }
10191                    // A string's `length` and its index properties are
10192                    // non-configurable, so deleting one answers `false`.
10193                    Value::String(text) => {
10194                        !(text_label == "length"
10195                            || array_index(&text_label)
10196                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10197                    }
10198                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10199                    // object to delete from, and only a *boxable* primitive has one.
10200                    Value::Undefined | Value::Null => {
10201                        return Err(Signal::Throw(
10202                            self.make_error("TypeError", "cannot convert to object"),
10203                        ));
10204                    }
10205                    // Any other primitive has no own properties; deleting nothing
10206                    // succeeds.
10207                    _ => true,
10208                };
10209                self.push(Value::Bool(deleted));
10210            }
10211
10212            // -- exceptions and bookkeeping ---------------------------------
10213            Fclosure | Fclosure8 => {
10214                let value = self.closure(a as usize)?;
10215                self.push(value);
10216            }
10217
10218            other => {
10219                let name = other.info().name;
10220                return Err(Signal::Throw(self.make_error(
10221                    "InternalError",
10222                    &format!("{name} is not implemented yet"),
10223                )));
10224            }
10225        }
10226        Ok(Step::Continue)
10227    }
10228
10229    // -- operand helpers ----------------------------------------------------
10230
10231    /// The slot index an operand names, taking short forms into account.
10232    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10233        use Opcode::*;
10234        match op {
10235            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10236            | SetVarRef0 => 0,
10237            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10238            | SetVarRef1 => 1,
10239            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10240            | SetVarRef2 => 2,
10241            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10242            | SetVarRef3 => 3,
10243            _ => a as usize,
10244        }
10245    }
10246
10247    /// The argument count of a call, taking `call0`…`call3` into account.
10248    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10249        use Opcode::*;
10250        match op {
10251            Call0 => 0,
10252            Call1 => 1,
10253            Call2 => 2,
10254            Call3 => 3,
10255            _ => a as usize,
10256        }
10257    }
10258
10259    /// The atom's name as a property key.
10260    ///
10261    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10262    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10263    /// `String::clone` was a heap allocation and a copy — per property access.
10264    /// The atom at `index`, as a property key.
10265    ///
10266    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10267    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10268    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10269    /// 5.3% of `property:monomorphic`.
10270    /// The atom's text, exactly — including an unpaired surrogate.
10271    ///
10272    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10273    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10274    /// `atom_text` below is for the other kind of use, where the atom is a key in the
10275    /// engine's own tables.
10276    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10277        self.frame()
10278            .code
10279            .code
10280            .atoms
10281            .get(index)
10282            .map(|atom| match atom {
10283                Atom::Str(text) => text.clone(),
10284                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10285                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10286                Atom::Null => crate::value::Wtf8::new(String::new()),
10287            })
10288            .unwrap_or_default()
10289    }
10290
10291    fn atom_text(&self, index: usize) -> String {
10292        self.frame()
10293            .code
10294            .code
10295            .atoms
10296            .get(index)
10297            .map(|atom| match atom {
10298                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10299                // compare it to an identifier, and a surrogate-bearing name is reachable
10300                // through `atom_wtf8` where it matters.
10301                Atom::Str(text) => text.to_string_lossy().into_owned(),
10302                Atom::Index(value) => value.to_string(),
10303                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10304                // `throw_error`, `delete super.x`) never read it.
10305                Atom::Null => String::new(),
10306            })
10307            .unwrap_or_default()
10308    }
10309
10310    fn constant(&mut self, index: usize) -> JsResult<Value> {
10311        let constant = self.frame().code.code.cpool.get(index).cloned();
10312        Ok(match &constant {
10313            Some(Constant::Number(number)) => Value::Float(*number),
10314            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10315            Some(Constant::BigInt { digits, radix }) => {
10316                match crate::bigint::BigInt::from_radix(digits, *radix) {
10317                    Some(big) => self.bigint(big),
10318                    // A literal the parser accepted is always parseable; a failure here
10319                    // would be a compiler bug, so it reads as an `InternalError`.
10320                    None => {
10321                        return Err(Signal::Throw(
10322                            self.make_error("InternalError", "unparseable bigint literal"),
10323                        ));
10324                    }
10325                }
10326            }
10327            Some(Constant::Function(_)) => {
10328                return Err(Signal::Throw(
10329                    self.make_error("InternalError", "a bare function constant"),
10330                ));
10331            }
10332            // A tagged template's call site: a frozen array of the cooked chunks with a
10333            // frozen `raw` array beside it, which is what `String.raw` reads back.
10334            Some(Constant::Template { cooked, raw }) => {
10335                let cooked_values: Vec<Value> = cooked
10336                    .iter()
10337                    .map(|chunk| match chunk {
10338                        Some(text) => self.string_wtf8(text.clone()),
10339                        None => Value::Undefined,
10340                    })
10341                    .collect();
10342                let raw_values: Vec<Value> =
10343                    raw.iter().map(|text| self.string(text.clone())).collect();
10344                let raw_array = self.new_array(raw_values);
10345                raw_array.set_extensible(false);
10346                let template = self.new_array(cooked_values);
10347                template.define(
10348                    "raw",
10349                    Property::with_attributes(Value::Object(raw_array), false, false),
10350                );
10351                template.set_extensible(false);
10352                Value::Object(template)
10353            }
10354            _ => Value::Undefined,
10355        })
10356    }
10357
10358    /// The reference cell a closure-variable slot names.
10359    ///
10360    /// Two kinds of binding share this addressing: a genuine closure variable
10361    /// (captured from an enclosing function) lives in this frame's environment,
10362    /// while a *declared global* lives in the realm so that a script, a function
10363    /// declaration and their uses all see one binding. A plain `Global` — an
10364    /// undeclared name that may be satisfied by the global object — has no cell at
10365    /// all, which is how `typeof x` still works for a name that does not exist.
10366    /// The reference cell a closure-variable slot names.
10367    ///
10368    /// The environment is resolved once, when the closure is built, and this is
10369    /// just the lookup afterwards. A *declared global* is in there too, pointing at
10370    /// the realm's cell, so a script, a hoisted function declaration and their uses
10371    /// all share one binding. A plain `Global` — a name the script never declared —
10372    /// is read and written through `get_var`/`put_var` by name instead, which is
10373    /// what lets the global object satisfy it.
10374    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10375        self.frame().env.cells.get(slot).cloned()
10376    }
10377
10378    /// Whether `slot` refers to a global binding through the reference table.
10379    ///
10380    /// A global's cell in the closure environment only exists so the slot has
10381    /// something to point at; the binding itself lives on the global object (a `var`)
10382    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10383    /// be routed, not performed on the placeholder.
10384    fn is_global_slot(&self, slot: usize) -> bool {
10385        self.frame()
10386            .code
10387            .code
10388            .closure_vars
10389            .get(slot)
10390            .is_some_and(|c| {
10391                // A module's declarations and imports are *not* globals: their cells are
10392                // the module environment's, filled by the host, so the placeholder routing
10393                // must not apply to them.
10394                matches!(
10395                    c.closure_type,
10396                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10397                )
10398            })
10399    }
10400
10401    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10402        if self.is_global_slot(slot) {
10403            return self.get_global(slot);
10404        }
10405        Ok(self
10406            .var_ref_cell(slot)
10407            .map(|cell| cell.get())
10408            .unwrap_or(Value::Undefined))
10409    }
10410
10411    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10412        // A function declaration is hoisted by storing into a global reference before
10413        // the body runs, so this path is also what puts it on the global object.
10414        if self.is_global_slot(slot) {
10415            return self.put_global(slot, value);
10416        }
10417        if let Some(cell) = self.var_ref_cell(slot) {
10418            cell.set(value);
10419        }
10420        Ok(())
10421    }
10422
10423    // -- closures -----------------------------------------------------------
10424
10425    /// Build the closure for the function constant `index`.
10426    ///
10427    /// Every entry in the child's closure table names where its binding lives in
10428    /// *this* frame: a local or argument slot that was marked captured, or a cell
10429    /// this frame is itself holding. That is how a variable three functions deep
10430    /// stays one binding.
10431    fn closure(&mut self, index: usize) -> JsResult<Value> {
10432        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10433        else {
10434            return Err(Signal::Throw(
10435                self.make_error("InternalError", "fclosure of a non-function"),
10436            ));
10437        };
10438        let mut cells = Vec::with_capacity(function.closure_vars.len());
10439        for closure_var in &function.closure_vars {
10440            let cell = match closure_var.closure_type {
10441                ClosureType::Arg => {
10442                    let slot = closure_var.var_idx as usize;
10443                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10444                }
10445                ClosureType::Local => {
10446                    let slot = closure_var.var_idx as usize;
10447                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10448                }
10449                ClosureType::Ref | ClosureType::GlobalRef => {
10450                    // A `Ref` names a cell in this frame's own closure table; a
10451                    // `GlobalRef` also starts there, then resolves by name below.
10452                    let slot = closure_var.var_idx as usize;
10453                    if let Some(cell) = self.frame().env.cells.get(slot) {
10454                        cells.push(cell.clone());
10455                        continue;
10456                    }
10457                    -1
10458                }
10459                _ => -1,
10460            };
10461            if cell >= 0 {
10462                let cell = self.frame().cells[cell as usize].clone();
10463                cells.push(cell);
10464                continue;
10465            }
10466            // A global: the cell is created on demand and shared through the realm,
10467            // so every function sees one binding.
10468            let name = closure_var.name.clone();
10469            let cell = match self.realm.globals.get(&name) {
10470                Some(cell) => cell.clone(),
10471                None => {
10472                    let cell = self.new_cell(Value::Undefined);
10473                    self.realm.globals.insert(name.clone(), cell.clone());
10474                    cell
10475                }
10476            };
10477            cells.push(cell);
10478        }
10479        let name = function.name.clone();
10480        // `.length` is the arity before any default or rest parameter, not the number
10481        // of slots a pattern parameter needs.
10482        let length = function.defined_args;
10483        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10484        // function and an arrow function do not. A *method* also does not, but that is not
10485        // known here — the method is marked when the `[[HomeObject]]` is attached (see
10486        // `set_home_object`), which is the moment it becomes a method.
10487        let function_kind = function.kind;
10488        let constructible =
10489            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10490        let code = Gc::new(self.heap, CompiledCode::new(*function));
10491        // A closure built inside an `eval` inherits the eval's view of the enclosing
10492        // bindings, so it can still read them once the eval has returned.
10493        let eval_scope = self
10494            .active_eval_scope
10495            .clone()
10496            .or_else(|| self.frame().env.eval_scope.clone());
10497        // A closure sees the variables a direct `eval` declared in the frame it was
10498        // created in — the ones declared before *and after* it, so the same object is
10499        // shared; only the phase bounds which of them are visible.
10500        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10501        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10502        let env = Gc::new(
10503            self.heap,
10504            ClosureEnv {
10505                cells,
10506                eval_scope,
10507                local_vars,
10508                local_phase,
10509            },
10510        );
10511        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10512        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10513        // the only thing that carries `Symbol.toStringTag`, so without it
10514        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10515        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10516        let proto = match function_kind {
10517            js_compile::bytecode::FunctionKind::AsyncGenerator => self
10518                .realm
10519                .async_generator_function_proto
10520                .clone()
10521                .or_else(|| self.realm.function_proto.clone().into()),
10522            js_compile::bytecode::FunctionKind::Generator => self
10523                .realm
10524                .generator_function_proto
10525                .clone()
10526                .or_else(|| self.realm.function_proto.clone().into()),
10527            js_compile::bytecode::FunctionKind::Async => self
10528                .realm
10529                .async_function_proto
10530                .clone()
10531                .or_else(|| self.realm.function_proto.clone().into()),
10532            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10533        };
10534        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10535        object.set_constructible(constructible);
10536        object.define(
10537            "length",
10538            Property::name_or_length(Value::Int(length as i32)),
10539        );
10540        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10541        // that checks the own-property descriptor fails if the property is missing.
10542        object.define("name", Property::name_or_length(self.string(name)));
10543        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10544        // when `[[Construct]]` is created, so a generator, an async function and an arrow
10545        // function have none of their own. Installing it unconditionally gave
10546        // `Array.fromAsync` (an async function) an own `prototype` property, which
10547        // `builtin.js` checks for absence.
10548        if constructible {
10549            self.install_function_prototype(&object);
10550        }
10551        Ok(Value::Object(object))
10552    }
10553
10554    // -- conversions used by the operators ----------------------------------
10555
10556    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10557        // `+x` is `ToNumber`, which for a string parses it and for an object runs
10558        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10559        // string, which then behaves differently in every later comparison.
10560        match value {
10561            Value::Int(_) | Value::Float(_) => Ok(value),
10562            other => Ok(Value::Float(self.to_js_number(&other)?)),
10563        }
10564    }
10565
10566    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10567    ///
10568    /// Returns the *converted* old value and the new one, because the two callers need
10569    /// different halves: `++x` yields the new value, while `x++` yields the old one and
10570    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10571    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10572    /// boolean.
10573    ///
10574    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10575    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10576    /// a bigint algorithm then ran exactly once.
10577    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10578        if let Value::BigInt(big) = &value {
10579            let one = crate::bigint::BigInt::from_i64(1);
10580            let next = if up { big.add(&one) } else { big.sub(&one) };
10581            return Ok((value, self.bigint(next)));
10582        }
10583        let old = self.numeric(value)?;
10584        let new = if up {
10585            increment(old.clone())
10586        } else {
10587            decrement(old.clone())
10588        };
10589        Ok((old, new))
10590    }
10591
10592    fn numeric(&mut self, value: Value) -> JsResult<Value> {
10593        // `ToNumber` on an object runs `ToPrimitive` first, which is how
10594        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10595        // heard at all. Reading the object's own tag instead (`other.to_number()`)
10596        // turned the whole operand into `NaN` and swallowed the exception.
10597        match value {
10598            Value::Int(_) | Value::Float(_) => Ok(value),
10599            other => Ok(Value::Float(self.to_js_number(&other)?)),
10600        }
10601    }
10602
10603    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10604    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10605        match value {
10606            Value::BigInt(big) => Ok((**big).clone()),
10607            // The reference words this the same way for every operator, so a failing
10608            // script reads identically; the operator itself adds nothing a caller can use.
10609            _ => Err(Signal::Throw(
10610                self.make_error("TypeError", "cannot convert bigint to number"),
10611            )),
10612        }
10613    }
10614
10615    /// Arithmetic where at least one operand is a `BigInt`.
10616    ///
10617    /// The two numeric types never mix, so a bigint paired with anything else is an error
10618    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10619    /// that the relational operators handle it separately.
10620    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10621        use Opcode::*;
10622        let a = self.bigint_operand(&left)?;
10623        let b = self.bigint_operand(&right)?;
10624        let result = match op {
10625            Add => a.add(&b),
10626            Sub => a.sub(&b),
10627            Mul => a.mul(&b),
10628            Div | Mod => {
10629                let Some((quotient, remainder)) = a.div_rem(&b) else {
10630                    return Err(Signal::Throw(
10631                        self.make_error("RangeError", "division by zero"),
10632                    ));
10633                };
10634                if op == Div { quotient } else { remainder }
10635            }
10636            Pow => {
10637                let Some(value) = a.pow(&b) else {
10638                    return Err(Signal::Throw(self.make_error(
10639                        "RangeError",
10640                        "BigInt exponent must be non-negative and not absurdly large",
10641                    )));
10642                };
10643                value
10644            }
10645            And => a.bitand(&b),
10646            Or => a.bitor(&b),
10647            Xor => a.bitxor(&b),
10648            Shl | Sar => {
10649                // A shift count is a `BigInt` here, and both directions are exact; a
10650                // negative count would be the other direction, which the spec forbids.
10651                let Some(count) = b.to_i64() else {
10652                    return Err(Signal::Throw(
10653                        self.make_error("RangeError", "BigInt shift count is too large"),
10654                    ));
10655                };
10656                if count < 0 {
10657                    return Err(Signal::Throw(self.make_error(
10658                        "RangeError",
10659                        "BigInt shift count must be non-negative",
10660                    )));
10661                }
10662                if op == Shl {
10663                    a.shl(count as u64)
10664                } else {
10665                    a.shr(count as u64)
10666                }
10667            }
10668            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10669            _ => {
10670                return Err(Signal::Throw(self.make_error(
10671                    "TypeError",
10672                    "BigInts have no unsigned right shift, use >> instead",
10673                )));
10674            }
10675        };
10676        Ok(self.bigint(result))
10677    }
10678
10679    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10680    ///
10681    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10682    /// is on the mathematical values, and nothing is rounded first.
10683    /// `<`, `<=`, `>`, `>=`.
10684    ///
10685    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10686    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10687    /// It is a `?`-returning function for exactly that reason: an object operand can run
10688    /// script, and script can throw. The old version compared `to_number` of the raw
10689    /// values, which answered `false` for every object instead of calling `valueOf` —
10690    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10691    /// never ran.
10692    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10693        // The hot arm first: `i < n` with both sides already integers. No conversion, no
10694        // call, nothing that can throw.
10695        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10696            let ordering = Some(left.cmp(right));
10697            return Ok(ordering_answer(op, ordering));
10698        }
10699        // Anything that can run script has to be converted first, in this order.
10700        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10701        {
10702            (
10703                self.to_primitive(left, Hint::Number)?,
10704                self.to_primitive(right, Hint::Number)?,
10705            )
10706        } else {
10707            (left, right)
10708        };
10709        let ordering = match (&left, &right) {
10710            // The loop condition `i < n` is integer against integer, and it runs once
10711            // per iteration of every loop in every program. Without this arm it took the
10712            // `to_number` path twice, which is a `match` plus a conversion each.
10713            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10714            (Value::String(a), Value::String(b)) => {
10715                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10716            }
10717            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10718            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10719            // is true even though `2.5` has no bigint form.
10720            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10721                let b = other.to_number();
10722                if b.is_nan() {
10723                    None
10724                } else {
10725                    compare_bigint_and_f64(a, b)
10726                }
10727            }
10728            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10729                let a = other.to_number();
10730                if a.is_nan() {
10731                    None
10732                } else {
10733                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10734                }
10735            }
10736            _ => left.to_number().partial_cmp(&right.to_number()),
10737        };
10738        Ok(ordering_answer(op, ordering))
10739    }
10740
10741    fn binary_add(&mut self) -> JsResult<()> {
10742        let right = self.pop();
10743        let left = self.pop();
10744        // Two integers add without any of the machinery below: no `ToPrimitive` (an
10745        // `Int` is already primitive), no string check, no bigint check, no allocation.
10746        // `x += 1` in a loop is the single most common instruction sequence in real
10747        // script, and it used to walk every one of those checks before reaching the
10748        // same `checked_add`.
10749        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10750            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10751            return Ok(());
10752        }
10753        let left = self.primitive_of(left)?;
10754        let right = self.primitive_of(right)?;
10755        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10756        // that check comes before the bigint one: `"" + 1n` is a string, not a
10757        // mixed-type error.
10758        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10759            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10760            // `TypeError`, the one place a symbol and a string do not mix.
10761            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10762            // between a copy and a rope from their lengths, and a rope is what turns
10763            // `text += "abc"` in a loop from quadratic into linear.
10764            if let (Value::String(left), Value::String(right)) = (&left, &right) {
10765                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10766                // reports as `InternalError: string too long`.
10767                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10768                    return Err(Signal::Throw(
10769                        self.make_error("InternalError", "string too long"),
10770                    ));
10771                };
10772                self.push(Value::String(Gc::new(self.heap, joined)));
10773                return Ok(());
10774            }
10775            // At least one operand was not a string, so `ToString` it. This rejects a
10776            // symbol, which is the one place a symbol and a string do not mix.
10777            let left = self.checked_to_wtf8(&left)?;
10778            let right = self.checked_to_wtf8(&right)?;
10779            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
10780            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
10781            let text = left.concat(&right);
10782            self.push(self.string_wtf8(text));
10783            return Ok(());
10784        }
10785        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
10786        // not a conversion.
10787        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
10788            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
10789            self.push(value);
10790            return Ok(());
10791        }
10792        let left = self.numeric(left)?;
10793        let right = self.numeric(right)?;
10794        self.push(add_numbers(left, right));
10795        Ok(())
10796    }
10797
10798    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
10799        self.to_primitive(value, Hint::Default)
10800    }
10801
10802    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
10803    ///
10804    /// The order depends on the hint: the "number" order tries `valueOf` first and
10805    /// `toString` second, the "string" order the other way round, and the default
10806    /// hint uses the number order. A result that is still an object is a `TypeError`,
10807    /// because no built-in `valueOf`/`toString` returns one.
10808    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
10809        let Value::Object(object) = &value else {
10810            return Ok(value);
10811        };
10812        // A Date overrides the default hint to mean "string", which is what
10813        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
10814        // this, `"" + new Date()` would print the milliseconds, not the date.
10815        let hint = if hint == Hint::Default && is_date_object(self, object) {
10816            Hint::String
10817        } else {
10818            hint
10819        };
10820        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
10821        // handed the hint as a string. This is the hook a Date uses for its default hint
10822        // and a script uses to take over conversion entirely.
10823        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
10824        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
10825            if !function.is_callable() {
10826                return Err(self.type_error("Symbol.toPrimitive is not a function"));
10827            }
10828            let hint = match hint {
10829                Hint::String => "string",
10830                Hint::Number => "number",
10831                Hint::Default => "default",
10832            };
10833            let hint = self.string(hint);
10834            let result = self.call_value(
10835                Value::Object(function),
10836                Value::Object(object.clone()),
10837                vec![hint],
10838            )?;
10839            if matches!(result, Value::Object(_)) {
10840                return Err(self.type_error("cannot convert object to primitive value"));
10841            }
10842            return Ok(result);
10843        }
10844        let order: [&str; 2] = match hint {
10845            Hint::String => ["toString", "valueOf"],
10846            Hint::Number | Hint::Default => ["valueOf", "toString"],
10847        };
10848        let receiver = object.clone();
10849        for method in order {
10850            if let Some(function) = self.get_property(&receiver, method)?
10851                && matches!(&function, Value::Object(object) if object.is_callable())
10852            {
10853                let result =
10854                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
10855                if !matches!(result, Value::Object(_)) {
10856                    return Ok(result);
10857                }
10858            }
10859        }
10860        Err(self.type_error("cannot convert object to primitive value"))
10861    }
10862
10863    /// `ToString` with the object case going through `ToPrimitive`.
10864    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
10865        if matches!(value, Value::Object(_)) {
10866            let primitive = self.to_primitive(value.clone(), Hint::String)?;
10867            return Ok(primitive.to_js_string());
10868        }
10869        Ok(value.to_js_string())
10870    }
10871
10872    /// `ToString` that keeps the string's code units instead of flattening them.
10873    ///
10874    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
10875    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
10876    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10877        if matches!(value, Value::Symbol(_)) {
10878            return Err(Signal::Throw(
10879                self.make_error("TypeError", "cannot convert symbol to string"),
10880            ));
10881        }
10882        // An object runs `ToPrimitive` first, which may itself produce a symbol.
10883        let value = self.to_primitive(value.clone(), Hint::String)?;
10884        match value {
10885            Value::Symbol(_) => Err(Signal::Throw(
10886                self.make_error("TypeError", "cannot convert symbol to string"),
10887            )),
10888            Value::String(text) => Ok(text.wtf8().clone()),
10889            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
10890        }
10891    }
10892
10893    /// `ToNumber` with the object case going through `ToPrimitive`.
10894    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
10895        let value = if matches!(value, Value::Object(_)) {
10896            self.to_primitive(value.clone(), Hint::Number)?
10897        } else {
10898            value.clone()
10899        };
10900        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
10901        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
10902        // `NaN` to stay total, and the operators check for the bigint themselves — but
10903        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
10904        // refuse, and answering `NaN` made them silently wrong instead.
10905        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
10906        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
10907        match value {
10908            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
10909            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
10910            other => Ok(other.to_number()),
10911        }
10912    }
10913
10914    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
10915    /// [`ElementType::write`].
10916    ///
10917    /// This is separated from the write because both conversions are observable script —
10918    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
10919    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
10920    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
10921    /// setters, and a plain `a[i] = v`.
10922    pub(crate) fn element_value(
10923        &mut self,
10924        element: crate::builtins::typedarray::ElementType,
10925        value: Value,
10926    ) -> JsResult<Value> {
10927        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
10928        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
10929        let primitive = match &value {
10930            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
10931            _ => value,
10932        };
10933        if element.is_bigint() {
10934            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
10935            Ok(Value::BigInt(Gc::new(self.heap, big)))
10936        } else {
10937            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
10938            Ok(Value::Float(self.to_js_number(&primitive)?))
10939        }
10940    }
10941
10942    /// `ToPropertyKey`: what a computed member access uses as its key.
10943    ///
10944    /// A symbol is returned as itself, never stringified — that is what keeps
10945    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
10946    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
10947        match value {
10948            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
10949            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
10950            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
10951            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
10952            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10953                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
10954                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
10955                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
10956                    other.to_js_string(),
10957                ))),
10958            },
10959            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
10960        }
10961    }
10962
10963    /// `ToPropertyKey` for the callers that can only use a string key.
10964    ///
10965    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
10966    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
10967    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
10968    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
10969    /// program continues with a value nobody asked for.
10970    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10971        use crate::value::Wtf8;
10972        Ok(match value {
10973            // A string key keeps its code units. Going through a lossy `String` would make
10974            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
10975            Value::String(text) => text.wtf8().clone(),
10976            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
10977            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
10978            // falling back to its `ToString` would print `[object Object]`.
10979            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10980                Value::String(text) => text.wtf8().clone(),
10981                other => Wtf8::new(other.to_js_string()),
10982            },
10983            other => Wtf8::new(other.to_js_string()),
10984        })
10985    }
10986
10987    // -- object operations used by instructions -----------------------------
10988
10989    /// Read `object[key]`, returning `undefined` when the property is missing.
10990    ///
10991    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
10992    /// primitive (looking through its prototype) as well as an object — which is what
10993    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
10994    /// argument needs too.
10995    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
10996        self.read_field_key(object, &PropertyKey::from(key))
10997    }
10998
10999    /// [`Interp::read_field`] with a key that may be a symbol.
11000    ///
11001    /// A symbol key never reaches the string shortcuts: a string's `length` and its
11002    /// indices are string properties, and a symbol named `length` is a different
11003    /// property that a string primitive cannot have.
11004    /// [`Interp::read_field_key`], with an inline cache in front of it.
11005    ///
11006    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11007    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11008    /// without this the engine walked the chain and compared ~40 property names on each
11009    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11010    ///
11011    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11012    /// missing property. Those answers depend on running code or on state the guard below
11013    /// does not cover, and a wrong answer here is far more expensive than a lookup.
11014    ///
11015    /// A hit is re-validated against the *whole* walked chain, not just the level that
11016    /// answered: the receiver and every prototype down to that level must still be the same
11017    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11018    /// property-table *lengths* — which is what catches a property appearing on an
11019    /// intermediate prototype and shadowing the cached one.
11020    pub fn read_field_cached(
11021        &mut self,
11022        object: &Value,
11023        key: &PropertyKey,
11024        slot: usize,
11025    ) -> JsResult<Value> {
11026        let index = Self::field_cache_slot(object, key, slot);
11027        let Value::Object(target) = object else {
11028            return self.read_field_key(object, key);
11029        };
11030        if target.proxy_state().is_some() {
11031            return self.read_field_key(object, key);
11032        }
11033        if let Some(cached) = &self.field_cache[index]
11034            && cached.key == *key
11035            && let Some(value) = Self::cached_hit(target, cached)
11036        {
11037            return Ok(value);
11038        }
11039        let value = self.read_field_key(object, key)?;
11040        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11041        Ok(value)
11042    }
11043
11044    /// Whether a cache entry still describes this lookup, and if so the value.
11045    ///
11046    /// The guard is the whole point of the entry: identity plus property-table length for
11047    /// every level walked. Re-checked per level rather than once at the receiving end,
11048    /// because a shadowing property can appear anywhere along the chain.
11049    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11050        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11051        // starts with: a clone is a reference-count bump and a drop, and for
11052        // `property:monomorphic` every single hit takes only this arm.
11053        let (weak, len) = cached.chain[0].as_ref()?;
11054        if !target.upgrades_to(weak) {
11055            return None;
11056        }
11057        if cached.level == 0 {
11058            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11059            return target.cached_property_at(cached.index, &cached.key, *len);
11060        }
11061        if target.props_len() != *len {
11062            return None;
11063        }
11064        let mut level = 1;
11065        let mut current = target.proto()?;
11066        loop {
11067            let (weak, len) = cached.chain[level].as_ref()?;
11068            if !current.upgrades_to(weak) || current.props_len() != *len {
11069                return None;
11070            }
11071            if level == cached.level as usize {
11072                // The level that answered: the value is only reusable while the key is
11073                // still there and still a plain data property.
11074                return current.cached_data_property(cached.index, &cached.key);
11075            }
11076            current = current.proto()?;
11077            level += 1;
11078        }
11079    }
11080
11081    /// Build a cache entry for a lookup that just went through the slow path.
11082    ///
11083    /// Records the chain only when the answer came from a plain data property at a level
11084    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11085    /// costs the next lookup the walk it would have cost anyway.
11086    fn record_field_lookup(
11087        target: &Gc<JsObject>,
11088        key: &PropertyKey,
11089        _value: Value,
11090    ) -> Option<FieldCache> {
11091        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11092            [None, None, None];
11093        let mut current = target.clone();
11094        for level in 0..MAX_CACHED_CHAIN {
11095            chain[level] = Some((current.downgrade(), current.props_len()));
11096            if let Some((found, _)) = current.own_property_index(key) {
11097                // `own_property_index` declines an accessor and a hole, which is exactly
11098                // the set that must not be cached.
11099                return Some(FieldCache {
11100                    key: key.clone(),
11101                    index: found,
11102                    level: level as u8,
11103                    chain,
11104                });
11105            }
11106            current = current.proto()?;
11107        }
11108        None
11109    }
11110
11111    /// Which cache slot a lookup uses.
11112    ///
11113    /// Mixes the object's address, the name and the site, so that two properties of one
11114    /// object, and one property of two objects, land in different slots — which is what lets
11115    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11116    /// other iteration.
11117    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11118        let mut hash = match object {
11119            Value::Object(object) => object.address(),
11120            _ => 0,
11121        };
11122        hash = hash
11123            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11124            .rotate_left(17)
11125            .wrapping_add(key.hash_code());
11126        hash = hash.wrapping_add(site.wrapping_mul(31));
11127        // The table is a power of two, so the low bits are the slot.
11128        hash & (FIELD_CACHE_SLOTS - 1)
11129    }
11130
11131    /// Read `key` from `object`, without the inline cache.
11132    ///
11133    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11134    /// prototype chain, while the cached form answers an own data property from memory.
11135    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11136        let text = key.as_str().unwrap_or("");
11137        let Value::Object(object) = object else {
11138            // Reading a property of `undefined`/`null` is the classic TypeError.
11139            if object.is_nullish() {
11140                return Err(Signal::Throw(self.make_error(
11141                    "TypeError",
11142                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11143                )));
11144            }
11145            // A string has `length` and index access without being boxed.
11146            if let Value::String(value) = object {
11147                if text == "length" {
11148                    return Ok(Value::Int(value.utf16_len() as i32));
11149                }
11150                if let Some(index) = array_index(text) {
11151                    return Ok(match value.wtf8().unit_at(index as usize) {
11152                        Some(unit) => self.string_wtf8(unit),
11153                        None => Value::Undefined,
11154                    });
11155                }
11156            }
11157            // A property of a primitive is looked up on its prototype: this is what
11158            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11159            let prototype = match object {
11160                Value::String(_) => self.realm.string_proto.clone(),
11161                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11162                Value::Bool(_) => self.realm.boolean_proto.clone(),
11163                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11164                // `sym.description` reads through the prototype, not off the symbol.
11165                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11166                // …and a bigint's on `BigInt.prototype`, which is how
11167                // `(255n).toString(16)` reaches its method.
11168                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11169                _ => None,
11170            };
11171            if let Some(prototype) = prototype
11172                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11173            {
11174                return Ok(value);
11175            }
11176            return Ok(Value::Undefined);
11177        };
11178        Ok(self
11179            .get_property_key(object, key)?
11180            .unwrap_or(Value::Undefined))
11181    }
11182
11183    /// The `#name` a private symbol stands for, for error messages.
11184    ///
11185    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11186    /// was made from.
11187    fn private_name(symbol: &Value) -> Option<String> {
11188        match symbol {
11189            Value::Symbol(symbol) if symbol.is_private() => Some(
11190                symbol
11191                    .description()
11192                    .map(|text| text.to_string())
11193                    .unwrap_or_default(),
11194            ),
11195            _ => None,
11196        }
11197    }
11198
11199    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11200    ///
11201    /// Every private-field opcode takes the symbol the class stored in its own scope; a
11202    /// non-symbol here would be a compiler bug, and the reference guards it with
11203    /// `JS_ThrowTypeErrorNotASymbol`.
11204    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11205        match symbol {
11206            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11207            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11208        }
11209    }
11210
11211    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11212    ///
11213    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11214    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11215    /// would hit if the parser did not reject it first.
11216    fn define_private_field(
11217        &mut self,
11218        object: &Value,
11219        symbol: &Value,
11220        value: Value,
11221    ) -> JsResult<()> {
11222        let key = self.private_key(symbol)?;
11223        let Some(target) = object.as_object() else {
11224            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11225        };
11226        if !target.is_extensible() {
11227            return Err(Signal::Throw(
11228                self.make_error("TypeError", "object is not extensible"),
11229            ));
11230        }
11231        if target.own_property_key(&key).is_some() {
11232            let name = Self::private_name(symbol).unwrap_or_default();
11233            return Err(Signal::Throw(self.make_error(
11234                "TypeError",
11235                &format!("private class field '{name}' already exists"),
11236            )));
11237        }
11238        target.define_data_key(&key, value);
11239        Ok(())
11240    }
11241
11242    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11243    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11244        let key = self.private_key(symbol)?;
11245        let Some(target) = object.as_object() else {
11246            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11247        };
11248        match target.own_property_key(&key) {
11249            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11250            None => {
11251                let name = Self::private_name(symbol).unwrap_or_default();
11252                Err(Signal::Throw(self.make_error(
11253                    "TypeError",
11254                    &format!("private class field '{name}' does not exist"),
11255                )))
11256            }
11257        }
11258    }
11259
11260    /// `JS_SetPrivateField`: the store half of the same rule.
11261    fn write_private_field(
11262        &mut self,
11263        object: &Value,
11264        symbol: &Value,
11265        value: Value,
11266    ) -> JsResult<()> {
11267        let key = self.private_key(symbol)?;
11268        let Some(target) = object.as_object() else {
11269            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11270        };
11271        if target.write_value_key(&key, value) {
11272            return Ok(());
11273        }
11274        let name = Self::private_name(symbol).unwrap_or_default();
11275        Err(Signal::Throw(self.make_error(
11276            "TypeError",
11277            &format!("private class field '{name}' does not exist"),
11278        )))
11279    }
11280
11281    /// The `in` half: does `object` have this private field?
11282    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11283    ///
11284    /// The symbol is created once per class — the first `add_brand` on a given home object
11285    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11286    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11287    /// emit for the *instance* brand passes null because all it wants is the symbol.
11288    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11289        let Some(home_object) = home.as_object() else {
11290            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11291        };
11292        let symbol = match home_object.private_brand() {
11293            Some(symbol) => symbol,
11294            None => {
11295                let symbol = Gc::new(
11296                    self.heap,
11297                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11298                );
11299                home_object.set_private_brand(symbol.clone());
11300                symbol
11301            }
11302        };
11303        let Some(target) = object.as_object() else {
11304            // Not an object: nothing to brand. The reference does the same, and `undefined`
11305            // here would otherwise turn a field initialiser into a TypeError.
11306            return Ok(());
11307        };
11308        if !target.is_extensible() {
11309            return Err(Signal::Throw(
11310                self.make_error("TypeError", "object is not extensible"),
11311            ));
11312        }
11313        if target.carries_brand(&symbol) {
11314            return Err(Signal::Throw(
11315                self.make_error("TypeError", "private method is already present"),
11316            ));
11317        }
11318        target.add_brand(symbol);
11319        Ok(())
11320    }
11321
11322    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11323    ///
11324    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11325    /// decides whether to throw.
11326    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11327        let Some(function) = function.as_object() else {
11328            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11329        };
11330        let Some(home) = function.home_object() else {
11331            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11332        };
11333        let Some(brand) = home.private_brand() else {
11334            return Err(Signal::Throw(
11335                self.make_error("TypeError", "expecting <brand> private field"),
11336            ));
11337        };
11338        Ok(object.carries_brand(&brand))
11339    }
11340
11341    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11342        let Value::Object(object) = object else {
11343            return Err(Signal::Throw(self.make_error(
11344                "TypeError",
11345                &format!("cannot set property '{key}' of {}", object.to_js_string()),
11346            )));
11347        };
11348        // The write half of the property inline cache, in effect: an own, writable,
11349        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11350        // decide — no prototype walk (an own property shadows the chain before a setter
11351        // there could matter), no extensibility check (the object already has the key),
11352        // and no `[[DefineOwnProperty]]`.
11353        //
11354        // `this.value = …` inside a method is the whole write side of
11355        // `property:method-call`, and it was reaching `set_property_with_key` with its
11356        // proxy test, its typed-array test, its array-index test and finally a linear
11357        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11358        //
11359        // Every disqualifier is checked here: a proxy traps the set, an array index and
11360        // `length` live outside the property table, and a typed array's element is stored
11361        // through its view's element type.
11362        if object.proxy_state().is_none()
11363            && !object.is_array()
11364            && object.typed_array_element_type().is_none()
11365            && object.write_value_key(key, value.clone())
11366        {
11367            return Ok(());
11368        }
11369        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11370        let on_failure = if self.frame().code.code.strict {
11371            DeleteFailure::Throw
11372        } else {
11373            DeleteFailure::Ignore
11374        };
11375        self.set_property_with_key(object, key, value, on_failure)
11376    }
11377
11378    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11379    ///
11380    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11381    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11382    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11383    /// `Number.parseInt(sym)` — so those callers use this instead.
11384    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11385        if matches!(value, Value::Symbol(_)) {
11386            return Err(Signal::Throw(
11387                self.make_error("TypeError", "cannot convert symbol to string"),
11388            ));
11389        }
11390        // An object runs `ToPrimitive` first, which may itself produce a symbol —
11391        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11392        let value = self.to_primitive(value.clone(), Hint::String)?;
11393        if matches!(value, Value::Symbol(_)) {
11394            return Err(Signal::Throw(
11395                self.make_error("TypeError", "cannot convert symbol to string"),
11396            ));
11397        }
11398        Ok(value.to_js_string())
11399    }
11400
11401    /// `ToPropertyKey` for a builtin that takes a key argument.
11402    ///
11403    /// Fallible: a key whose `toString` throws has to propagate that error, both for
11404    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11405    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11406    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11407    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11408        self.propkey(value)
11409    }
11410
11411    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11412    ///
11413    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11414    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11415    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11416    /// `RangeError` — and why this cannot be a plain `ToNumber`.
11417    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11418        let number = match value {
11419            Value::Int(number) => *number as f64,
11420            Value::Float(number) => *number,
11421            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11422            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11423            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11424            // reference answers 0.
11425            Value::Null | Value::Bool(_) => value.to_number(),
11426            _ => {
11427                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11428                match primitive {
11429                    Value::Int(number) => number as f64,
11430                    Value::Float(number) => number,
11431                    other => {
11432                        // `ToString` then `ToNumber`, so a string length goes through the
11433                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
11434                        // `Value::to_number` on the string already implements exactly that.
11435                        let text = self.to_js_string(&other)?;
11436                        crate::value::string_to_number(&text)
11437                    }
11438                }
11439            }
11440        };
11441        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11442        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11443        // is a `RangeError`, not `0`.
11444        if !number.is_finite()
11445            || number.fract() != 0.0
11446            || !(0.0..=u32::MAX as f64).contains(&number)
11447        {
11448            return Err(self.range_error("invalid array length"));
11449        }
11450        Ok(number as u32)
11451    }
11452
11453    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11454    /// `Object.getOwnPropertySymbols` put in their result array.
11455    pub fn key_value(&self, key: &PropertyKey) -> Value {
11456        match key {
11457            PropertyKey::String(text) => self.string_wtf8(text.clone()),
11458            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11459        }
11460    }
11461
11462    /// Fill in a String exotic object: `_value`, `length` and the index properties.
11463    ///
11464    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11465    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11466    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11467    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11468    /// the two paths had drifted; this is the one both now use.
11469    ///
11470    /// The indices are *code units*, so an astral character occupies two of them — the
11471    /// same rule `s.length` and `s[i]` follow.
11472    /// Give an already-created object the internal slot that makes it a wrapper of
11473    /// `value`, so the primitive's prototype methods work on it.
11474    ///
11475    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11476    /// which are wrappers of their own type holding the empty value.
11477    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11478        self.internal_set(object, "_value", value);
11479    }
11480
11481    pub(crate) fn init_string_wrapper(
11482        &mut self,
11483        object: &Gc<JsObject>,
11484        text: &Gc<crate::value::JsString>,
11485    ) {
11486        object.define(
11487            "length",
11488            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11489        );
11490        for index in 0..text.utf16_len() {
11491            if let Some(unit) = text.wtf8().unit_at(index) {
11492                object.define(
11493                    &index.to_string(),
11494                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11495                    Property::with_attributes(self.string_wtf8(unit), false, true),
11496                );
11497            }
11498        }
11499        object.define_key(
11500            &self.internal_slot("_value"),
11501            Property::with_attributes(Value::String(text.clone()), false, false),
11502        );
11503    }
11504
11505    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11506    ///
11507    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11508    /// throws. The wrapper carries its primitive in `_value` — the same slot
11509    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11510    /// on a boxed value no constructor ever built.
11511    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11512        let (prototype, primitive) = match value {
11513            Value::Object(object) => return Ok(object.clone()),
11514            Value::String(text) => {
11515                let object = self.new_object(self.realm.string_proto.clone());
11516                self.init_string_wrapper(&object, text);
11517                return Ok(object);
11518            }
11519            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11520            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11521            // A symbol and a bigint box into wrappers whose methods live on
11522            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11523            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11524            // branch below instead produced an object with *no* prototype, so those
11525            // methods were unreachable on a box.
11526            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11527            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11528            Value::Undefined | Value::Null => {
11529                return Err(Signal::Throw(self.make_error(
11530                    "TypeError",
11531                    &format!("cannot convert {} to object", value.to_js_string()),
11532                )));
11533            }
11534            _ => (None, value.clone()),
11535        };
11536        let object = self.new_object(prototype);
11537        self.internal_set(&object, "_value", primitive);
11538        Ok(object)
11539    }
11540
11541    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11542    ///
11543    /// Split out for a reader that has to create the object *before* it knows what it wraps:
11544    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11545    /// written before its primitive, so the placeholder has to exist first and be filled in
11546    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11547    /// than a second in the deserialiser.
11548    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11549        let prototype = match value {
11550            Value::String(_) => self.realm.string_proto.clone(),
11551            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11552            Value::Bool(_) => self.realm.boolean_proto.clone(),
11553            Value::Symbol(_) => self.realm.symbol_proto.clone(),
11554            Value::BigInt(_) => self.realm.bigint_proto.clone(),
11555            _ => {
11556                return Err(Signal::Throw(self.make_error(
11557                    "TypeError",
11558                    &format!("cannot box {}", value.to_js_string()),
11559                )));
11560            }
11561        };
11562        object.set_proto(prototype);
11563        if let Value::String(text) = value {
11564            self.init_string_wrapper(object, text);
11565            return Ok(());
11566        }
11567        self.internal_set(object, "_value", value.clone());
11568        Ok(())
11569    }
11570
11571    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11572    ///
11573    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11574    /// through the `Symbol` function object, so the registry is reachable as a method rather
11575    /// than only from `builtins::symbol`.
11576    pub fn symbol_for(&mut self, key: &str) -> Value {
11577        if let Some(existing) = self.realm.symbol_registry.get(key) {
11578            return existing.clone();
11579        }
11580        let symbol = crate::builtins::symbol::symbol_value(
11581            self,
11582            crate::value::JsSymbol::registered(key.to_string()),
11583        );
11584        self.realm
11585            .symbol_registry
11586            .insert(key.to_string(), symbol.clone());
11587        symbol
11588    }
11589
11590    /// `a == b`, the coercing comparison.
11591    ///
11592    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11593    /// which is what makes `[] == ""` true: `[]` becomes `""` via
11594    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11595    /// because the conversion is allowed to call script code, so the two primitive
11596    /// operands are handed back to it.
11597    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11598        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11599            return Ok(left.loose_equals(&right));
11600        }
11601        // `null == undefined` holds even though neither is an object.
11602        if matches!(left, Value::Undefined | Value::Null)
11603            && matches!(right, Value::Undefined | Value::Null)
11604        {
11605            return Ok(true);
11606        }
11607        if matches!(left, Value::Undefined | Value::Null)
11608            || matches!(right, Value::Undefined | Value::Null)
11609        {
11610            return Ok(false);
11611        }
11612        // Two objects compare by identity. Only an object *against a primitive* is
11613        // converted, which is why `{} == {}` is false while `[] == ""` is true.
11614        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11615            return Ok(a.ptr_eq(b));
11616        }
11617        let left = self.to_primitive(left, Hint::Default)?;
11618        let right = self.to_primitive(right, Hint::Default)?;
11619        Ok(left.loose_equals(&right))
11620    }
11621
11622    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11623        let Value::Object(object) = object else {
11624            return Err(Signal::Throw(
11625                self.make_error("TypeError", "cannot use 'in' on a non-object"),
11626            ));
11627        };
11628        let key = self.propkey(key)?;
11629        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11630        // trap. One implementation, so an array's derived `length` and its inherited holes
11631        // cannot be right in one caller and wrong in another.
11632        self.has_own_or_inherited(object, &key)
11633    }
11634
11635    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11636    ///
11637    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11638    /// whole reason the operator is a hook rather than a prototype walk.
11639    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11640        if let Value::Object(function) = constructor {
11641            let key = self.realm.well_known_key(WellKnown::HasInstance);
11642            let method = self.get_property_key(function, &key)?;
11643            if let Some(method) = method
11644                && !matches!(method, Value::Undefined)
11645            {
11646                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11647                return Ok(answer.to_boolean());
11648            }
11649        }
11650        self.instance_of(object, constructor)
11651    }
11652
11653    /// `OrdinaryHasInstance`: the prototype walk on its own.
11654    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11655        self.instance_of(object, constructor)
11656    }
11657
11658    /// `IsArray`: an array, or a proxy whose target is one.
11659    ///
11660    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11661    /// makes `Array.isArray(new Proxy([], {}))` true.
11662    pub fn is_array_value(&self, value: &Value) -> bool {
11663        match value {
11664            Value::Object(object) => {
11665                if let Some(state) = object.proxy_state() {
11666                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11667                }
11668                object.is_array()
11669            }
11670            _ => false,
11671        }
11672    }
11673
11674    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11675    ///
11676    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11677    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11678    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11679    /// see [`Interp::enqueue_job_function`].
11680    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11681        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11682        // the handler is reported rather than lost — the same reason a `then` reaction needs a
11683        // promise to settle.
11684        let promise = self.new_promise();
11685        self.fulfill_promise(&promise, Value::Undefined);
11686        self.jobs.push_back(Job::Reaction {
11687            handler: Some(function),
11688            argument: Value::Undefined,
11689            rejected: false,
11690            promise,
11691        });
11692        Ok(())
11693    }
11694
11695    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11696        let Value::Object(target) = object else {
11697            return Ok(false);
11698        };
11699        let Value::Object(function) = constructor else {
11700            return Err(Signal::Throw(self.make_error(
11701                "TypeError",
11702                "right-hand side of 'instanceof' is not callable",
11703            )));
11704        };
11705        let prototype = self.get_property(function, "prototype")?;
11706        let Some(Value::Object(prototype)) = prototype else {
11707            return Ok(false);
11708        };
11709        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11710        // which is also what makes `proxyOfInstance instanceof C` work.
11711        let mut current = Some(target.clone());
11712        while let Some(object) = current {
11713            if object.ptr_eq(&prototype) {
11714                return Ok(true);
11715            }
11716            current = self.object_prototype_of(&object)?;
11717        }
11718        Ok(false)
11719    }
11720
11721    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11722    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11723        if let Some(proto) = self.proxy_get_prototype_of(object)? {
11724            return Ok(proto);
11725        }
11726        if let Some(exotic) = object.exotic()
11727            && let Some(proto) = exotic.get_prototype(self, object)?
11728        {
11729            return Ok(proto);
11730        }
11731        Ok(object.proto())
11732    }
11733
11734    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11735    pub fn object_set_prototype_of(
11736        &mut self,
11737        object: &Gc<JsObject>,
11738        proto: Option<Gc<JsObject>>,
11739    ) -> JsResult<bool> {
11740        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11741            return Ok(answer);
11742        }
11743        if let Some(exotic) = object.exotic()
11744            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11745        {
11746            return Ok(answer);
11747        }
11748        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11749        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11750        // inheriting from itself, which every later prototype walk then had to defend
11751        // against — and `Reflect.setPrototypeOf` reported success for an operation the
11752        // language says is impossible.
11753        if let Some(proto) = &proto {
11754            let mut current = Some(proto.clone());
11755            let mut guard = 0;
11756            while let Some(node) = current {
11757                if node.ptr_eq(object) {
11758                    return Err(Signal::Throw(
11759                        self.make_error("TypeError", "circular prototype chain"),
11760                    ));
11761                }
11762                guard += 1;
11763                if guard > 1000 {
11764                    break;
11765                }
11766                current = node.proto();
11767            }
11768        }
11769        object.set_proto(proto);
11770        Ok(true)
11771    }
11772
11773    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
11774    ///
11775    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
11776    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
11777    /// already one.
11778    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
11779        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
11780        // (§10.4.5.4 step 1.b.i) — the prototype chain is *not* consulted for a canonical
11781        // numeric index. That is observable: a view that has been resized out of bounds
11782        // has no indices, and `2 in view` must then be `false` even when
11783        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
11784        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
11785        // A proxy is excluded because it has no `[[ViewedArrayBuffer]]` slot of its own.
11786        if object.typed_array_parts().is_some()
11787            && object.proxy_state().is_none()
11788            && let Some(index) = key.as_str().and_then(array_index)
11789        {
11790            return Ok(object
11791                .typed_array_length()
11792                .is_some_and(|length| (index as usize) < length));
11793        }
11794        let mut current = Some(object.clone());
11795        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
11796        let mut guard = 0;
11797        while let Some(node) = current {
11798            guard += 1;
11799            if guard > 1000 {
11800                return Ok(false);
11801            }
11802            let own = self.object_get_own_property(&node, key)?;
11803            if own.is_some() {
11804                return Ok(true);
11805            }
11806            current = self.object_prototype_of(&node)?;
11807        }
11808        Ok(false)
11809    }
11810
11811    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
11812    ///
11813    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
11814    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
11815    /// boolean as well, and it needs the receiver to be the one the caller named.
11816    pub fn set_property_with_key_receiver(
11817        &mut self,
11818        object: &Gc<JsObject>,
11819        key: &PropertyKey,
11820        value: Value,
11821        receiver: Option<&Value>,
11822        on_failure: DeleteFailure,
11823    ) -> JsResult<bool> {
11824        let receiver = receiver
11825            .cloned()
11826            .unwrap_or_else(|| Value::Object(object.clone()));
11827        if object.proxy_state().is_some() {
11828            return match self.proxy_set(object, key, value, &receiver)? {
11829                Some(accepted) => Ok(accepted),
11830                None => Ok(true),
11831            };
11832        }
11833        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
11834        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
11835        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
11836        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
11837        if object.typed_array_element_type().is_some()
11838            && key.as_str().and_then(array_index).is_some()
11839        {
11840            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
11841            self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
11842            return Ok(true);
11843        }
11844        // An own accessor, or one found up the chain, receives the call with `receiver` as
11845        // `this` — which is the whole reason this variant exists.
11846        if let Some(setter) = self.lookup_setter(object, key)? {
11847            self.call_value(setter, receiver, vec![value])?;
11848            return Ok(true);
11849        }
11850        // Otherwise it is an ordinary create-or-write, which the plain path already does —
11851        // carrying the receiver comparison, which a typed array's element store can see.
11852        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
11853        self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
11854        Ok(true)
11855    }
11856
11857    /// The setter `key` resolves to, if it resolves to an accessor.
11858    fn lookup_setter(
11859        &mut self,
11860        object: &Gc<JsObject>,
11861        key: &PropertyKey,
11862    ) -> JsResult<Option<Value>> {
11863        let mut current = Some(object.clone());
11864        let mut guard = 0;
11865        while let Some(node) = current {
11866            guard += 1;
11867            if guard > 1000 {
11868                return Ok(None);
11869            }
11870            if let Some(property) = self.object_get_own_property(&node, key)? {
11871                if property.is_accessor() {
11872                    return Ok(property.setter);
11873                }
11874                // A data property stops the walk: the store writes here, not further up.
11875                return Ok(None);
11876            }
11877            current = self.object_prototype_of(&node)?;
11878        }
11879        Ok(None)
11880    }
11881
11882    /// `[[IsExtensible]]`, with the proxy trap when there is one.
11883    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11884        if let Some(answer) = self.proxy_is_extensible(object)? {
11885            return Ok(answer);
11886        }
11887        if let Some(exotic) = object.exotic()
11888            && let Some(answer) = exotic.is_extensible(self, object)?
11889        {
11890            return Ok(answer);
11891        }
11892        Ok(object.is_extensible())
11893    }
11894
11895    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
11896    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11897        if let Some(answer) = self.proxy_prevent_extensions(object)? {
11898            return Ok(answer);
11899        }
11900        if let Some(exotic) = object.exotic()
11901            && let Some(answer) = exotic.prevent_extensions(self, object)?
11902        {
11903            return Ok(answer);
11904        }
11905        object.set_extensible(false);
11906        Ok(true)
11907    }
11908
11909    fn copy_properties(
11910        &mut self,
11911        target: &Value,
11912        source: &Value,
11913        exclusion: &Value,
11914    ) -> JsResult<()> {
11915        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
11916        // does contribute: its index properties are own, enumerable and writable, which
11917        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
11918        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
11919        // is a no-op.
11920        let Some(target) = target.as_object() else {
11921            return Ok(());
11922        };
11923        let source_object = match source {
11924            Value::Object(object) => object.clone(),
11925            Value::String(text) => {
11926                // Untaken keys are the string's indices, which are code units.
11927                for index in 0..text.utf16_len() {
11928                    if let Some(unit) = text.wtf8().unit_at(index) {
11929                        target.define_data(&index.to_string(), self.string_wtf8(unit));
11930                    }
11931                }
11932                return Ok(());
11933            }
11934            _ => return Ok(()),
11935        };
11936        // An object *rest* element passes the keys already taken by the literal part as
11937        // an array of strings; a spread passes `null`, which excludes nothing. Only the
11938        // string keys of the exclusion array are meaningful, so an array is read by its
11939        // elements rather than by its own property names.
11940        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
11941        if let Value::Object(list) = exclusion
11942            && let Some(length) = list.array_length()
11943        {
11944            for index in 0..length {
11945                if let Some(value) = list.array_get(index) {
11946                    excluded.push(self.propkey_of(&value)?);
11947                }
11948            }
11949        }
11950        let source = &source_object;
11951        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
11952        // Reading the property table directly made every spread of a proxy empty.
11953        let keys = self.object_own_property_keys(source)?;
11954        for as_key in keys {
11955            if as_key.is_symbol() {
11956                // A spread copies string-keyed properties only.
11957                continue;
11958            }
11959            if excluded.contains(&crate::value::Wtf8::new(
11960                as_key.as_str().unwrap_or_default(),
11961            )) {
11962                continue;
11963            }
11964            let enumerable = self
11965                .object_get_own_property(source, &as_key)?
11966                .is_some_and(|property| property.enumerable);
11967            if !enumerable {
11968                continue;
11969            }
11970            let value = self
11971                .get_property_key(source, &as_key)?
11972                .unwrap_or(Value::Undefined);
11973            target.define_data_key(&as_key, value);
11974        }
11975        Ok(())
11976    }
11977
11978    // -- iteration ---------------------------------------------------------
11979
11980    /// One object's own keys in enumeration order: array indices ascending, then the
11981    /// rest in insertion order.
11982    ///
11983    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
11984    /// whether the key is enumerable, which the caller resolves per key because an
11985    /// array's elements are not in the same store as its named properties.
11986    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
11987        // An index can arrive twice, once from the array's element store and once from
11988        // its property map, so the numeric keys go through a map that keeps the
11989        // enumerable answer if either source gave one.
11990        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
11991        for (key, enumerable) in &own {
11992            if let Some(index) = key.as_str().and_then(array_index) {
11993                let entry = numeric.entry(index).or_insert(false);
11994                *entry = *entry || *enumerable;
11995            }
11996        }
11997        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
11998            .into_iter()
11999            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12000            .collect();
12001        ordered.extend(
12002            own.into_iter()
12003                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12004        );
12005        ordered
12006    }
12007
12008    /// Build the key list a `for-in` loop walks.
12009    ///
12010    /// The order is the specification's: own properties before inherited ones, and
12011    /// within one object the integer-like keys in ascending numeric order ahead of the
12012    /// string keys in insertion order. A shadowed key only appears once, and a key that
12013    /// is a non-enumerable own property anywhere nearer is skipped entirely.
12014    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12015        let record = self.new_object(None);
12016        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12017        // A proxy supplies its own key list, and — the reason this is not just another
12018        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12019        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12020        // descriptor there.
12021        if let Value::Object(object) = value
12022            && object.proxy_state().is_some()
12023        {
12024            let own = self
12025                .proxy_own_keys(object)?
12026                .unwrap_or_else(|| object.own_property_keys());
12027            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12028            let mut numeric: Vec<u32> = Vec::new();
12029            let mut rest: Vec<PropertyKey> = Vec::new();
12030            for key in own {
12031                match key.as_str().and_then(array_index) {
12032                    Some(index) => numeric.push(index),
12033                    None => rest.push(key),
12034                }
12035            }
12036            numeric.sort_unstable();
12037            ordered.extend(
12038                numeric
12039                    .into_iter()
12040                    .map(|index| PropertyKey::from(index.to_string())),
12041            );
12042            ordered.extend(rest);
12043            for (index, key) in ordered.into_iter().enumerate() {
12044                record.define_data(&index.to_string(), self.key_value(&key));
12045            }
12046            record.define_data("__index", Value::Int(0));
12047            // The mark that makes `for_in_advance` re-ask the proxy per key.
12048            record.define_data("__proxy", Value::Object(object.clone()));
12049            return Ok(record);
12050        }
12051        if let Value::Object(object) = value {
12052            let mut chain = vec![object.clone()];
12053            chain.extend(object.chain());
12054            // Every own string key the walk has seen, enumerable or not. A
12055            // non-enumerable own property still hides a same-named enumerable one
12056            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12057            // keeps `x` out of the loop even when the prototype has one.
12058            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12059            for object in chain {
12060                let mut own: Vec<(crate::value::Wtf8, bool)> = object
12061                    .own_property_keys()
12062                    .iter()
12063                    .filter_map(|key| key.as_wtf8().cloned())
12064                    .map(|key| {
12065                        let enumerable = object
12066                            .own_property(&key.to_string_lossy())
12067                            .map(|property| property.enumerable)
12068                            .unwrap_or(false);
12069                        (key, enumerable)
12070                    })
12071                    .collect();
12072                if let Some(length) = object.array_length() {
12073                    own.retain(|(key, _)| key.as_str() != Some("length"));
12074                    for index in 0..length {
12075                        if object.array_get(index).is_some() {
12076                            own.push((crate::value::Wtf8::new(index.to_string()), true));
12077                        }
12078                    }
12079                }
12080                // Integer-like keys come first in ascending order, then the rest in
12081                // insertion order — and the ordering is *per object*, not for the chain
12082                // as a whole: one pass over every collected key lifted a prototype's
12083                // `"4"` above the target's own `x`/`y`, which is not the order
12084                // `for…in` reports.
12085                for (key, enumerable) in Self::order_own_keys(own) {
12086                    if visited.contains(&key) {
12087                        continue;
12088                    }
12089                    visited.push(key.clone());
12090                    if enumerable {
12091                        keys.push(key);
12092                    }
12093                }
12094            }
12095        }
12096        for (index, key) in keys.into_iter().enumerate() {
12097            record.define_data(&index.to_string(), self.string_wtf8(key));
12098        }
12099        record.define_data("__index", Value::Int(0));
12100        Ok(record)
12101    }
12102
12103    /// The next key of a `for…in` record, `None` when the loop is done.
12104    ///
12105    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12106    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12107    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12108    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12109    /// key the handler had already withdrawn.
12110    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12111        let Value::Object(record) = record else {
12112            return Ok(None);
12113        };
12114        let proxy = record
12115            .own_property("__proxy")
12116            .and_then(|property| property.value);
12117        loop {
12118            let index = record
12119                .own_property("__index")
12120                .and_then(|property| property.value)
12121                .map(|value| value.to_int32())
12122                .unwrap_or(0);
12123            let Some(candidate) = record
12124                .own_property(&index.to_string())
12125                .and_then(|property| property.value)
12126            else {
12127                return Ok(None);
12128            };
12129            record.define_data("__index", Value::Int(index + 1));
12130            let text = candidate.to_js_string();
12131            let Some(Value::Object(proxy)) = &proxy else {
12132                return Ok(Some(text));
12133            };
12134            // The candidate is already a key string here, so the lookup does not need a
12135            // second `ToPropertyKey` conversion.
12136            let key = PropertyKey::from(text.as_str());
12137            let live = match self.proxy_get_own_property(proxy, &key)? {
12138                Some(descriptor) => descriptor,
12139                // Not a proxy after all, or it lost its state: fall back to the target.
12140                None => proxy.own_property_key(&key),
12141            };
12142            if live.is_some_and(|property| property.enumerable) {
12143                return Ok(Some(text));
12144            }
12145            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12146            // next one.
12147        }
12148    }
12149
12150    /// The iterator for `for-of`: the object and its `next` method.
12151    ///
12152    /// An object that already carries a `next` method is used as it is — that is what
12153    /// `arr.values()` returns — and only arrays and strings get the built-in
12154    /// sequence iterator.
12155    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12156    ///
12157    /// Callers that must choose between the iterable and the array-like protocol — the
12158    /// typed-array constructor is the main one — need to ask *before* committing to one.
12159    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12160        let key = self.realm.well_known_key(WellKnown::Iterator);
12161        let method = self.read_field_key(value, &key)?;
12162        if matches!(method, Value::Undefined | Value::Null) {
12163            return Ok(false);
12164        }
12165        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12166            return Err(Signal::Throw(
12167                self.make_error("TypeError", "Symbol.iterator is not callable"),
12168            ));
12169        }
12170        Ok(true)
12171    }
12172
12173    /// Collect everything an iterable yields, closing it if the walk is abandoned.
12174    ///
12175    /// The cap is a guard against a generator that never ends: an unbounded collect would
12176    /// be an out-of-memory abort rather than a catchable error.
12177    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12178        const MAX_ITEMS: usize = 1 << 24;
12179        let iterator = self.get_iterator(value)?;
12180        let mut out = Vec::new();
12181        loop {
12182            let (element, done) = self.iterator_step(&iterator)?;
12183            if done {
12184                return Ok(out);
12185            }
12186            out.push(element);
12187            if out.len() > MAX_ITEMS {
12188                return Err(self.range_error("iterable is too long to collect"));
12189            }
12190        }
12191    }
12192
12193    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12194    ///
12195    /// A native constructor calls this once it has validated its arguments, which is the
12196    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12197    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12198    /// never reached. The prototype comes from `new.target` when it is an object, and from
12199    /// `default_proto` otherwise.
12200    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12201        let proto = self.ctor_prototype(default_proto)?;
12202        Ok(self.new_object(Some(proto)))
12203    }
12204
12205    /// An **array** whose prototype comes from `new.target`.
12206    ///
12207    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12208    /// instance from `new.target.prototype`, and building a plain array instead made every
12209    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12210    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12211        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12212        Ok(JsObject::array(self.heap, Some(proto), 0))
12213    }
12214
12215    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12216    ///
12217    /// The `Option` form is for the constructors that build their instance in a helper which
12218    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12219    /// from `await`'s internal promise, and only the first has a `new.target`.
12220    fn ctor_prototype_opt(
12221        &mut self,
12222        default_proto: Option<Gc<JsObject>>,
12223    ) -> JsResult<Option<Gc<JsObject>>> {
12224        let Some(target) = self.pending_new_target.clone() else {
12225            return Ok(default_proto);
12226        };
12227        let Some(target) = target.as_object().cloned() else {
12228            return Ok(default_proto);
12229        };
12230        match self.get_property(&target, "prototype")? {
12231            Some(Value::Object(proto)) => Ok(Some(proto)),
12232            _ => Ok(default_proto),
12233        }
12234    }
12235
12236    /// `new.target.prototype`, or `default_proto` when this is a plain call.
12237    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12238        let Some(target) = self.pending_new_target.clone() else {
12239            return Ok(default_proto);
12240        };
12241        let Some(target) = target.as_object().cloned() else {
12242            return Ok(default_proto);
12243        };
12244        match self.get_property(&target, "prototype")? {
12245            Some(Value::Object(proto)) => Ok(proto),
12246            _ => Ok(default_proto),
12247        }
12248    }
12249
12250    /// `CreateDataPropertyOrThrow(O, key, value)`.
12251    ///
12252    /// A *definition*, not an assignment. The difference is visible the moment the target
12253    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12254    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12255    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12256    /// refused (`configurable: false`).
12257    ///
12258    /// The fast path exists because this is called once per element by `map`, `filter`,
12259    /// `slice` and friends: a plain array with no custom element descriptors and a writable
12260    /// `length` can store straight into its element vector.
12261    pub fn create_data_property_or_throw(
12262        &mut self,
12263        object: &Gc<JsObject>,
12264        index: usize,
12265        value: Value,
12266    ) -> JsResult<()> {
12267        if object.is_array()
12268            && object.elements_writable()
12269            && !object.has_element_descriptors()
12270            && object.is_extensible()
12271            && object.array_set(self.heap, index, value.clone())
12272        {
12273            return Ok(());
12274        }
12275        let key = PropertyKey::from(index.to_string());
12276        let property = Property {
12277            value: Some(value),
12278            writable: true,
12279            enumerable: true,
12280            configurable: true,
12281            ..Property::default()
12282        };
12283        if self.object_define_own_property(object, &key, property)? {
12284            return Ok(());
12285        }
12286        Err(self.type_error("cannot create the property"))
12287    }
12288
12289    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12290    ///
12291    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12292    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12293    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12294    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12295    /// run user code and both can throw.
12296    pub fn species_constructor(
12297        &mut self,
12298        object: &Gc<JsObject>,
12299        default: Value,
12300    ) -> JsResult<Value> {
12301        let Some(constructor) = self.get_property(object, "constructor")? else {
12302            return Ok(default);
12303        };
12304        let constructor = match constructor {
12305            Value::Undefined => return Ok(default),
12306            Value::Object(constructor) => constructor,
12307            _ => return Err(self.type_error("constructor is not an object")),
12308        };
12309        let key = self.realm.well_known_key(WellKnown::Species);
12310        let species = self.get_property_key(&constructor, &key)?;
12311        match species {
12312            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12313            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12314            Some(_) => Err(self.type_error("species is not a constructor")),
12315        }
12316    }
12317
12318    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12319    ///
12320    /// The result is an array of `length` holes whose prototype comes from
12321    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12322    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12323    /// is why the `IsArray` check is the first step and not an optimisation.
12324    pub fn array_species_create(
12325        &mut self,
12326        original: &Value,
12327        length: usize,
12328    ) -> JsResult<Gc<JsObject>> {
12329        let Some(object) = original.as_object().cloned() else {
12330            return Ok(self.new_array_of_length(length));
12331        };
12332        if !object.is_array() {
12333            return Ok(self.new_array_of_length(length));
12334        }
12335        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12336        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12337        let Some(constructor) = self.get_property(&object, "constructor")? else {
12338            return Ok(self.new_array_of_length(length));
12339        };
12340        let species = match constructor {
12341            Value::Undefined => return Ok(self.new_array_of_length(length)),
12342            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12343                return Ok(self.new_array_of_length(length));
12344            }
12345            Value::Object(constructor) => {
12346                let key = self.realm.well_known_key(WellKnown::Species);
12347                match self.get_property_key(&constructor, &key)? {
12348                    None | Some(Value::Undefined) | Some(Value::Null) => {
12349                        return Ok(self.new_array_of_length(length));
12350                    }
12351                    Some(species) => species,
12352                }
12353            }
12354            _ => return Ok(self.new_array_of_length(length)),
12355        };
12356        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12357        // that is merely callable is the `create-species-non-ctor` case.
12358        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12359            return Err(self.type_error("species is not a constructor"));
12360        }
12361        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12362        let Some(created) = created.as_object().cloned() else {
12363            return Err(self.type_error("species constructor did not answer an object"));
12364        };
12365        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12366        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12367        // object, and `create-species-with-non-writable-property` asserts exactly that.
12368        // The length is set for the array case; the generic case is the caller's
12369        // `Set(A, "length", …)`.
12370        if created.is_array() {
12371            created.array_set_length(self.heap, length);
12372        }
12373        Ok(created)
12374    }
12375
12376    /// Whether `object` is this realm's `%Array%`.
12377    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12378        self.realm
12379            .array_constructor
12380            .as_ref()
12381            .is_some_and(|array| array.ptr_eq(object))
12382    }
12383
12384    /// A fresh `length`-hole array with the intrinsic prototype.
12385    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12386        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12387        array.array_set_length(self.heap, length);
12388        array
12389    }
12390
12391    /// Whether this call is a construction, i.e. `new.target` is defined.
12392    ///
12393    /// A native constructor receives `this = undefined` (it builds its own instance), so it
12394    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12395    /// The native function currently executing, if any.
12396    pub fn current_native(&self) -> Option<Gc<JsObject>> {
12397        self.current_native.clone()
12398    }
12399
12400    /// Whether this call is a construction, i.e. `new.target` is defined.
12401    pub fn is_constructing(&self) -> bool {
12402        self.pending_new_target.is_some()
12403    }
12404
12405    /// The `TypeError` a constructor too primitive to have a wrapper raises.
12406    ///
12407    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12408    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12409    /// happens inside the native function, which is why the trace carries an
12410    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12411    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12412    /// constructor`, and an unnamed one reports the leading space of `" is not a
12413    /// constructor"` because the reference formats the empty name as it is.
12414    ///
12415    /// It is also the answer for a `new.target` that cannot be named at all — not a
12416    /// function, or a throwing `name` getter — where the reference falls back to the bare
12417    /// `not a constructor`.
12418    pub fn not_a_constructor_error(&mut self) -> Signal {
12419        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12420        self.not_a_constructor_error_for(target)
12421    }
12422
12423    /// The same `TypeError` for an explicit target, for the callers that check
12424    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12425    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12426        let target = match target {
12427            Value::Object(target) if target.is_callable() => target,
12428            _ => return self.type_error("not a constructor"),
12429        };
12430        let name = match self.get_property(&target, "name") {
12431            Ok(Some(value)) => value.to_js_string(),
12432            _ => return self.type_error("not a constructor"),
12433        };
12434        self.type_error(format!("{name} is not a constructor"))
12435    }
12436
12437    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12438    ///
12439    /// True whenever `new.target` is not the callee itself, or when it has no usable
12440    /// `prototype` — the cases where reading the property is observable at all.
12441    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12442        match &self.pending_new_target {
12443            Some(Value::Object(target)) => !target.ptr_eq(callee),
12444            Some(_) => true,
12445            None => false,
12446        }
12447    }
12448
12449    /// The symbol key for one of the engine's own hidden slots.
12450    ///
12451    /// Cached on the realm, so every object of a kind shares one key and a slot can be
12452    /// read back by name.
12453    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12454        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12455            return PropertyKey::Symbol(symbol.clone());
12456        }
12457        let symbol = Gc::new(
12458            self.heap,
12459            crate::value::JsSymbol::new(Some(name.to_string())),
12460        );
12461        self.realm
12462            .internal_slots
12463            .borrow_mut()
12464            .insert(name, Value::Symbol(symbol.clone()));
12465        PropertyKey::Symbol(symbol)
12466    }
12467
12468    /// Read a hidden slot, or `None` when the object has none of that name.
12469    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12470        let slots = self.realm.internal_slots.borrow();
12471        let Value::Symbol(symbol) = slots.get(name)? else {
12472            return None;
12473        };
12474        object
12475            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12476            .and_then(|property| property.value)
12477    }
12478
12479    /// Define a hidden slot.
12480    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12481        let key = self.internal_slot(name);
12482        object.define_key(&key, Property::with_attributes(value, false, false));
12483    }
12484
12485    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12486    ///
12487    /// The method is looked up on the value (through its prototype), called with no
12488    /// arguments, and its result becomes the iterator. A generator gets here through
12489    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12490    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12491    ///
12492    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12493    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12494    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12495    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12496    /// does, and a user-defined iterable works without a special case.
12497    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12498    /// `Symbol.iterator`.
12499    ///
12500    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12501    /// iterable is legal there, and each value it produces is simply already settled by
12502    /// the time the `await` around it runs.
12503    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12504        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12505        let method = self.read_field_key(value, &async_key)?;
12506        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12507        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12508        // is *present but not callable* is a TypeError — it does not mean "try the other
12509        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12510        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12511        // guard is there to catch.
12512        let absent = matches!(method, Value::Undefined | Value::Null);
12513        if !absent {
12514            let Value::Object(object) = &method else {
12515                return Err(Signal::Throw(
12516                    self.make_error("TypeError", "value is not iterable"),
12517                ));
12518            };
12519            if !object.is_callable() {
12520                return Err(Signal::Throw(
12521                    self.make_error("TypeError", "value is not iterable"),
12522                ));
12523            }
12524        }
12525        if absent {
12526            return self.get_iterator(value);
12527        }
12528        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12529        if !matches!(iterator, Value::Object(_)) {
12530            return Err(Signal::Throw(
12531                self.make_error("TypeError", "iterator is not an object"),
12532            ));
12533        }
12534        let next = self.read_field(&iterator, "next")?;
12535        Ok(Iterator {
12536            object: iterator,
12537            next,
12538        })
12539    }
12540
12541    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12542        let key = self.realm.well_known_key(WellKnown::Iterator);
12543        let method = self.read_field_key(value, &key)?;
12544        let Value::Object(function) = &method else {
12545            return Err(Signal::Throw(self.make_error(
12546                "TypeError",
12547                &format!("{} is not iterable", value.to_js_string()),
12548            )));
12549        };
12550        if !function.is_callable() {
12551            return Err(Signal::Throw(self.make_error(
12552                "TypeError",
12553                &format!("{} is not iterable", value.to_js_string()),
12554            )));
12555        }
12556        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12557        // The spec requires an object here; a primitive iterator has no `next` to call
12558        // and would fail one step later with a confusing message.
12559        if !matches!(iterator, Value::Object(_)) {
12560            return Err(Signal::Throw(
12561                self.make_error("TypeError", "iterator is not an object"),
12562            ));
12563        }
12564        let next = self.read_field(&iterator, "next")?;
12565        Ok(Iterator {
12566            object: iterator,
12567            next,
12568        })
12569    }
12570
12571    /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
12572    /// not iterable.
12573    ///
12574    /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
12575    /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
12576    /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
12577    /// was `[]`.
12578    pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
12579        let key = self.realm.well_known_key(WellKnown::Iterator);
12580        let method = self.read_field_key(value, &key)?;
12581        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12582            return Ok(None);
12583        }
12584        let iterator = self.get_iterator(value)?;
12585        let mut out = Vec::new();
12586        loop {
12587            let (element, done) = self.iterator_step(&iterator)?;
12588            if done {
12589                return Ok(Some(out));
12590            }
12591            out.push(element);
12592        }
12593    }
12594
12595    /// One step of an internal iterator: the value and whether it is exhausted.
12596    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12597        // A real iterator (`next` is a function) answers with a result object.
12598        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12599            let result =
12600                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12601            let Some(result) = result.as_object().cloned() else {
12602                return Err(self.type_error("iterator result is not an object"));
12603            };
12604            let done = self
12605                .get_property(&result, "done")?
12606                .is_some_and(|value| value.to_boolean());
12607            let value = self
12608                .get_property(&result, "value")?
12609                .unwrap_or(Value::Undefined);
12610            return Ok((value, done));
12611        }
12612        // An iterator whose `next` is not callable is treated as exhausted, which is
12613        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12614        // that are not iterable at all.
12615        Ok((Value::Undefined, true))
12616    }
12617
12618    /// `[...iterable]`: append everything the iterator yields, and answer the next
12619    /// index.
12620    ///
12621    /// This goes through the same iterator machinery `for-of` uses rather than copying
12622    /// an array's elements, because a spread source is any iterable: a string spreads
12623    /// into its characters and an array iterator spreads into its results. Handling
12624    /// only arrays made `[..."ab"]` come out empty with no error at all.
12625    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12626        let Some(target) = array.as_object().cloned() else {
12627            return Ok(0);
12628        };
12629        let start = target.array_length().unwrap_or(0);
12630        let mut added = 0;
12631        let iterator = self.get_iterator(iterable)?;
12632        loop {
12633            let (value, done) = self.iterator_step(&iterator)?;
12634            if done {
12635                break;
12636            }
12637            target.array_set(self.heap, start + added, value);
12638            added += 1;
12639        }
12640        Ok((start + added) as i32)
12641    }
12642
12643    /// How an uncaught exception is reported.
12644    ///
12645    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12646    /// with `ToString` — `js_std_dump_error` is three lines that end in
12647    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12648    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12649    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12650    ///
12651    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12652    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12653    /// `toString`"; it does call it, but only for objects of a class it does not know how
12654    /// to walk, and never for errors, arrays or plain objects.
12655    ///
12656    /// A printer that fails must not take the reporter down with it, so that case falls
12657    /// back to the `ToString` rendering.
12658    pub fn describe_exception(&mut self, value: &Value) -> String {
12659        match crate::print::sprint(self, value) {
12660            Ok(text) => text,
12661            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12662        }
12663    }
12664
12665    /// The file name of whatever is running, innermost frame first.
12666    ///
12667    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12668    /// innermost frame's file name, without distinguishing a module body from a plain
12669    /// script. `import()` uses it as the base for a relative specifier, which is why
12670    /// `import('./x.js')` inside a script resolves next to the script and not next to the
12671    /// process's working directory.
12672    pub fn script_or_module_name(&self) -> Option<String> {
12673        self.script_or_module_name_at(0)
12674    }
12675
12676    /// [`Interp::script_or_module_name`] `level` frames further out.
12677    ///
12678    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12679    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12680    /// frame without a file name is skipped rather than counted, because a native call
12681    /// pushes no frame of its own and so cannot be a level.
12682    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12683        self.frames
12684            .iter()
12685            .rev()
12686            .filter_map(|frame| frame.code.code.filename.clone())
12687            .nth(level)
12688    }
12689
12690    /// The current call stack, formatted the way `qjs` prints `error.stack`.
12691    ///
12692    /// One `    at name (file:line:col)` line per active frame, innermost first. The
12693    /// position is the one recorded for the instruction each frame is stopped on, which
12694    /// is why the compiler builds a pc-to-position table per function: without it a
12695    /// trace could only name the function, not the line inside it.
12696    ///
12697    /// A frame whose code has no positions prints just `(file)`, matching the
12698    /// reference's output for stripped bytecode.
12699    pub fn stack_trace(&self) -> String {
12700        self.stack_trace_skipping(0)
12701    }
12702
12703    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12704    fn stack_trace_skipping(&self, skip: usize) -> String {
12705        // One ordered list, innermost first, so `skip` counts the same thing whether the
12706        // frames it leaves out are native or bytecode. Indices rather than references: a
12707        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12708        let depth = self.frames.len();
12709        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12710        // A native entered while `at` bytecode frames were live was called *from* the
12711        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12712        // entered at the current depth are therefore innermost of all.
12713        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12714            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12715                if *at == wanted {
12716                    order.push((true, index));
12717                }
12718            }
12719        };
12720        push_natives(&mut order, depth);
12721        for index in (0..depth).rev() {
12722            order.push((false, index));
12723            push_natives(&mut order, index);
12724        }
12725        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12726        // barrier. Natives entered at exactly the barrier depth are the eval entry point
12727        // itself (`evalScript (native)`), and the reference leaves those out too.
12728        if let Some(barrier) = self.trace_barriers.last().copied() {
12729            order.retain(|(is_native, index)| match is_native {
12730                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12731                false => *index >= barrier,
12732            });
12733        }
12734
12735        let mut out = String::new();
12736        for (is_native, index) in order.into_iter().skip(skip) {
12737            match is_native {
12738                true => {
12739                    out.push_str("    at ");
12740                    let (native, _) = &self.native_frames[index];
12741                    let name = native
12742                        .own_property("name")
12743                        .and_then(|property| property.value)
12744                        .map(|value| value.to_js_string())
12745                        .unwrap_or_default();
12746                    out.push_str(&name);
12747                    out.push_str(" (native)\n");
12748                }
12749                false => {
12750                    let frame = &self.frames[index];
12751                    let code = &frame.code.code;
12752                    let file = code.filename.as_deref().unwrap_or("<input>");
12753                    // The name comes from the function *object*, not from the compiled code:
12754                    // an anonymous function expression is named by the property it is stored
12755                    // in (`{valueOf: function(){}}`), which only the object knows.
12756                    let bound_name = match &frame.callee {
12757                        Value::Object(object) => {
12758                            object
12759                                .own_property("name")
12760                                .and_then(|property| match property.value {
12761                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
12762                                        Some(text.to_string_lossy().into_owned())
12763                                    }
12764                                    _ => None,
12765                                })
12766                        }
12767                        _ => None,
12768                    };
12769                    // No callee object means the body was entered by the host, so the
12770                    // name has to come from the compiled code. Two cases differ:
12771                    //
12772                    // * an *unnamed* function of any kind — the reference reads the
12773                    //   `name` property, finds it empty, and prints `<anonymous>`;
12774                    // * a *module* body, which has no `name` property at all: the
12775                    //   reference builds that function object with `js_closure2` and
12776                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
12777                    //   so a trace reaching it also prints `<anonymous>` — while a
12778                    //   *script* body prints `<eval>`, its `name`.
12779                    let unnamed = code.name.is_empty() || code.module.is_some();
12780                    out.push_str("    at ");
12781                    match bound_name.as_deref() {
12782                        Some(name) => out.push_str(name),
12783                        None if unnamed => out.push_str("<anonymous>"),
12784                        None => out.push_str(&code.name),
12785                    }
12786                    match code.position_at(frame.at as u32) {
12787                        Some((line, column)) => {
12788                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
12789                        }
12790                        None => out.push_str(&format!(" ({file})\n")),
12791                    }
12792                }
12793            }
12794        }
12795        out
12796    }
12797
12798    /// Give an anonymous function the name of the property it is stored in.
12799    ///
12800    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
12801    /// enumerable and not configurable, and a function that already has a real name
12802    /// keeps it.
12803    ///
12804    /// "Already named" means a *non-empty* name: every function object is created with
12805    /// a `name` of `""` so the property exists on all of them, and treating that empty
12806    /// string as a name left every anonymous function nameless — which is how a stack
12807    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
12808    /// `SetFunctionName`, for a name that came from source text.
12809    fn set_function_name(&mut self, function: &Value, name: &str) {
12810        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
12811    }
12812
12813    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
12814    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
12815    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
12816        let Value::Object(object) = function else {
12817            return;
12818        };
12819        // `SetFunctionName` applies to *functions* and classes only, and only when they are
12820        // anonymous. Without the callability guard, `{value: someObject}` renamed
12821        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
12822        // on the right-hand side of a property. That is how a `zipKeyed` result object
12823        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
12824        // has no `NamedEvaluation` at all.
12825        if !object.is_callable() {
12826            return;
12827        }
12828        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
12829            && !existing.wtf8().is_empty()
12830        {
12831            return;
12832        }
12833        let text = self.string_wtf8(name.clone());
12834        object.define("name", Property::name_or_length(text));
12835    }
12836
12837    // -- global declarations -----------------------------------------------
12838
12839    /// Declare a global binding, creating its reference cell.
12840    /// Declare a `var` or function global, whose home is the global object.
12841    ///
12842    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
12843    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
12844    /// such as `print`, or a redeclaration — is left alone.
12845    pub fn declare_var_global(&mut self, name: &str) {
12846        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
12847        // global object is exactly the leak `typeof my_var === "undefined"` after
12848        // `eval("var my_var=2")` rules out.
12849        if let Some(scope) = self.eval_scope.as_mut() {
12850            scope.entry(name.to_string()).or_insert(Value::Undefined);
12851            return;
12852        }
12853        // A sloppy direct eval declares into its *caller's* variable environment. Doing
12854        // this on the global object instead made `eval("var c = 1")` inside a parameter
12855        // list overwrite a global `c`, and made two calls to the same function share one
12856        // binding.
12857        if let Some(cell) = self.declare_eval_local(name) {
12858            cell.set(Value::Undefined);
12859            return;
12860        }
12861        let global = self.realm.global.clone();
12862        if global.own_property(name).is_some() {
12863            return;
12864        }
12865        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
12866        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
12867        // whole point of that trick and what lets `Object.defineProperty` reshape it
12868        // afterwards. `eval_scope` is `Some` while an eval is running.
12869        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
12870        global.define(
12871            name,
12872            Property {
12873                value: Some(Value::Undefined),
12874                writable: true,
12875                enumerable: true,
12876                configurable: from_eval,
12877                ..Property::default()
12878            },
12879        );
12880    }
12881
12882    /// Declare a *lexical* global binding, which starts in its dead zone.
12883    ///
12884    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
12885    /// global object and is created when its initialiser runs.
12886    pub fn declare_global(&mut self, name: &str, is_const: bool) {
12887        if is_const {
12888            self.realm.lexical_consts.insert(name.to_string());
12889        }
12890        if !self.realm.globals.contains_key(name) {
12891            // `Uninitialized` rather than `Undefined`: the binding exists but is not
12892            // readable until its initialiser runs, and that is what `let x` before
12893            // `x = 1` has to observe.
12894            let cell = self.new_cell(Value::Uninitialized);
12895            self.realm.globals.insert(name.to_string(), cell);
12896            self.realm.declared.push(name.to_string());
12897        }
12898    }
12899}
12900
12901/// The bytecode and environment of a function object, if it is a bytecode function.
12902///
12903/// Extracted before a call so no borrow of the object is held across it.
12904fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
12905    function.with(|data| match &data.kind {
12906        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
12907        _ => None,
12908    })
12909}
12910
12911/// A native call target, extracted before the call so no borrow is held.
12912enum NativeCall {
12913    Native(NativeFn),
12914    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
12915    /// not hold that object's `RefCell` borrow.
12916    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
12917    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
12918    Bound {
12919        target: Value,
12920        this: Value,
12921        leading: Vec<Value>,
12922    },
12923    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
12924    Revoker(crate::object::ProxyRef),
12925    /// A promise's `resolve`.
12926    PromiseResolve(Gc<JsObject>),
12927    /// A promise's `reject`.
12928    PromiseReject(Gc<JsObject>),
12929    /// The executor `NewPromiseCapability(C)` hands a user constructor.
12930    CapabilityExecutor {
12931        state: Gc<JsObject>,
12932    },
12933    /// One leg of a `then` that settles through a user capability.
12934    ThenShim {
12935        handler: Option<Value>,
12936        resolve: Value,
12937        reject: Value,
12938        fulfilled: bool,
12939    },
12940    /// One continuation of an `await`.
12941    AwaitResume {
12942        coroutine: Gc<JsObject>,
12943        promise: Gc<JsObject>,
12944        kind: ResumeKind,
12945    },
12946    /// One element of a `Promise` combinator settling.
12947    CombinatorSettle {
12948        state: Gc<JsObject>,
12949        index: usize,
12950        fulfilled: bool,
12951    },
12952    /// One of `Promise.prototype.finally`'s two shims.
12953    FinallyShim {
12954        callback: Option<Value>,
12955        fulfilled: bool,
12956        constructor: Value,
12957    },
12958    /// Settle a promise with a fixed outcome.
12959    SettlePromise {
12960        promise: Gc<JsObject>,
12961        value: Value,
12962        rejected: bool,
12963    },
12964    /// Continue an async generator after its `await` settled.
12965    GeneratorResume {
12966        generator: Gc<JsObject>,
12967        promise: Gc<JsObject>,
12968        kind: ResumeKind,
12969    },
12970    /// Read a module namespace's binding out of its cell.
12971    ModuleBinding(Gc<Cell>),
12972    /// Finish a completed async generator's `return(v)` once `v` has settled.
12973    CompletedReturn {
12974        generator: Gc<JsObject>,
12975        promise: Gc<JsObject>,
12976        rejected: bool,
12977    },
12978    /// Answer a pending async-generator method with `{value, done}`.
12979    YieldResult {
12980        generator: Gc<JsObject>,
12981        promise: Gc<JsObject>,
12982        done: bool,
12983    },
12984    /// One step of `AsyncDisposableStack.disposeAsync`.
12985    DisposeStep {
12986        remaining: Gc<JsObject>,
12987        promise: Gc<JsObject>,
12988        error: Value,
12989        rejected: bool,
12990    },
12991}
12992
12993/// What a store does when the object refuses the write.
12994#[derive(Clone, Copy, PartialEq, Eq)]
12995pub enum DeleteFailure {
12996    /// Raise a `TypeError`, which is what strict mode and every built-in does.
12997    Throw,
12998    /// Ignore the write, which is what a sloppy-mode assignment does.
12999    Ignore,
13000}
13001
13002/// Whether `object` is a `Date` instance, by the class tag it carries.
13003///
13004/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13005/// builtins module depending on the interpreter's conversion order.
13006fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13007    interp
13008        .internal_get(object, "_class")
13009        .is_some_and(|value| value.to_js_string() == "Date")
13010}
13011
13012/// Which type `ToPrimitive` prefers when it converts an object.
13013#[derive(Clone, Copy, PartialEq, Eq)]
13014pub enum Hint {
13015    /// The default hint, which behaves like [`Hint::Number`].
13016    Default,
13017    /// `Number(obj)` and the arithmetic operators.
13018    Number,
13019    /// `String(obj)` and `ToPropertyKey`.
13020    String,
13021}
13022
13023/// Which table a binding slot indexes, for the messages that name it.
13024#[derive(Clone, Copy)]
13025enum VarSlot {
13026    Loc,
13027    Closure,
13028}
13029
13030/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13031fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13032    Ok(this)
13033}
13034
13035/// An internal iterator: the sequence plus a cursor.
13036pub(crate) struct Iterator {
13037    pub(crate) object: Value,
13038    pub(crate) next: Value,
13039}
13040
13041/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13042/// and plain `a` for a method.
13043///
13044/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13045/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13046/// reads `at get a (file:1:2)`.
13047/// The same prefixing, for a name that may hold an unpaired surrogate.
13048fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13049    let prefix = match flags & 3 {
13050        1 => "get ",
13051        2 => "set ",
13052        _ => return key.clone(),
13053    };
13054    let mut units: Vec<u16> = prefix.encode_utf16().collect();
13055    units.extend_from_slice(&key.to_units());
13056    crate::value::Wtf8::from_units(&units)
13057}
13058
13059fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13060    match flags & 3 {
13061        1 => format!("get {key}"),
13062        2 => format!("set {key}"),
13063        _ => key.to_string(),
13064    }
13065}
13066
13067/// Define a method or accessor property, per the `define_method` flag byte.
13068///
13069/// The low two bits pick value/getter/setter and bit 2 marks the property
13070/// enumerable.
13071///
13072/// A getter and a setter arrive as two separate `define_method` instructions, and the
13073/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13074/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13075/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13076/// `JS_DefineProperty`, which leaves the other half alone.
13077fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13078    let enumerable = flags & 4 != 0;
13079    let kind = flags & 3;
13080    let existing = object.own_property_key(key);
13081    let property = match kind {
13082        1 => Property {
13083            getter: Some(function),
13084            // The setter half, if this literal already defined one.
13085            setter: existing
13086                .filter(Property::is_accessor)
13087                .and_then(|p| p.setter),
13088            enumerable,
13089            configurable: true,
13090            ..Property::default()
13091        },
13092        2 => Property {
13093            getter: existing
13094                .filter(Property::is_accessor)
13095                .and_then(|p| p.getter),
13096            setter: Some(function),
13097            enumerable,
13098            configurable: true,
13099            ..Property::default()
13100        },
13101        _ => Property {
13102            value: Some(function),
13103            writable: true,
13104            enumerable,
13105            configurable: true,
13106            ..Property::default()
13107        },
13108    };
13109    object.define_key(key, property);
13110}
13111
13112// ---------------------------------------------------------------------------
13113// Operand decoding
13114// ---------------------------------------------------------------------------
13115
13116/// How `print` renders a value: the reference's `JS_PrintValue`.
13117///
13118/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13119/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13120/// The format is reproduced closely because the test suite compares output text:
13121///
13122/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13123/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13124/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13125/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13126///   end print as `<N empty item(s)>`;
13127/// * a string is quoted inside a container but raw at the top level, which is why
13128///   `print("x")` and `print(["x"])` differ.
13129pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13130    // A string argument is printed raw: `js_print` converts it with `ToString`
13131    // instead of dumping it, and the quoting only appears inside a container.
13132    if let Value::String(text) = value {
13133        return text.to_string_lossy().into_owned();
13134    }
13135    let mut printer = Printer {
13136        interp,
13137        out: String::new(),
13138        stack: Vec::new(),
13139    };
13140    printer.value(value, 0);
13141    printer.out
13142}
13143
13144/// The internal class name an object carries, when it has one.
13145fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13146    interp
13147        .internal_get(object, "_class")
13148        .map(|value| value.to_js_string())
13149}
13150
13151/// A string property, looked up the way `GetProperty` does: own first, then the
13152/// prototype chain. Needed because the print formatter holds the interpreter
13153/// immutably and so cannot run getters.
13154fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13155    let mut current = Some(object.clone());
13156    // Bounded, because a prototype cycle would otherwise loop forever.
13157    for _ in 0..100 {
13158        let node = current?;
13159        if let Some(property) = node.own_property(name)
13160            && let Some(value) = property.value
13161        {
13162            return Some(value.to_js_string());
13163        }
13164        current = node.with(|data| data.proto.clone());
13165    }
13166    None
13167}
13168
13169/// The `JS_PrintValue` state: output, and the objects currently being printed.
13170struct Printer<'a, 'rt> {
13171    /// Kept for the class-name lookups that typed arrays and `Date` will need.
13172    #[allow(dead_code)]
13173    interp: &'a Interp<'rt>,
13174    out: String,
13175    stack: Vec<Gc<JsObject>>,
13176}
13177
13178impl Printer<'_, '_> {
13179    /// Depth past which a container is summarised by its class name.
13180    const MAX_DEPTH: usize = 2;
13181
13182    fn value(&mut self, value: &Value, level: usize) {
13183        match value {
13184            Value::Undefined
13185            | Value::Uninitialized
13186            | Value::Hole
13187            | Value::CatchOffset(_)
13188            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13189            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13190            // The printer writes a bigint the way the language spells one, so a dump is
13191            // unambiguous about which kind of number it is showing.
13192            Value::BigInt(big) => {
13193                self.out.push_str(&big.to_decimal_string());
13194                self.out.push('n');
13195            }
13196            Value::Null => self.out.push_str("null"),
13197            Value::Bool(true) => self.out.push_str("true"),
13198            Value::Bool(false) => self.out.push_str("false"),
13199            Value::Int(number) => self.out.push_str(&number.to_string()),
13200            Value::Float(number) => {
13201                self.out
13202                    .push_str(&crate::value::number_to_string_for_print(*number));
13203            }
13204            Value::String(text) => self.print_string(&text.to_string_lossy()),
13205            Value::Object(object) => self.object(object, level),
13206        }
13207    }
13208
13209    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13210        // A cycle is reported rather than followed; the index is where the object
13211        // already sits in the print stack, which is what the reference shows.
13212        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13213            self.out.push_str(&format!("[circular {index}]"));
13214            return;
13215        }
13216        if object.is_callable() {
13217            let name = object
13218                .own_property("name")
13219                .and_then(|property| property.value)
13220                .map(|value| value.to_js_string())
13221                .unwrap_or_default();
13222            if name.is_empty() {
13223                self.out.push_str("[Function (anonymous)]");
13224            } else {
13225                self.out.push_str(&format!("[Function {name}]"));
13226            }
13227            return;
13228        }
13229        if level >= Self::MAX_DEPTH {
13230            let class = if object.is_array() { "Array" } else { "Object" };
13231            self.out.push_str(&format!("[{class}]"));
13232            return;
13233        }
13234        // `Date` and `Error` print as themselves rather than as bags of properties:
13235        // the ISO string, and `Name: message` followed by the trace.
13236        if let Some(class) = class_of(self.interp, object) {
13237            if class == "Date" {
13238                self.date(object);
13239                return;
13240            }
13241            if class == "Error" {
13242                self.error(object);
13243                return;
13244            }
13245        }
13246        self.stack.push(object.clone());
13247        if object.is_array() {
13248            self.array(object, level);
13249        } else {
13250            self.plain_object(object, level);
13251        }
13252        self.stack.pop();
13253    }
13254
13255    /// A Date prints as its ISO string; an invalid one falls through to the plain
13256    /// object form, the way the reference falls back when `toISOString` throws.
13257    fn date(&mut self, object: &Gc<JsObject>) {
13258        let value = self
13259            .interp
13260            .internal_get(object, "_date_value")
13261            .map(|value| value.to_number());
13262        match value.and_then(crate::builtins::date::iso_string) {
13263            Some(text) => self.out.push_str(&text),
13264            None => self.plain_object(object, 0),
13265        }
13266    }
13267
13268    /// `Name: message`, then the trace with its trailing newline removed.
13269    fn error(&mut self, object: &Gc<JsObject>) {
13270        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13271        self.out.push_str(&name);
13272        if let Some(message) = inherited(object, "message")
13273            && !message.is_empty()
13274        {
13275            self.out.push_str(": ");
13276            self.out.push_str(&message);
13277        }
13278        if let Some(stack) = inherited(object, "stack") {
13279            self.out.push('\n');
13280            self.out.push_str(stack.trim_end_matches('\n'));
13281        }
13282    }
13283
13284    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13285        let elements = object.array_elements().unwrap_or_default();
13286        self.out.push_str("[ ");
13287        // An interior hole means the array is "sparse": the reference prints those
13288        // as `index: value` pairs and says nothing about the holes themselves, while
13289        // a hole run at the end becomes a single `<N empty items>` note.
13290        let last_present = elements
13291            .iter()
13292            .rposition(|value| !matches!(value, Value::Hole));
13293        let has_interior_hole = match last_present {
13294            Some(last) => elements[..last]
13295                .iter()
13296                .any(|value| matches!(value, Value::Hole)),
13297            None => false,
13298        };
13299        let mut first = true;
13300        if has_interior_hole {
13301            let mut index = 0;
13302            while index < elements.len() {
13303                let value = &elements[index];
13304                if matches!(value, Value::Hole) {
13305                    index += 1;
13306                    continue;
13307                }
13308                if !first {
13309                    self.out.push_str(", ");
13310                }
13311                first = false;
13312                self.out.push_str(&format!("{index}: "));
13313                self.value(value, level + 1);
13314                index += 1;
13315            }
13316        } else {
13317            for (index, value) in elements.iter().enumerate() {
13318                if matches!(value, Value::Hole) {
13319                    continue;
13320                }
13321                if !first {
13322                    self.out.push_str(", ");
13323                }
13324                first = false;
13325                let _ = index;
13326                self.value(value, level + 1);
13327            }
13328            if let Some(last) = last_present {
13329                let trailing = elements.len() - last - 1;
13330                if trailing > 0 {
13331                    if !first {
13332                        self.out.push_str(", ");
13333                    }
13334                    self.out.push_str(&format!(
13335                        "<{trailing} empty item{}>",
13336                        if trailing > 1 { "s" } else { "" }
13337                    ));
13338                }
13339            } else if !elements.is_empty() {
13340                let count = elements.len();
13341                self.out.push_str(&format!(
13342                    "<{count} empty item{}>",
13343                    if count > 1 { "s" } else { "" }
13344                ));
13345            }
13346        }
13347        self.out.push_str(" ]");
13348    }
13349
13350    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13351        self.out.push_str("{ ");
13352        let mut first = true;
13353        for key in object.own_keys() {
13354            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13355                continue;
13356            };
13357            if !property.enumerable {
13358                continue;
13359            }
13360            if !first {
13361                self.out.push_str(", ");
13362            }
13363            first = false;
13364            self.out
13365                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13366                    &key.to_string_lossy(),
13367                )));
13368            self.out.push_str(": ");
13369            // An accessor has no value to dump; the reference names the half that
13370            // exists instead of calling it.
13371            if property.is_accessor() {
13372                let text = match (property.getter.is_some(), property.setter.is_some()) {
13373                    (true, true) => "[Getter/Setter]",
13374                    (false, true) => "[Setter]",
13375                    _ => "[Getter]",
13376                };
13377                self.out.push_str(text);
13378            } else {
13379                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13380            }
13381        }
13382        self.out.push_str(" }");
13383    }
13384
13385    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13386    fn print_string(&mut self, text: &str) {
13387        self.out.push('"');
13388        for character in text.chars() {
13389            match character {
13390                '"' => self.out.push_str("\\\""),
13391                '\\' => self.out.push_str("\\\\"),
13392                '\n' => self.out.push_str("\\n"),
13393                '\r' => self.out.push_str("\\r"),
13394                '\t' => self.out.push_str("\\t"),
13395                c if (c as u32) < 0x20 => {
13396                    self.out.push_str(&format!("\\u{:04x}", c as u32));
13397                }
13398                c => self.out.push(c),
13399            }
13400        }
13401        self.out.push('"');
13402    }
13403}
13404
13405/// How `print` renders a value.
13406///
13407/// `ToString`, except that negative zero keeps its sign — the reference's host
13408/// printer does that while `String(-0)` is `"0"`.
13409pub fn display(value: &Value) -> String {
13410    match value {
13411        Value::Float(number) => crate::value::number_to_string_for_print(*number),
13412        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13413            "undefined".to_string()
13414        }
13415        other => other.to_js_string(),
13416    }
13417}
13418
13419// ---------------------------------------------------------------------------
13420// Numeric operators
13421// ---------------------------------------------------------------------------
13422
13423/// `a + b` keeping the `Int` representation when it fits.
13424fn add_numbers(left: Value, right: Value) -> Value {
13425    match (&left, &right) {
13426        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13427            Some(sum) => Value::Int(sum),
13428            None => Value::Float(*a as f64 + *b as f64),
13429        },
13430        _ => Value::Float(left.to_number() + right.to_number()),
13431    }
13432}
13433
13434/// The arithmetic operators other than `+`, which needs string concatenation.
13435fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13436    use Opcode::*;
13437    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13438    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13439    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13440    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13441        return Ok(match op {
13442            And => Value::Int(x & y),
13443            Or => Value::Int(x | y),
13444            Xor => Value::Int(x ^ y),
13445            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13446            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13447            Shr => match (*x as u32) >> ((*y as u32) & 31) {
13448                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13449                shifted => Value::Float(shifted as f64),
13450            },
13451            Sub => match x.checked_sub(*y) {
13452                Some(value) => Value::Int(value),
13453                None => Value::Float(*x as f64 - *y as f64),
13454            },
13455            _ => return arithmetic_slow(op, left, right),
13456        });
13457    }
13458    arithmetic_slow(op, left, right)
13459}
13460
13461/// [`arithmetic`] for everything the integer fast path above does not take.
13462fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13463    use Opcode::*;
13464    let (a, b) = (left.to_number(), right.to_number());
13465    Ok(match op {
13466        Sub => match (&left, &right) {
13467            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13468                Some(value) => Value::Int(value),
13469                None => Value::Float(a - b),
13470            },
13471            _ => Value::Float(a - b),
13472        },
13473        Mul => Value::Float(a * b),
13474        Div => Value::Float(a / b),
13475        Mod => Value::Float(js_mod(a, b)),
13476        Pow => Value::Float(a.powf(b)),
13477        And => Value::Int(left.to_int32() & right.to_int32()),
13478        Or => Value::Int(left.to_int32() | right.to_int32()),
13479        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13480        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13481        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13482        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13483        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13484        // fits the small-integer representation stays an `Int`; the rest become a
13485        // float, which is how the reference keeps `n >>> 0` non-negative.
13486        Shr => {
13487            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13488            match i32::try_from(shifted) {
13489                Ok(value) => Value::Int(value),
13490                Err(_) => Value::Float(shifted as f64),
13491            }
13492        }
13493        _ => Value::Float(a),
13494    })
13495}
13496
13497/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13498///
13499/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13500/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13501/// slow path where the rules live.
13502fn is_number(value: &Value) -> bool {
13503    matches!(value, Value::Int(_) | Value::Float(_))
13504}
13505
13506/// The `Value::Bool` a comparison operator answers for `ordering`.
13507///
13508/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13509/// false for it, including `<=` and `>=`.
13510fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13511    use Opcode::*;
13512    let answer = match (op, ordering) {
13513        (_, None) => false,
13514        (Lt, Some(ordering)) => ordering.is_lt(),
13515        (Lte, Some(ordering)) => ordering.is_le(),
13516        (Gt, Some(ordering)) => ordering.is_gt(),
13517        (Gte, Some(ordering)) => ordering.is_ge(),
13518        _ => false,
13519    };
13520    Value::Bool(answer)
13521}
13522
13523/// `%`, which follows the sign of the dividend rather than Rust's.
13524fn js_mod(left: f64, right: f64) -> f64 {
13525    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13526        return f64::NAN;
13527    }
13528    if right.is_infinite() {
13529        return left;
13530    }
13531    let remainder = left % right;
13532    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13533    // the spec makes the sign match the dividend.
13534    if remainder == 0.0 {
13535        0.0f64.copysign(left)
13536    } else {
13537        remainder
13538    }
13539}
13540
13541fn negate(value: Value) -> Value {
13542    match value {
13543        Value::Int(0) => Value::Float(-0.0),
13544        Value::Int(i) => Value::Int(-i),
13545        other => Value::Float(-other.to_number()),
13546    }
13547}
13548
13549fn increment(value: Value) -> Value {
13550    match value {
13551        Value::Int(i) => match i.checked_add(1) {
13552            Some(next) => Value::Int(next),
13553            None => Value::Float(i as f64 + 1.0),
13554        },
13555        other => Value::Float(other.to_number() + 1.0),
13556    }
13557}
13558
13559fn decrement(value: Value) -> Value {
13560    match value {
13561        Value::Int(i) => match i.checked_sub(1) {
13562            Some(next) => Value::Int(next),
13563            None => Value::Float(i as f64 - 1.0),
13564        },
13565        other => Value::Float(other.to_number() - 1.0),
13566    }
13567}
13568
13569/// Compare a `BigInt` with an `f64` on their mathematical values.
13570///
13571/// Neither side is rounded to the other's precision: the number is split into its integer
13572/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13573/// when the integer parts are equal. An infinite value is larger than every bigint.
13574fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13575    use std::cmp::Ordering;
13576    if number.is_nan() {
13577        return None;
13578    }
13579    if number.is_infinite() {
13580        return Some(if number > 0.0 {
13581            Ordering::Less
13582        } else {
13583            Ordering::Greater
13584        });
13585    }
13586    let truncated = number.trunc();
13587    // A number wider than `i128` still has an exact integer part, but no bigint form we can
13588    // build cheaply; the sign of the difference is all that is needed, so compare against
13589    // the bigint's own magnitude instead.
13590    if truncated.abs() >= 1.7e38 {
13591        let big_as_f64 = big.to_f64();
13592        return big_as_f64.partial_cmp(&number);
13593    }
13594    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13595    match big.cmp(&integer) {
13596        Ordering::Equal => {
13597            // Same integer part: the fraction decides, and a negative number's fraction is
13598            // below the integer (`-1.5` truncates to `-1`).
13599            if number > truncated {
13600                Some(Ordering::Less)
13601            } else if number < truncated {
13602                Some(Ordering::Greater)
13603            } else {
13604                Some(Ordering::Equal)
13605            }
13606        }
13607        other => Some(other),
13608    }
13609}