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        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1520        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1521        // checks it.
1522        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1523        self.realm
1524            .iterator_protos
1525            .insert(tag.to_string(), proto.clone());
1526        proto
1527    }
1528
1529    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1530    ///
1531    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1532    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1533    /// produced. That is why the two branches are not merged.
1534    pub fn object_own_property_keys(
1535        &mut self,
1536        object: &Gc<JsObject>,
1537    ) -> JsResult<Vec<PropertyKey>> {
1538        if let Some(keys) = self.proxy_own_keys(object)? {
1539            return Ok(keys);
1540        }
1541        // Integer-like keys ascending, then the string keys in insertion order, then the
1542        // symbols — the order every schema that walks an object expects.
1543        let entries = object.property_entries();
1544        let mut numeric: Vec<u32> = Vec::new();
1545        // An integer-indexed exotic object reports its indices as own keys even though they
1546        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1547        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1548        // order). The length is asked per call, so a resizable buffer's view reports the
1549        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1550        if object.typed_array_parts().is_some() {
1551            for index in 0..object.typed_array_length().unwrap_or(0) {
1552                // `u32::try_from` cannot fail for a real length, but the length is a
1553                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1554                // as an array index and one element beyond is not.
1555                match u32::try_from(index) {
1556                    Ok(index) => numeric.push(index),
1557                    Err(_) => break,
1558                }
1559            }
1560        }
1561        let mut strings: Vec<PropertyKey> = Vec::new();
1562        let mut symbols: Vec<PropertyKey> = Vec::new();
1563        for (key, _) in entries {
1564            match &key {
1565                // A class-private name is never reported by any enumeration: that is the
1566                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1567                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1568                // symbol skip, `Object.assign`) therefore cannot see it.
1569                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1570                PropertyKey::Symbol(_) => symbols.push(key),
1571                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1572                    Some(index) => {
1573                        if !numeric.contains(&index) {
1574                            numeric.push(index);
1575                        }
1576                    }
1577                    None => strings.push(key),
1578                },
1579            }
1580        }
1581        numeric.sort_unstable();
1582        let mut keys: Vec<PropertyKey> = numeric
1583            .into_iter()
1584            .map(|index| PropertyKey::from(index.to_string()))
1585            .collect();
1586        keys.extend(strings);
1587        keys.extend(symbols);
1588        Ok(keys)
1589    }
1590
1591    /// The state behind a promise object, or `None` when `object` is not one.
1592    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1593        object.with(|data| match &data.kind {
1594            ObjectKind::Promise(state) => Some(state.clone()),
1595            _ => None,
1596        })
1597    }
1598
1599    /// A new pending promise.
1600    pub fn new_promise(&mut self) -> Gc<JsObject> {
1601        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1602        // the one place every promise is built, and a subclass that builds its instances
1603        // somewhere else would be invisible to `instanceof`.
1604        let default = self.realm.promise_proto.clone();
1605        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1606        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1607        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1608        // `prototype` getter therefore still gets a working promise; the alternative is a
1609        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1610        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1611        let promise = JsObject::ordinary(self.heap, proto);
1612        promise.with_mut(|data| {
1613            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1614                crate::object::PromiseState::default(),
1615            )));
1616        });
1617        promise
1618    }
1619
1620    /// Fulfil `promise`, unless it has already settled.
1621    ///
1622    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1623    /// after `reject`, changes nothing.
1624    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1625        let Some(state) = self.promise_state(promise) else {
1626            return;
1627        };
1628        let reactions = {
1629            let mut state = state.borrow_mut();
1630            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1631                return;
1632            }
1633            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1634            std::mem::take(&mut state.reactions)
1635        };
1636        self.queue_reactions(reactions, value, false);
1637    }
1638
1639    /// Reject `promise`, unless it has already settled.
1640    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1641        let Some(state) = self.promise_state(promise) else {
1642            return;
1643        };
1644        let reactions = {
1645            let mut state = state.borrow_mut();
1646            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1647                return;
1648            }
1649            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1650            std::mem::take(&mut state.reactions)
1651        };
1652        // Remember it only when nothing is listening *now*; a `then` registered later
1653        // prunes the entry in `perform_then`.
1654        if reactions.is_empty() {
1655            self.unhandled.push((promise.clone(), reason.clone()));
1656        }
1657        self.queue_reactions(reactions, reason, true);
1658    }
1659
1660    /// Queue one job per reaction.
1661    ///
1662    /// This is what makes `then` asynchronous even on an already-settled promise:
1663    /// `p.then(f); g()` calls `g` first.
1664    fn queue_reactions(
1665        &mut self,
1666        reactions: Vec<crate::object::PromiseReaction>,
1667        argument: Value,
1668        rejected: bool,
1669    ) {
1670        for reaction in reactions {
1671            let handler = if rejected {
1672                reaction.on_rejected.clone()
1673            } else {
1674                reaction.on_fulfilled.clone()
1675            };
1676            self.jobs.push_back(Job::Reaction {
1677                handler,
1678                argument: argument.clone(),
1679                rejected,
1680                promise: reaction.promise,
1681            });
1682        }
1683    }
1684
1685    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1686    /// resolve/reject pair.
1687    ///
1688    /// The pair are callable objects rather than Rust closures, because the script gets
1689    /// them and may stash them for later.
1690    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1691        let promise = self.new_promise();
1692        // Both handlers are built-ins with an empty name and length 1, in
1693        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1694        // off `Object.getOwnPropertyNames`.
1695        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1696        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1697        (promise, Value::Object(resolve), Value::Object(reject))
1698    }
1699
1700    /// §27.2.1.5 `NewPromiseCapability(C)`.
1701    ///
1702    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1703    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1704    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1705    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1706    /// silently ignored argument.
1707    ///
1708    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1709    /// the engine's own executor is exactly what `new_promise_capability` builds.
1710    pub fn new_promise_capability_for(
1711        &mut self,
1712        constructor: &Value,
1713    ) -> JsResult<(Value, Value, Value)> {
1714        let Some(object) = constructor.as_object().cloned() else {
1715            return Err(self.type_error("promise constructor is not a constructor"));
1716        };
1717        if !object.is_constructor() {
1718            return Err(self.type_error("promise constructor is not a constructor"));
1719        }
1720        if self
1721            .realm
1722            .promise_constructor
1723            .as_ref()
1724            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1725        {
1726            let (promise, resolve, reject) = self.new_promise_capability();
1727            return Ok((Value::Object(promise), resolve, reject));
1728        }
1729        let state = self.new_object(Some(self.realm.object_proto.clone()));
1730        let executor = self.builtin_function(
1731            "",
1732            1,
1733            Callable::CapabilityExecutor {
1734                state: state.clone(),
1735            },
1736        );
1737        let promise = self.construct(
1738            Value::Object(object.clone()),
1739            Value::Object(object),
1740            vec![Value::Object(executor)],
1741        )?;
1742        // The pair is read *after* the constructor returns, so a constructor that never
1743        // called its executor, or called it with non-callables, is the spec's step 11
1744        // `TypeError` — not something the engine can paper over.
1745        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1746            return Err(self.type_error("promise executor never ran"));
1747        };
1748        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1749            return Err(self.type_error("promise executor never ran"));
1750        };
1751        for handler in [&resolve, &reject] {
1752            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1753                return Err(self.type_error("promise capability handler is not callable"));
1754            }
1755        }
1756        Ok((promise, resolve, reject))
1757    }
1758
1759    /// §27.2.3.1 `PromiseResolve(C, x)`.
1760    ///
1761    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1762    /// an `x` that is already a promise of exactly this constructor is handed back
1763    /// unchanged, and anything else gets a fresh capability from `C`.
1764    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1765        if let Value::Object(object) = &value
1766            && self.promise_state(object).is_some()
1767        {
1768            // `x.constructor === C` means "already the right kind", so no capability is
1769            // built — which is observable through a `resolve` that counts its calls.
1770            let x_constructor = self.get_property(object, "constructor")?;
1771            let same = match (
1772                x_constructor.as_ref().and_then(Value::as_object),
1773                constructor.as_object(),
1774            ) {
1775                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1776                _ => false,
1777            };
1778            if same {
1779                return Ok(value);
1780            }
1781        }
1782        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1783        self.call_value(resolve, Value::Undefined, vec![value])?;
1784        Ok(promise)
1785    }
1786
1787    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1788    /// promise, as `{ value: completion }`.
1789    ///
1790    /// The three cases are the reference's, and they differ on purpose:
1791    ///
1792    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1793    ///   exception before any promise exists;
1794    /// * a **runtime** error rejects the returned promise;
1795    /// * success resolves it with `{ value }`, where the value is the script's completion
1796    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1797    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1798    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1799    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1800    ///
1801    /// # What this does not do
1802    ///
1803    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1804    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1805    /// the parser and the suspension machinery to accept a suspended top-level script, and
1806    /// is not implemented — such source is a syntax error here. Everything else about the
1807    /// flag is reproduced.
1808    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1809        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1810        // too, and the reference truncates that one at the same place as a runtime failure.
1811        if barrier {
1812            let depth = self.frames.len();
1813            self.trace_barriers.push(depth);
1814        }
1815        // Compiled before the promise exists, so a parse failure propagates as a throw
1816        // instead of being folded into a rejection.
1817        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1818            Ok(compiled) => compiled,
1819            Err(error) => {
1820                if barrier {
1821                    self.trace_barriers.pop();
1822                }
1823                return Err(error);
1824            }
1825        };
1826        // An async body answers its own promise, and that promise is what the reference
1827        // hands back — the same object, not a wrapper around it. Its resolution value is
1828        // the `{value}` object the compiled epilogue built.
1829        if compiled.kind.is_async() {
1830            let strict = compiled.strict;
1831            let promise = self.run_eval_script(compiled, strict)?;
1832            if barrier {
1833                self.trace_barriers.pop();
1834            }
1835            return Ok(promise);
1836        }
1837        let (promise, resolve, reject) = self.new_promise_capability();
1838        let strict = compiled.strict;
1839        match self.run_eval_script(compiled, strict) {
1840            Ok(value) => {
1841                // `{ value }` is a plain object, so resolving with it adopts nothing even
1842                // when the completion value is itself a promise.
1843                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1844                self.set_property(&wrapped, "value", value)?;
1845                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1846            }
1847            Err(Signal::Throw(error)) => {
1848                self.call_value(reject, Value::Undefined, vec![error])?;
1849            }
1850            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1851        }
1852        if barrier {
1853            self.trace_barriers.pop();
1854        }
1855        Ok(Value::Object(promise))
1856    }
1857
1858    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1859    ///
1860    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1861    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1862    /// timer table, where the collector already scans it.
1863    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1864        let (promise, resolve, _reject) = self.new_promise_capability();
1865        let resolve = self.new_host_function(
1866            "resolve",
1867            1,
1868            Box::new(
1869                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1870                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1871                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1872                },
1873            ),
1874        );
1875        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1876        // timer table is part of what the collector walks.
1877        self.schedule_timer(Value::Object(resolve), delay_ms);
1878        Ok(Value::Object(promise))
1879    }
1880
1881    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1882    /// new promise resolved with it.
1883    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1884        if let Value::Object(object) = &value
1885            && self.promise_state(object).is_some()
1886        {
1887            return Ok(value);
1888        }
1889        let promise = self.new_promise();
1890        self.resolve_promise_with(&promise, value)?;
1891        Ok(Value::Object(promise))
1892    }
1893
1894    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1895    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1896        // Resolving a promise with itself is a `TypeError`. The check exists because the
1897        // alternative is a chain of self-reactions that never settles.
1898        if let Value::Object(object) = &value
1899            && object.ptr_eq(promise)
1900        {
1901            // The spec rejects *and* throws, so both the promise and the caller see it.
1902            let thrown = self.type_error("cannot resolve a promise with itself");
1903            let Signal::Throw(error) = thrown.clone() else {
1904                unreachable!("type_error always throws")
1905            };
1906            self.reject_promise(promise, error);
1907            return Err(thrown);
1908        }
1909        let then = match &value {
1910            Value::Object(object) => self.get_property(object, "then")?,
1911            _ => None,
1912        };
1913        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1914        if !callable_then {
1915            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1916            self.fulfill_promise(promise, value);
1917            return Ok(());
1918        }
1919        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1920        // inside `resolve`, so a script cannot make a promise settle synchronously.
1921        self.jobs.push_back(Job::Thenable {
1922            then: then.expect("checked callable"),
1923            value,
1924            promise: promise.clone(),
1925        });
1926        Ok(())
1927    }
1928
1929    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1930    ///
1931    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1932    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1933    ///
1934    /// The property read is **not** short-circuitable even for a real promise: the spec says
1935    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1936    /// expects it to run. Skipping the read for promises not only lost the throw, it made
1937    /// the combinator's loop infinite — the test's iterator never sets `done`.
1938    pub fn invoke_then(
1939        &mut self,
1940        thenable: Value,
1941        on_fulfilled: Value,
1942        on_rejected: Value,
1943    ) -> JsResult<()> {
1944        let then = match &thenable {
1945            Value::Object(object) => self.get_property(object, "then")?,
1946            primitive => {
1947                let boxed = self.object_from(primitive)?;
1948                self.get_property(&boxed, "then")?
1949            }
1950        };
1951        let Some(then) = then else {
1952            return Err(self.type_error("thenable has no then method"));
1953        };
1954        if !matches!(&then, Value::Object(object) if object.is_callable()) {
1955            return Err(self.type_error("then is not a function"));
1956        }
1957        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1958        Ok(())
1959    }
1960
1961    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1962    ///
1963    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1964    /// promise.
1965    pub fn perform_then(
1966        &mut self,
1967        promise: &Gc<JsObject>,
1968        on_fulfilled: Option<Value>,
1969        on_rejected: Option<Value>,
1970    ) -> JsResult<Value> {
1971        let Some(state) = self.promise_state(promise) else {
1972            return Err(self.type_error("not a promise"));
1973        };
1974        // Whether a rejection handler is being attached decides whether a recorded
1975        // rejection stops being unhandled, so it is read before the values are moved.
1976        let has_rejection_handler = on_rejected.is_some();
1977        let derived = self.new_promise();
1978        let reaction = crate::object::PromiseReaction {
1979            on_fulfilled,
1980            on_rejected,
1981            promise: derived.clone(),
1982        };
1983        let settled = {
1984            let mut state = state.borrow_mut();
1985            // A rejection somebody reacts to is no longer unhandled.
1986            state.handled = true;
1987            match &state.status {
1988                crate::object::PromiseStatus::Pending => {
1989                    state.reactions.push(reaction.clone());
1990                    None
1991                }
1992                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1993                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1994            }
1995        };
1996        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1997        // later, means somebody is listening after all.
1998        if has_rejection_handler {
1999            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2000        }
2001        if let Some((argument, rejected)) = settled {
2002            let handler = if rejected {
2003                reaction.on_rejected
2004            } else {
2005                reaction.on_fulfilled
2006            };
2007            self.jobs.push_back(Job::Reaction {
2008                handler,
2009                argument,
2010                rejected,
2011                promise: reaction.promise,
2012            });
2013        }
2014        Ok(Value::Object(derived))
2015    }
2016
2017    /// The rejections nobody listened to, formatted the way the reference reports them.
2018    ///
2019    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2020    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2021    /// unhandled at the point the queue drains, because a `then` may still be attached
2022    /// before the host acts on it.
2023    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2024        let entries = std::mem::take(&mut self.unhandled);
2025        // Somebody may have attached a handler after the rejection was recorded, so the
2026        // promise is the authority rather than the list.
2027        let still_unhandled: Vec<Value> = entries
2028            .into_iter()
2029            .filter_map(|(promise, reason)| {
2030                let handled = self
2031                    .promise_state(&promise)
2032                    .map(|state| state.borrow().handled)
2033                    .unwrap_or(true);
2034                (!handled).then_some(reason)
2035            })
2036            .collect();
2037        still_unhandled
2038            .into_iter()
2039            .map(|reason| {
2040                let text = self.describe_exception(&reason);
2041                let stack = match &reason {
2042                    Value::Object(object) => self
2043                        .get_property(object, "stack")
2044                        .ok()
2045                        .flatten()
2046                        .map(|value| value.to_js_string())
2047                        // `stack` carries a trailing newline of its own, which would leave
2048                        // a blank line between two reported rejections.
2049                        .map(|text| text.trim_end().to_string())
2050                        .unwrap_or_default(),
2051                    _ => String::new(),
2052                };
2053                if stack.is_empty() {
2054                    format!("Possibly unhandled promise rejection: {text}")
2055                } else {
2056                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2057                }
2058            })
2059            .collect()
2060    }
2061
2062    /// Run the microtask queue to exhaustion.
2063    ///
2064    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2065    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2066    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2067    ///
2068    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2069    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2070    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2071    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2072        crate::builtins::json::parse_text(self, text, true)
2073    }
2074
2075    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2076    ///
2077    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2078    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2079    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2080    ///
2081    /// The callback is called with **no arguments**. The reference stores only the function
2082    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2083    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2084    /// extra arguments arrive as `undefined`.
2085    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2086        let id = self.next_timer_id;
2087        // Wrap rather than grow: the id reaches the script as an `Int32`.
2088        self.next_timer_id = if self.next_timer_id == i32::MAX {
2089            1
2090        } else {
2091            self.next_timer_id + 1
2092        };
2093        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2094        self.tasks.push(Task::Timer {
2095            id,
2096            callback,
2097            due_at,
2098        });
2099        id
2100    }
2101
2102    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2103    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2104    pub fn cancel_timer(&mut self, id: i32) -> bool {
2105        let before = self.tasks.len();
2106        self.tasks.retain(|task| match task {
2107            Task::Timer { id: task_id, .. } => *task_id != id,
2108        });
2109        self.tasks.len() != before
2110    }
2111
2112    /// How long until the earliest pending timer, or `None` when none is pending.
2113    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2114        let now = std::time::Instant::now();
2115        self.tasks
2116            .iter()
2117            .map(|task| match task {
2118                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2119            })
2120            .min()
2121    }
2122
2123    /// Run one turn of the event loop.
2124    ///
2125    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2126    /// run at most one due timer, then drain again. The blocking belongs to the caller
2127    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2128    /// is how it asks.
2129    ///
2130    /// One timer per turn rather than all of them: a timer callback may schedule another
2131    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2132    /// starve the microtask queue.
2133    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2134        self.drain_jobs()?;
2135        let now = std::time::Instant::now();
2136        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2137        // followed by `setTimeout(g, 1)` must run `g` first.
2138        let due = self
2139            .tasks
2140            .iter()
2141            .enumerate()
2142            .filter(|(_, task)| match task {
2143                Task::Timer { due_at, .. } => *due_at <= now,
2144            })
2145            .min_by_key(|(_, task)| match task {
2146                Task::Timer { due_at, .. } => *due_at,
2147            })
2148            .map(|(index, _)| index);
2149        let Some(index) = due else {
2150            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2151            // descriptor is registered but no timer is closer, so a script that never
2152            // touches the descriptor still gets control back. Without a cap a handler on a
2153            // descriptor that is never ready would block for as long as the host allows.
2154            let timeout = self
2155                .next_timeout()
2156                .unwrap_or(std::time::Duration::from_secs(10))
2157                .min(std::time::Duration::from_secs(10));
2158            if !self.fd_handlers.is_empty() {
2159                // Blocking on a timer while descriptors are registered would starve them,
2160                // and blocking on the descriptors while a timer is due would delay it; the
2161                // host polls with the earlier of the two deadlines, which this timeout is.
2162                return Ok(Turn::Poll(timeout));
2163            }
2164            return Ok(match self.next_timeout() {
2165                Some(wait) => Turn::Wait(wait),
2166                None => Turn::Done,
2167            });
2168        };
2169        let Task::Timer { callback, .. } = self.tasks.remove(index);
2170        let this = Value::Undefined;
2171        // A throwing timer callback must not stop the loop: the reference reports it and
2172        // keeps going, because the alternative is that one bad timer silently stops every
2173        // later one.
2174        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2175        match self.call_value(callback, this, Vec::new()) {
2176            Ok(_) => {}
2177            Err(Signal::Throw(value)) => {
2178                let text = self.describe_exception(&value);
2179                self.timer_errors.push(text);
2180            }
2181            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2182        }
2183        self.drain_jobs()?;
2184        Ok(Turn::Ran)
2185    }
2186
2187    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2188    ///
2189    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2190    /// left is removed — the reference does the same, so a script can rely on
2191    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2192    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2193        let entry = self.fd_handlers.entry(fd).or_default();
2194        if readable {
2195            entry.read = callback;
2196        } else {
2197            entry.write = callback;
2198        }
2199        if entry.read.is_none() && entry.write.is_none() {
2200            self.fd_handlers.remove(&fd);
2201        }
2202    }
2203
2204    /// Register or clear an `os.signal` handler.
2205    ///
2206    /// `None` removes it; the host separately restores the default disposition or sets
2207    /// ignore, because which of those happened is the script's choice (`null` versus
2208    /// `undefined`) and not something this table can express.
2209    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2210        match handler {
2211            Some(handler) => {
2212                self.signal_handlers.insert(signal, handler);
2213            }
2214            None => {
2215                self.signal_handlers.remove(&signal);
2216            }
2217        }
2218    }
2219
2220    /// Run the handler for `signal`, reporting whether one ran.
2221    ///
2222    /// A throwing handler is reported and the loop continues, like a timer's.
2223    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2224        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2225            return Ok(false);
2226        };
2227        match self.call_value(handler, Value::Undefined, Vec::new()) {
2228            Ok(_) => {}
2229            Err(Signal::Throw(value)) => {
2230                let text = self.describe_exception(&value);
2231                self.timer_errors.push(text);
2232            }
2233            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2234        }
2235        self.drain_jobs()?;
2236        Ok(true)
2237    }
2238
2239    /// The descriptors the host has to poll, and in which direction.
2240    ///
2241    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2242    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2243    /// `os_poll` asks for.
2244    pub fn pending_fds(&self) -> Vec<FdInterest> {
2245        self.fd_handlers
2246            .iter()
2247            .map(|(fd, entry)| FdInterest {
2248                fd: *fd,
2249                read: entry.read.is_some(),
2250                write: entry.write.is_some(),
2251            })
2252            .collect()
2253    }
2254
2255    /// Call the handler registered for `fd`, reporting whether one ran.
2256    ///
2257    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2258    /// poll iteration and then restarts the loop, because the handler may have changed the
2259    /// registration list underneath it; doing the same here keeps a handler that
2260    /// unregisters itself from being called with stale state.
2261    ///
2262    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2263    /// every later one, exactly as with timers.
2264    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2265        let Some(entry) = self.fd_handlers.get(&fd) else {
2266            return Ok(false);
2267        };
2268        let callback = if readable {
2269            entry.read.clone()
2270        } else if writable {
2271            entry.write.clone()
2272        } else {
2273            None
2274        };
2275        let Some(callback) = callback else {
2276            return Ok(false);
2277        };
2278        self.drain_jobs()?;
2279        match self.call_value(callback, Value::Undefined, Vec::new()) {
2280            Ok(_) => {}
2281            Err(Signal::Throw(value)) => {
2282                let text = self.describe_exception(&value);
2283                self.timer_errors.push(text);
2284            }
2285            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2286        }
2287        self.drain_jobs()?;
2288        Ok(true)
2289    }
2290
2291    /// Take the errors timer callbacks threw, leaving the list empty.
2292    pub fn take_timer_errors(&mut self) -> Vec<String> {
2293        std::mem::take(&mut self.timer_errors)
2294    }
2295
2296    /// Whether anything is still pending: a microtask or a timer.
2297    pub fn has_pending_work(&self) -> bool {
2298        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2299    }
2300
2301    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2302    pub fn has_pending_timers_or_jobs(&self) -> bool {
2303        !self.jobs.is_empty() || !self.tasks.is_empty()
2304    }
2305
2306    /// Run every queued microtask, including ones queued while draining.
2307    pub fn drain_jobs(&mut self) -> JsResult<()> {
2308        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2309        // would spin forever, so the drain is bounded the way the call stack is.
2310        let mut budget = 1_000_000usize;
2311        while let Some(job) = self.jobs.pop_front() {
2312            if budget == 0 {
2313                return Err(Signal::Throw(
2314                    self.make_error("InternalError", "promise job queue did not drain"),
2315                ));
2316            }
2317            budget -= 1;
2318            self.run_job(job)?;
2319            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2320            // engine may run script that the script itself did not ask for. Doing it here
2321            // rather than from a drop hook is what keeps the callback out of arbitrary
2322            // engine bookkeeping — see `builtins::weak`'s header.
2323            crate::builtins::weak::drain_finalizers(self)?;
2324        }
2325        // A script that queued no jobs may still have dropped targets, so the checkpoint
2326        // runs once more after the queue empties.
2327        crate::builtins::weak::drain_finalizers(self)?;
2328        Ok(())
2329    }
2330
2331    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2332    ///
2333    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2334    /// `None` and is swept out here. This is also where the realm learns that a registry
2335    /// died, which is why it is a mutation rather than a read.
2336    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2337        let handles = std::mem::take(&mut self.realm.finalization_registries);
2338        let mut live = Vec::with_capacity(handles.len());
2339        for handle in handles {
2340            let Some(object) = handle.upgrade() else {
2341                continue;
2342            };
2343            let Some(state) = object.finalization_state() else {
2344                continue;
2345            };
2346            live.push((object.clone(), *state));
2347            self.realm.finalization_registries.push(object.downgrade());
2348        }
2349        live
2350    }
2351
2352    /// Run one microtask.
2353    fn run_job(&mut self, job: Job) -> JsResult<()> {
2354        match job {
2355            Job::Reaction {
2356                handler: None,
2357                argument,
2358                rejected,
2359                promise,
2360            } => {
2361                // No handler: the settlement passes straight through to the derived
2362                // promise, which is why `p.catch(f)` ignores fulfilments.
2363                if rejected {
2364                    self.reject_promise(&promise, argument);
2365                } else {
2366                    self.fulfill_promise(&promise, argument);
2367                }
2368                Ok(())
2369            }
2370            Job::Reaction {
2371                handler: Some(handler),
2372                argument,
2373                promise,
2374                ..
2375            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2376                Ok(answer) => {
2377                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2378                        self.reject_promise(&promise, error);
2379                    }
2380                    Ok(())
2381                }
2382                Err(Signal::Throw(reason)) => {
2383                    self.reject_promise(&promise, reason);
2384                    Ok(())
2385                }
2386                Err(other) => Err(other),
2387            },
2388            Job::Thenable {
2389                then,
2390                value,
2391                promise,
2392            } => {
2393                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2394                // the value it produces settles `promise`.
2395                // The thenable's `then` gets this promise's own pair, so whatever it
2396                // produces settles `promise`.
2397                let resolve = JsObject::function(
2398                    self.heap,
2399                    Some(self.realm.function_proto.clone()),
2400                    Callable::PromiseResolve(promise.clone()),
2401                );
2402                let reject = JsObject::function(
2403                    self.heap,
2404                    Some(self.realm.function_proto.clone()),
2405                    Callable::PromiseReject(promise.clone()),
2406                );
2407                match self.call_value(
2408                    then,
2409                    value,
2410                    vec![Value::Object(resolve), Value::Object(reject)],
2411                ) {
2412                    Ok(_) => Ok(()),
2413                    Err(Signal::Throw(reason)) => {
2414                        self.reject_promise(&promise, reason);
2415                        Ok(())
2416                    }
2417                    Err(other) => Err(other),
2418                }
2419            }
2420            Job::Resume {
2421                coroutine,
2422                promise,
2423                kind,
2424                value,
2425            } => self.drive_async(&coroutine, &promise, kind, value),
2426            Job::GeneratorResume {
2427                generator,
2428                promise,
2429                kind,
2430                value,
2431            } => self.step_async_generator(&generator, &promise, kind, value),
2432            Job::Import {
2433                specifier,
2434                referrer,
2435                promise,
2436            } => {
2437                self.run_dynamic_import(&specifier, &referrer, &promise);
2438                Ok(())
2439            }
2440        }
2441    }
2442
2443    /// One element of a `Promise` combinator settled.
2444    ///
2445    /// The shared state object holds the result array, the number still outstanding, and
2446    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2447    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2448    /// to settle, only whatever `Sub` said a capability is.
2449    ///
2450    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2451    /// and `any` must ignore every later settlement, and `all` must not report a second
2452    /// rejection after the first.
2453    fn settle_combinator(
2454        &mut self,
2455        state: &Gc<JsObject>,
2456        index: usize,
2457        fulfilled: bool,
2458        value: Value,
2459    ) -> JsResult<()> {
2460        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2461        // Each element settles at most once: a thenable may call `onFulfilled` twice
2462        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2463        // call a no-op. Without it the second call decremented `remaining` again and settled
2464        // `all` with a short values array (`call-resolve-element-items`).
2465        let done = field("done");
2466        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2467        let settled = field("settled").is_some_and(|value| value.to_boolean());
2468        if settled {
2469            return Ok(());
2470        }
2471        if let Some(Value::Object(done)) = &done {
2472            if done
2473                .array_get(index)
2474                .is_some_and(|value| value.to_boolean())
2475            {
2476                return Ok(());
2477            }
2478            done.array_set(self.heap, index, Value::Bool(true));
2479        }
2480        let resolve = field("resolve");
2481        let reject = field("reject");
2482        let results = field("results").and_then(|value| value.as_object().cloned());
2483        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2484        // promise: the handler is a plain function the constructor chose.
2485        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2486            if let Some(handler) = handler {
2487                interp.call_value(handler, Value::Undefined, vec![value])?;
2488            }
2489            Ok(())
2490        };
2491        match kind {
2492            // `race`: the first settlement wins and stops the rest.
2493            3 => {
2494                state.define_data("settled", Value::Bool(true));
2495                let handler = if fulfilled { resolve } else { reject };
2496                settle_with(self, handler, value)?;
2497                return Ok(());
2498            }
2499            // `all`: the first rejection wins outright.
2500            0 if !fulfilled => {
2501                state.define_data("settled", Value::Bool(true));
2502                settle_with(self, reject, value)?;
2503                return Ok(());
2504            }
2505            // `any`: the first fulfilment wins.
2506            2 if fulfilled => {
2507                state.define_data("settled", Value::Bool(true));
2508                settle_with(self, resolve, value)?;
2509                return Ok(());
2510            }
2511            _ => {}
2512        }
2513        let Some(results) = &results else {
2514            return Ok(());
2515        };
2516        match kind {
2517            0 => {
2518                results.array_set(self.heap, index, value);
2519            }
2520            // `allSettled` never rejects; each slot records what happened.
2521            1 => {
2522                let record = self.new_object(Some(self.realm.object_proto.clone()));
2523                if fulfilled {
2524                    record.define_data("status", self.string("fulfilled"));
2525                    record.define_data("value", value);
2526                } else {
2527                    record.define_data("status", self.string("rejected"));
2528                    record.define_data("reason", value);
2529                }
2530                results.array_set(self.heap, index, Value::Object(record));
2531            }
2532            // `any`: a rejection is parked in the errors array and the sweep continues.
2533            2 => {
2534                results.array_set(self.heap, index, value);
2535            }
2536            _ => {}
2537        }
2538        let remaining = field("remaining")
2539            .map(|value| value.to_int32())
2540            .unwrap_or(0);
2541        let left = remaining - 1;
2542        state.define_data("remaining", Value::Int(left));
2543        if left != 0 {
2544            return Ok(());
2545        }
2546        state.define_data("settled", Value::Bool(true));
2547        match kind {
2548            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2549            2 => {
2550                // The rejection is an `AggregateError` whose `errors` is the results array
2551                // itself — the slots are the reasons, in input order.
2552                let errors = results.array_elements().unwrap_or_default();
2553                let error = self.aggregate_error(errors, "all promises were rejected");
2554                settle_with(self, reject, error)?;
2555            }
2556            _ => {}
2557        }
2558        Ok(())
2559    }
2560
2561    /// Build an async function's result: a promise whose body runs as a coroutine.
2562    pub fn new_async_function(
2563        &mut self,
2564        function: Value,
2565        this: Value,
2566        args: Vec<Value>,
2567    ) -> JsResult<Value> {
2568        let promise = self.new_promise();
2569        let coroutine = self.new_coroutine(function, this, args)?;
2570        if let Err(Signal::Throw(reason)) =
2571            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2572        {
2573            self.reject_promise(&promise, reason);
2574        }
2575        Ok(Value::Object(promise))
2576    }
2577
2578    /// The coroutine an async body runs in.
2579    ///
2580    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2581    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2582    /// than growing a second state machine. The difference is only in the ending — a
2583    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2584    /// Run `code` as an async function body, answering the promise it settles.
2585    ///
2586    /// Used for a module with top-level `await`: its body is an async function whose
2587    /// caller is the host, so there is no function object to pass through
2588    /// [`Interp::new_async_function`].
2589    pub fn run_async_body(
2590        &mut self,
2591        code: Gc<CompiledCode>,
2592        env: Gc<ClosureEnv>,
2593        this: Value,
2594    ) -> JsResult<Value> {
2595        let promise = self.new_promise();
2596        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2597        if let Err(Signal::Throw(reason)) =
2598            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2599        {
2600            self.reject_promise(&promise, reason);
2601        }
2602        Ok(Value::Object(promise))
2603    }
2604
2605    fn new_coroutine(
2606        &mut self,
2607        function: Value,
2608        this: Value,
2609        args: Vec<Value>,
2610    ) -> JsResult<Gc<JsObject>> {
2611        let Some(object) = function.as_object().cloned() else {
2612            return Err(self.type_error("not a function"));
2613        };
2614        let Some((code, env)) = bytecode_of(&object) else {
2615            return Err(self.type_error("not a function"));
2616        };
2617        self.new_coroutine_from(code, env, this, args)
2618    }
2619
2620    /// Build a coroutine over an already-resolved body.
2621    fn new_coroutine_from(
2622        &mut self,
2623        code: Gc<CompiledCode>,
2624        env: Gc<ClosureEnv>,
2625        this: Value,
2626        args: Vec<Value>,
2627    ) -> JsResult<Gc<JsObject>> {
2628        let function = Value::Undefined;
2629        self.push_frame(code, env, this, args, function)?;
2630        let frame = self.frames.pop().expect("push_frame just pushed it");
2631        let state = GeneratorState {
2632            frame: Some(frame),
2633            phase: GeneratorPhase::SuspendedStart,
2634            parked_on_await: false,
2635            parked_on_yield_star: false,
2636            requests: std::collections::VecDeque::new(),
2637            async_busy: false,
2638        };
2639        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2640        coroutine.with_mut(|data| {
2641            data.kind = ObjectKind::Generator(Box::new(state));
2642        });
2643        Ok(coroutine)
2644    }
2645
2646    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2647    /// `await` and `value` is what it awaited.
2648    fn resume_coroutine(
2649        &mut self,
2650        coroutine: &Gc<JsObject>,
2651        kind: ResumeKind,
2652        value: Value,
2653    ) -> JsResult<(Value, bool)> {
2654        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2655            ObjectKind::Generator(state) => Some(std::mem::replace(
2656                state.as_mut(),
2657                GeneratorState {
2658                    frame: None,
2659                    phase: GeneratorPhase::Executing,
2660                    parked_on_await: false,
2661                    parked_on_yield_star: false,
2662                    requests: std::collections::VecDeque::new(),
2663                    async_busy: false,
2664                },
2665            )),
2666            _ => None,
2667        }) else {
2668            return Err(self.type_error("not a coroutine"));
2669        };
2670        let result = self.step_generator(&mut state, kind, value);
2671        coroutine.with_mut(|data| {
2672            data.kind = ObjectKind::Generator(Box::new(state));
2673        });
2674        let (value, done, _ready, _reason) = result?;
2675        Ok((value, done))
2676    }
2677
2678    /// Advance an async body and settle its promise with the outcome.
2679    fn drive_async(
2680        &mut self,
2681        coroutine: &Gc<JsObject>,
2682        promise: &Gc<JsObject>,
2683        kind: ResumeKind,
2684        value: Value,
2685    ) -> JsResult<()> {
2686        match self.resume_coroutine(coroutine, kind, value) {
2687            Ok((value, true)) => {
2688                // `Ok` with `done` means the body finished *normally*, even when it was
2689                // resumed by a `throw` — `try { await p } catch {}` completes by
2690                // returning. Only the `Err` arm below is a rejection.
2691                //
2692                // Resolving rather than fulfilling matters: `return promise` in an async
2693                // body adopts the inner promise, so `async function f(){ return
2694                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2695                // promise.
2696                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2697                    self.reject_promise(promise, reason);
2698                }
2699                Ok(())
2700            }
2701            Ok((value, false)) => {
2702                // Parked on `await`: follow what it awaited and resume with the outcome.
2703                let awaited = match self.promise_resolve_value(value) {
2704                    Ok(awaited) => awaited,
2705                    Err(Signal::Throw(error)) => {
2706                        self.reject_promise(promise, error);
2707                        return Ok(());
2708                    }
2709                    Err(other) => return Err(other),
2710                };
2711                self.hook_await(awaited, coroutine, promise)
2712            }
2713            Err(Signal::Throw(reason)) => {
2714                self.reject_promise(promise, reason);
2715                Ok(())
2716            }
2717            Err(other) => Err(other),
2718        }
2719    }
2720
2721    /// Arrange for `coroutine` to resume when `awaited` settles.
2722    fn hook_await(
2723        &mut self,
2724        awaited: Value,
2725        coroutine: &Gc<JsObject>,
2726        promise: &Gc<JsObject>,
2727    ) -> JsResult<()> {
2728        let resumed = JsObject::function(
2729            self.heap,
2730            Some(self.realm.function_proto.clone()),
2731            Callable::AwaitResume {
2732                coroutine: coroutine.clone(),
2733                promise: promise.clone(),
2734                kind: ResumeKind::Next,
2735            },
2736        );
2737        let raised = JsObject::function(
2738            self.heap,
2739            Some(self.realm.function_proto.clone()),
2740            Callable::AwaitResume {
2741                coroutine: coroutine.clone(),
2742                promise: promise.clone(),
2743                kind: ResumeKind::Throw,
2744            },
2745        );
2746        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2747        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2748        let Value::Object(awaited) = &awaited else {
2749            self.jobs.push_back(Job::Resume {
2750                coroutine: coroutine.clone(),
2751                promise: promise.clone(),
2752                kind: ResumeKind::Next,
2753                value: awaited,
2754            });
2755            return Ok(());
2756        };
2757        self.perform_then(
2758            awaited,
2759            Some(Value::Object(resumed)),
2760            Some(Value::Object(raised)),
2761        )?;
2762        Ok(())
2763    }
2764
2765    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2766    /// things an engine keeps outside it — array elements and an array's `length`.
2767    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2768        if let Some(property) = object.own_property_key(key) {
2769            return Some(property);
2770        }
2771        // An array's elements live in their own vector rather than the property table, so
2772        // a descriptor for one has to be synthesized — with the attributes an element has.
2773        if let Some(index) = key.as_str().and_then(array_index)
2774            && let Some(value) = object.array_get(index as usize)
2775            && !matches!(value, Value::Hole)
2776        {
2777            return Some(Property::data(value));
2778        }
2779        // `length` is an own property of an array that is not in its property table
2780        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2781        // and non-enumerable.
2782        if key.as_str() == Some("length")
2783            && let Some(length) = object.array_length()
2784        {
2785            return Some(Property {
2786                value: Some(crate::object::length_value(length)),
2787                writable: object.length_writable(),
2788                enumerable: false,
2789                configurable: false,
2790                getter: None,
2791                setter: None,
2792            });
2793        }
2794        None
2795    }
2796
2797    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2798    pub fn object_get_own_property(
2799        &mut self,
2800        object: &Gc<JsObject>,
2801        key: &PropertyKey,
2802    ) -> JsResult<Option<Property>> {
2803        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2804            return Ok(answer);
2805        }
2806        if let Some(exotic) = object.exotic()
2807            && let Some(answer) = exotic.get_own_property(self, object, key)?
2808        {
2809            return Ok(answer);
2810        }
2811        Ok(Self::ordinary_own_property(object, key))
2812    }
2813
2814    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2815    pub fn object_define_own_property(
2816        &mut self,
2817        object: &Gc<JsObject>,
2818        key: &PropertyKey,
2819        property: Property,
2820    ) -> JsResult<bool> {
2821        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2822            return Ok(accepted);
2823        }
2824        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
2825        // non-extensible object. The check lives here rather than in the callers because
2826        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
2827        // `Array.prototype.filter` uses to store its result, and a species object made
2828        // non-extensible by its own constructor must make that a `TypeError`
2829        // (`target-array-non-extensible`).
2830        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
2831            return Ok(false);
2832        }
2833        // A host class that intercepts definitions owns the attributes of the properties it
2834        // defines: `_class`-style storage on the native side is the usual reason.
2835        if let Some(exotic) = object.exotic()
2836            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
2837        {
2838            return Ok(accepted);
2839        }
2840        // An array index is stored in the element vector, which can hold a plain value and
2841        // nothing else. An accessor — or a data property with non-default attributes —
2842        // therefore has to live in the property table, and the element slot is blanked so
2843        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2844        // {get})` stored the accessor where no read ever looked, and the array kept
2845        // answering its old value.
2846        // An array's `length` is not stored in the property table, so defining it has to
2847        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2848        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2849        // {value: 1})` reported success and changed nothing.
2850        if key.as_str() == Some("length") && object.is_array() {
2851            // `{writable: false}` on `length` does not change the length, but it does make
2852            // it read-only — after which neither a later `{writable: true}` nor a store
2853            // past the end may succeed.
2854            if property.value.is_none() {
2855                if !object.length_writable() && property.writable {
2856                    return Ok(false);
2857                }
2858                object.set_length_writable(property.writable);
2859                return Ok(true);
2860            }
2861            if !object.length_writable() {
2862                return Ok(false);
2863            }
2864        }
2865        if key.as_str() == Some("length")
2866            && object.is_array()
2867            && let Some(value) = property.value.clone()
2868        {
2869            let requested = value.to_number();
2870            let valid = requested.is_finite()
2871                && requested >= 0.0
2872                && requested.fract() == 0.0
2873                && requested <= u32::MAX as f64;
2874            if !valid {
2875                return Err(self.range_error("invalid array length"));
2876            }
2877            // Truncating deletes the elements above the new length, and a non-configurable
2878            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2879            // makes `a.length = 2` fail rather than quietly drop it.
2880            let current = object.array_length().unwrap_or(0);
2881            let requested = requested as usize;
2882            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2883                return Ok(false);
2884            }
2885            object.array_set_length(self.heap, requested);
2886            return Ok(true);
2887        }
2888        let plain = property.writable
2889            && property.enumerable
2890            && property.configurable
2891            && !property.is_accessor();
2892        if let Some(index) = key.as_str().and_then(array_index)
2893            && object.is_array()
2894        {
2895            // Growing the array needs a writable `length`: after
2896            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2897            // be added.
2898            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2899                return Ok(false);
2900            }
2901            if plain && property.value.is_some() {
2902                // An ordinary element: the vector is where a read looks first, so it has
2903                // to be the vector that changes — unless the index is too far out to be
2904                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2905                // one property, because past its own limit it stores the index as an
2906                // ordinary key. Falling through to `define_key` below is the same choice,
2907                // and the alternative was worse: the store used to be *dropped* and the
2908                // length left at 0, which is a silent wrong answer.
2909                let value = property.value.clone().unwrap_or(Value::Undefined);
2910                object.delete_key(key);
2911                if object.array_set(self.heap, index as usize, value) {
2912                    return Ok(true);
2913                }
2914                // Past the dense limit the element lives in the table like any property.
2915                object.note_element_descriptor();
2916                object.define_key(key, property);
2917                // A sparse store past the dense limit still extends `length`, which is what
2918                // `a[a.length] = v` relies on — but only extends: shortening would delete
2919                // the sparse properties above the index, including this one.
2920                if index as usize + 1 > object.array_length().unwrap_or(0) {
2921                    object.array_set_length(self.heap, index as usize + 1);
2922                }
2923                return Ok(true);
2924            }
2925            // A non-plain element — an accessor, or an attribute that is not the default —
2926            // lives in the table while the slot becomes a hole. Recording it keeps every
2927            // later `a[i] = v` off the dense path, where the write would have shadowed the
2928            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
2929            // replace the accessor with a plain data property.
2930            object.note_element_descriptor();
2931            object.define_key(key, property);
2932            // The slot stays, so `length` does not shrink; a hole is not an element, so
2933            // the table entry is now what a read finds.
2934            object.array_set(self.heap, index as usize, Value::Hole);
2935            return Ok(true);
2936        }
2937        object.define_key(key, property);
2938        Ok(true)
2939    }
2940
2941    /// Build a proxy object over `target`, with its traps read from `handler`.
2942    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2943        JsObject::proxy(self.heap, target, handler)
2944    }
2945
2946    /// The `revoke` function for a proxy's slots.
2947    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2948        JsObject::function(
2949            self.heap,
2950            Some(self.realm.function_proto.clone()),
2951            Callable::Revoker(slots),
2952        )
2953    }
2954
2955    /// A new array.
2956    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2957        let array = JsObject::array(
2958            self.heap,
2959            Some(self.realm.array_proto.clone()),
2960            elements.len(),
2961        );
2962        for (index, element) in elements.into_iter().enumerate() {
2963            array.array_set(self.heap, index, element);
2964        }
2965        array
2966    }
2967
2968    /// A new native function object.
2969    ///
2970    /// The observable `name` and `length` are installed as properties here, which is
2971    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2972    /// so `f.name = "x"` behaves like the writable property it is.
2973    /// A native constructor that builds its own instance after validating its arguments.
2974    ///
2975    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2976    /// check runs before `new.target.prototype` is read.
2977    pub fn new_native_ctor(
2978        &self,
2979        name: impl Into<String>,
2980        length: u32,
2981        func: NativeFn,
2982    ) -> Gc<JsObject> {
2983        let function = JsObject::function(
2984            self.heap,
2985            Some(self.realm.function_proto.clone()),
2986            Callable::Native {
2987                func,
2988                own_instance: true,
2989            },
2990        );
2991        function.set_constructible(true);
2992        function.define(
2993            "length",
2994            Property::name_or_length(Value::Int(length as i32)),
2995        );
2996        function.define("name", Property::name_or_length(self.string(name)));
2997        function
2998    }
2999
3000    /// A native constructor that lets `new` build the instance first.
3001    ///
3002    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3003    /// validation that must precede reading `new.target.prototype`, so the object can be
3004    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3005    /// which makes a *method* and therefore not a constructor at all.
3006    pub fn new_native_constructor(
3007        &self,
3008        name: impl Into<String>,
3009        length: u32,
3010        func: NativeFn,
3011    ) -> Gc<JsObject> {
3012        let function = self.new_native(name, length, func);
3013        function.set_constructible(true);
3014        function
3015    }
3016
3017    /// A new host function object: a native closure that carries its own state.
3018    ///
3019    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3020    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3021    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3022    /// this safe: the closure must not capture a `Gc`.
3023    pub fn new_host_function(
3024        &self,
3025        name: impl Into<String>,
3026        length: u32,
3027        func: crate::object::HostFn,
3028    ) -> Gc<JsObject> {
3029        self.new_host_inner(name.into(), length, func, false)
3030    }
3031
3032    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3033    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3034    pub fn new_host_ctor(
3035        &self,
3036        name: impl Into<String>,
3037        length: u32,
3038        func: crate::object::HostFn,
3039    ) -> Gc<JsObject> {
3040        let function = self.new_host_inner(name.into(), length, func, true);
3041        function.set_constructible(true);
3042        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3043        // installs its own methods on it, so it starts as a plain object.
3044        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3045        function.define(
3046            "prototype",
3047            Property {
3048                value: Some(Value::Object(proto)),
3049                writable: true,
3050                enumerable: false,
3051                configurable: false,
3052                ..Property::default()
3053            },
3054        );
3055        function
3056    }
3057
3058    fn new_host_inner(
3059        &self,
3060        name: String,
3061        length: u32,
3062        func: crate::object::HostFn,
3063        own_instance: bool,
3064    ) -> Gc<JsObject> {
3065        let function = JsObject::function(
3066            self.heap,
3067            Some(self.realm.function_proto.clone()),
3068            Callable::Host {
3069                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3070                own_instance,
3071            },
3072        );
3073        function.define(
3074            "length",
3075            Property::name_or_length(Value::Int(length as i32)),
3076        );
3077        function.define("name", Property::name_or_length(self.string(name)));
3078        function
3079    }
3080
3081    /// A callable object with the `length`/`name` a built-in function has, in that order.
3082    ///
3083    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3084    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3085    /// [`JsObject::function`] defines neither, which is why every capability helper built
3086    /// with it reported no own `length` and no own `name` at all.
3087    ///
3088    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3089    /// configurable.
3090    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3091        let function =
3092            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3093        function.define(
3094            "length",
3095            Property::name_or_length(Value::Int(length as i32)),
3096        );
3097        function.define("name", Property::name_or_length(self.string(name)));
3098        function
3099    }
3100
3101    /// A new native function object.
3102    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3103        let function = JsObject::function(
3104            self.heap,
3105            Some(self.realm.function_proto.clone()),
3106            Callable::Native {
3107                func,
3108                own_instance: false,
3109            },
3110        );
3111        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3112        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3113        // `length,name` and this listed `name,length`. A bytecode function already gets it
3114        // the right way round; only native ones were built backwards.
3115        function.define(
3116            "length",
3117            Property::name_or_length(Value::Int(length as i32)),
3118        );
3119        function.define("name", Property::name_or_length(self.string(name)));
3120        function
3121    }
3122
3123    /// A new bound function.
3124    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3125        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3126        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3127        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3128        let constructible = target
3129            .as_object()
3130            .is_some_and(|target| target.is_constructor());
3131        let bound = JsObject::function(
3132            self.heap,
3133            Some(self.realm.function_proto.clone()),
3134            Callable::Bound { target, this, args },
3135        );
3136        bound.set_constructible(constructible);
3137        bound
3138    }
3139
3140    /// A new reference cell.
3141    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3142        Gc::new(self.heap, Cell::new(value))
3143    }
3144
3145    // -- running ------------------------------------------------------------
3146
3147    /// Evaluate `code` as a script body and return its completion value.
3148    /// Compile and run `source` for the engine's own use, returning its completion value.
3149    ///
3150    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3151    /// needs to be a real async function, and the engine already runs those as coroutines,
3152    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3153    ///
3154    /// Differences from [`Self::eval_in_global`], both deliberate:
3155    ///
3156    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3157    ///   being built, and the source is an IIFE that only constructs a closure, so there
3158    ///   is nothing to drain — and draining here would run script-queued jobs in the
3159    ///   middle of `install`.
3160    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3161    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3162    ///   and it should not look like the user wrote something wrong.
3163    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3164        let program = match js_parse::parse_script(source) {
3165            Ok(program) => program,
3166            Err(error) => {
3167                let message = format!("builtin source does not parse: {error}");
3168                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3169            }
3170        };
3171        let mut code = match js_compile::compile_script(&program) {
3172            Ok(code) => code,
3173            Err(error) => {
3174                let message = format!("builtin source does not compile: {}", error.message);
3175                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3176            }
3177        };
3178        // The frame has to name something, and `<builtin>` is what a stack trace through
3179        // this code should say.
3180        code.set_filename("<builtin>");
3181        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3182        let closure_vars = compiled.code.closure_vars.clone();
3183        let env = self.global_env(&closure_vars);
3184        let this = Value::Object(self.realm.global.clone());
3185        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3186    }
3187
3188    /// Run an already-parsed script and drain the microtasks it queued.
3189    ///
3190    /// The drain is what lets an `async` function's body advance past its first `await`
3191    /// before the host sees the result: nothing else pumps the job queue.
3192    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3193        let this = Value::Object(self.realm.global.clone());
3194        self.run_script_with_this(code, this)
3195    }
3196
3197    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3198    ///
3199    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3200    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3201    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3202    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3203    /// state the next script evaluation tripped over.
3204    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3205        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3206        let closure_vars = compiled.code.closure_vars.clone();
3207        let env = self.global_env(&closure_vars);
3208        let callee = Value::Undefined;
3209        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3210        // The script is done, so the microtasks it queued run before the host sees the
3211        // result. Without this an `async` function's body would never advance past its
3212        // first `await`, because nothing else drains the queue.
3213        self.drain_jobs()?;
3214        Ok(result)
3215    }
3216
3217    /// Compile and run `source` in global scope, returning its completion value.
3218    ///
3219    /// This is what `eval` and `new Function` use. Running it as a script means it
3220    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3221    /// for a `Function` body; a *direct* eval that reads a local variable would need
3222    /// the compiler to hand its variable environment over, which is not implemented.
3223    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3224        self.eval_in_global_named(source, EVAL_FILE, false)
3225    }
3226
3227    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3228    ///
3229    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3230    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3231    /// through the code, so they cannot share one constant.
3232    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3233        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3234    }
3235
3236    /// Evaluate `source` as a global script, reported under `file`.
3237    ///
3238    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3239    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3240    /// from inside a C callback, where the interpreter is the running one rather than a
3241    /// context's own.
3242    pub fn eval_in_global_named(
3243        &mut self,
3244        source: &str,
3245        file: &str,
3246        barrier: bool,
3247    ) -> JsResult<Value> {
3248        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3249        // eval-created global binding — configurable, unlike a script's own `var`.
3250        self.eval_depth += 1;
3251        if barrier {
3252            let depth = self.frames.len();
3253            self.trace_barriers.push(depth);
3254        }
3255        let result = self.eval_in_global_inner(source, file);
3256        if barrier {
3257            self.trace_barriers.pop();
3258        }
3259        self.eval_depth -= 1;
3260        result
3261    }
3262
3263    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3264        let compiled = self.compile_global_script(source, file, false)?;
3265        let strict = compiled.strict;
3266        self.run_eval_script(compiled, strict)
3267    }
3268
3269    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3270    ///
3271    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3272    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3273    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3274    /// direct eval's is.
3275    pub fn eval_script_with_this(
3276        &mut self,
3277        source: &str,
3278        file: &str,
3279        this: Value,
3280    ) -> JsResult<Value> {
3281        let program = match js_parse::parse_script(source) {
3282            Ok(program) => program,
3283            Err(error) => {
3284                return Err(Signal::Throw(self.syntax_error_at(
3285                    file,
3286                    error.span.start.line,
3287                    error.span.start.column,
3288                    &error.message,
3289                )));
3290            }
3291        };
3292        let mut compiled = match js_compile::compile_script(&program) {
3293            Ok(compiled) => compiled,
3294            Err(error) => {
3295                return Err(Signal::Throw(self.syntax_error_at(
3296                    file,
3297                    error.span.start.line,
3298                    error.span.start.column,
3299                    &error.message,
3300                )));
3301            }
3302        };
3303        compiled.set_filename(file);
3304        self.run_script_with_this(compiled, this)
3305    }
3306
3307    /// Parse and compile `source` as a global script, without running it.
3308    ///
3309    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3310    /// before a promise exists to reject — while still evaluating in the same eval context
3311    /// (direct-eval strictness, `new.target`, `super`).
3312    fn compile_global_script(
3313        &mut self,
3314        source: &str,
3315        file: &str,
3316        async_body: bool,
3317    ) -> JsResult<CompiledFunction> {
3318        // A *direct* eval inherits the strictness of the code that called it, which is
3319        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3320        // implicit global. The caller's frame is the innermost one here, because a
3321        // native function does not push a frame of its own.
3322        let strict = self.current_strict();
3323        // `eval` runs in the caller's function context, so `new.target` is legal here
3324        // even though the source is a bare script — and so is `super.x` when the caller
3325        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3326        // caller's, which is what `special_object 4` already does.
3327        let context = js_parse::EvalContext {
3328            in_method: self.enclosing_home_object().is_some(),
3329            // `super()` belongs to a derived constructor, and an eval'd body is not a
3330            // constructor at all: the caller frame's `this` is already built.
3331            in_derived_constructor: false,
3332        };
3333        // A *global* eval is not a function body: `new.target` and `super` are out of
3334        // reach there. Its `{async: true}` form differs in the other direction — the body
3335        // may `await` — so the two flags are independent and the reference sets both from
3336        // the eval type rather than from the caller.
3337        let parsed = if async_body {
3338            js_parse::parse_suspensible_global_eval(source, strict)
3339        } else {
3340            js_parse::parse_eval_script_in(source, strict, context)
3341        };
3342        let program = match parsed {
3343            Ok(program) => program,
3344            Err(error) => {
3345                // The message is bare: the position lives in `fileName`,
3346                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3347                // the reference puts it. An `invalid source: L:C: ` prefix made
3348                // `e.message` differ from the reference while the stack already agreed.
3349                return Err(Signal::Throw(self.syntax_error_at(
3350                    file,
3351                    error.span.start.line,
3352                    error.span.start.column,
3353                    &error.message,
3354                )));
3355            }
3356        };
3357        let mut compiled = match if async_body {
3358            js_compile::compile_script_suspensible(&program)
3359        } else {
3360            js_compile::compile_script(&program)
3361        } {
3362            Ok(compiled) => compiled,
3363            // A construct the compiler does not handle yet is reported the same way a
3364            // parse error is: it happens before anything runs, so the trace is the
3365            // position in the source followed by the caller.
3366            Err(error) => {
3367                return Err(Signal::Throw(self.syntax_error_at(
3368                    file,
3369                    error.span.start.line,
3370                    error.span.start.column,
3371                    &error.message,
3372                )));
3373            }
3374        };
3375        compiled.set_filename(file);
3376        Ok(compiled)
3377    }
3378
3379    /// Run an `eval`'d script in the caller's scope.
3380    ///
3381    /// Three things have to come from the calling frame, because the eval'd code is a
3382    /// script and would otherwise see only the global object:
3383    ///
3384    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3385    /// * `arguments`, exposed as a binding of the eval's own scope, so
3386    ///   `f("arguments.length", 1)` sees the caller's arguments;
3387    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3388    ///   `eval("var v = 1")` into the global object.
3389    ///
3390    /// Locals of the calling function are *not* reachable: that needs the compiler to
3391    /// hand its variable environment over, which this milestone does not do.
3392    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3393        // `this` and `arguments` come from the innermost frame only — those are not
3394        // lexical — while the name bindings come from the whole chain of frames, part
3395        // of it being ordinary scope resolution.
3396        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3397        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3398        // read from its closure.
3399        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3400        // variable environment is the innermost frame of all: an arrow's own body is where
3401        // `var`s declared by an `eval` inside it belong.
3402        let caller_index = self
3403            .frames
3404            .iter()
3405            .rposition(|frame| !frame.code.code.is_arrow)
3406            .or_else(|| self.frames.len().checked_sub(1));
3407        let env_index = self.frames.len().checked_sub(1);
3408        let caller = caller_index.and_then(|index| self.frames.get(index));
3409        let (this, passed) = match caller {
3410            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3411            // No frame at all: the eval is running at the top level, so there is
3412            // nothing to inherit and the global receiver is right.
3413            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3414        };
3415        // Innermost frame first, so the first binding found for a name is the one that
3416        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3417        let mut bindings: Vec<EvalBinding> = Vec::new();
3418        // The calling function's own bindings, resolved by the compiler at the call
3419        // site. That table is the only reliable answer when a name is declared twice in
3420        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3421        // body means, and guessing by declaration order picks the wrong one as soon as
3422        // two loops in a row use the same name.
3423        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3424        // every direct call — a bare `eval(...)` callee — so finding one at the current
3425        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3426        // callee to a value first and leave no site behind.
3427        let mut direct = false;
3428        let mut resolved_here = false;
3429        if let Some(frame) = self.frames.last() {
3430            let (line, column) = frame
3431                .code
3432                .code
3433                .position_at(frame.at as u32)
3434                .unwrap_or_default();
3435            // The nearest site at or before the current position, not an exact match:
3436            // the recorded position of the `call` instruction is the callee's, which
3437            // sits a few columns inside the call expression the compiler recorded. A
3438            // site is unique per call, so "the closest one behind us" identifies it.
3439            if let Some(site) = frame
3440                .code
3441                .code
3442                .eval_sites
3443                .iter()
3444                .filter(|site| (site.line, site.column) <= (line, column))
3445                .max_by_key(|site| (site.line, site.column))
3446            {
3447                direct = true;
3448                resolved_here = true;
3449                for binding in &site.bindings {
3450                    // An enclosing function's frame sits `owner` levels below the one
3451                    // running the call.
3452                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3453                    else {
3454                        continue;
3455                    };
3456                    bindings.push(EvalBinding {
3457                        name: binding.name.clone(),
3458                        frame,
3459                        slot: if binding.is_arg {
3460                            EvalSlot::Arg
3461                        } else {
3462                            EvalSlot::Local
3463                        },
3464                        index: binding.index as usize,
3465                    });
3466                }
3467            }
3468        }
3469        for frame_index in (0..self.frames.len()).rev() {
3470            // Skip the innermost frame's flat scan when the compiler already answered
3471            // for it; an enclosing frame still needs one, because the eval resolves
3472            // those names dynamically.
3473            if resolved_here && frame_index == self.frames.len() - 1 {
3474                continue;
3475            }
3476            let frame = &self.frames[frame_index];
3477            for (index, arg) in frame.code.code.args.iter().enumerate() {
3478                bindings.push(EvalBinding {
3479                    name: arg.name.clone(),
3480                    frame: frame_index,
3481                    slot: EvalSlot::Arg,
3482                    index,
3483                });
3484            }
3485            for (index, local) in frame.code.code.vars.iter().enumerate() {
3486                bindings.push(EvalBinding {
3487                    name: local.name.clone(),
3488                    frame: frame_index,
3489                    slot: EvalSlot::Local,
3490                    index,
3491                });
3492            }
3493        }
3494        let mut seen = BTreeSet::new();
3495        bindings.retain(|binding| seen.insert(binding.name.clone()));
3496
3497        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3498        // elements is all the spec's ordinary uses need.
3499        //
3500        // Known divergence: this is bound for a *global* eval too, where there is no
3501        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3502        // needs "does the calling frame have an `arguments` of its own", which is not
3503        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3504        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3505        // the call-site detection does not answer it. Modelled as a binding in the caller's
3506        // variable environment, this would fall out; that is a larger change than the one
3507        // this comment is attached to.
3508        let arguments = Value::Object(self.new_array(passed));
3509
3510        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3511        // declares its `var`s in the caller's — which for a top-level eval is the global
3512        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3513        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3514        // vanish into a scope nobody reads back from.
3515        let previous_scope = if code_strict {
3516            self.eval_scope.replace(BTreeMap::new())
3517        } else {
3518            None
3519        };
3520        let previous_arguments = self.eval_arguments.replace(arguments);
3521        let previous_with = self.eval_with.replace(self.with_objects());
3522        let inherited_new_target = self
3523            .frames
3524            .iter()
3525            .rev()
3526            .find(|frame| !frame.code.code.is_arrow)
3527            .map(|frame| frame.new_target.clone());
3528        let previous_new_target = self
3529            .eval_new_target
3530            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3531        let eval_cells = self.eval_cells_for(&bindings);
3532        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3533        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3534        // `declare_eval_local` needs to know which frame that is.
3535        // An indirect eval gets the global environment, so nothing of the caller's is
3536        // recorded as the place its `var`s belong.
3537        let previous_caller = self
3538            .eval_caller
3539            .replace(if direct { env_index } else { None });
3540        // The cell-based view of the same bindings, which is what a closure created
3541        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3542        // whose compiler did not put a binding in a cell simply does not appear here —
3543        // reads and writes still work through `eval_bindings`, they just cannot outlive
3544        // the eval.
3545        let previous_eval_scope = self
3546            .active_eval_scope
3547            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3548        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3549        let closure_vars = compiled.code.closure_vars.clone();
3550        let env = self.global_env(&closure_vars);
3551        let callee = Value::Undefined;
3552        // An async body does not run here: it becomes a coroutine and answers a promise,
3553        // which is what makes `await` legal in it. `this` still has to be the caller's
3554        // (for a global eval, the global object), because `this` is not part of `await`.
3555        let result = if compiled.code.kind.is_async() {
3556            self.run_async_body(compiled, env, this)
3557        } else {
3558            self.execute(compiled, env, this, Vec::new(), callee)
3559        };
3560        self.eval_scope = previous_scope;
3561        self.eval_arguments = previous_arguments;
3562        self.eval_with = previous_with;
3563        self.eval_new_target = previous_new_target;
3564        self.eval_bindings = previous_bindings;
3565        self.eval_caller = previous_caller;
3566        self.active_eval_scope = previous_eval_scope;
3567        result
3568    }
3569
3570    /// The cell-backed subset of `bindings`, in the same priority order.
3571    ///
3572    /// Both lookup routes have to agree — the eval's own reads go through
3573    /// [`Interp::eval_binding_value`] and the closures it builds go through
3574    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3575    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3576    /// is not in a cell simply does not appear: reads and writes still work, they just
3577    /// cannot be handed to a closure that outlives the eval.
3578    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3579        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3580        for binding in bindings {
3581            let Some(frame) = self.frames.get(binding.frame) else {
3582                continue;
3583            };
3584            let cell = match binding.slot {
3585                EvalSlot::Arg => frame
3586                    .code
3587                    .arg_cell
3588                    .get(binding.index)
3589                    .copied()
3590                    .unwrap_or(-1),
3591                EvalSlot::Local => frame
3592                    .code
3593                    .loc_cell
3594                    .get(binding.index)
3595                    .copied()
3596                    .unwrap_or(-1),
3597            };
3598            if cell < 0 {
3599                continue;
3600            }
3601            if let Some(cell) = frame.cells.get(cell as usize) {
3602                names.push((binding.name.clone(), cell.clone()));
3603            }
3604        }
3605        names
3606    }
3607
3608    /// A `SyntaxError` that reports where in the source it happened.
3609    ///
3610    /// Compile-time failures never run, so they have no frame of their own; the
3611    /// reference still puts the position first in the trace, with no function name and
3612    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3613    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3614    /// reference borrows), which is how a script reads the position without parsing
3615    /// the trace.
3616    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3617    ///
3618    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3619    /// `columnNumber`, which is how the reference prints one. A positionless error
3620    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3621    /// the reference raises it from `js_resolve_module`, where there is no position.
3622    pub(crate) fn syntax_error_plain(
3623        &mut self,
3624        error: &js_parse::SyntaxError,
3625        file: &str,
3626    ) -> Value {
3627        if error.positionless {
3628            return self.make_error("SyntaxError", &error.message);
3629        }
3630        self.syntax_error_at(
3631            file,
3632            error.span.start.line,
3633            error.span.start.column,
3634            &error.message,
3635        )
3636    }
3637
3638    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3639        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
3640        let value = self.make_error("SyntaxError", message);
3641        if let Value::Object(object) = &value {
3642            let text = self.string(blamed);
3643            object.define("stack", Property::with_attributes(text, true, true));
3644            let name = self.string(file);
3645            object.define("fileName", Property::with_attributes(name, true, true));
3646            object.define(
3647                "lineNumber",
3648                Property::with_attributes(Value::Int(line as i32), true, true),
3649            );
3650            object.define(
3651                "columnNumber",
3652                Property::with_attributes(Value::Int(column as i32), true, true),
3653            );
3654        }
3655        value
3656    }
3657
3658    /// Run a compiled script whose completion value is a function, returning it.
3659    ///
3660    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3661    /// get the closure out, which keeps the constant-pool plumbing in one place.
3662    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3663        self.run_script(code)
3664    }
3665
3666    /// The environment of a script or of any function compiled at global scope:
3667    /// every entry is a global binding, so each one resolves to the realm's cell.
3668    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3669        let mut cells = Vec::with_capacity(closure_vars.len());
3670        for closure_var in closure_vars {
3671            let cell = match closure_var.closure_type {
3672                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3673                    if closure_var.is_lexical =>
3674                {
3675                    // A lexical declaration: the cell is created here holding the
3676                    // dead-zone marker, which is what makes the binding exist and
3677                    // unreadable before its initialiser runs.
3678                    self.declare_global(&closure_var.name, closure_var.is_const);
3679                    self.realm.globals[&closure_var.name].clone()
3680                }
3681                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3682                    // A `var` or function declaration becomes a property of the global
3683                    // object, and it exists from here on — which is why
3684                    // `print(v); var v = 1` prints `undefined` instead of raising.
3685                    // Declaring it at instantiation time (rather than at the
3686                    // initialiser) is also what makes it non-configurable: the store
3687                    // then lands on an existing property instead of creating one.
3688                    self.declare_var_global(&closure_var.name);
3689                    // The cell is a placeholder that nothing indexes; it cannot be
3690                    // omitted because the slot has to hold something.
3691                    self.new_cell(Value::Undefined)
3692                }
3693                _ => {
3694                    // An undeclared global is read by name; the cell is a
3695                    // placeholder that nothing indexes.
3696                    self.new_cell(Value::Undefined)
3697                }
3698            };
3699            cells.push(cell);
3700        }
3701        Gc::new(
3702            self.heap,
3703            ClosureEnv {
3704                cells,
3705                eval_scope: None,
3706                local_vars: None,
3707                local_phase: 1,
3708            },
3709        )
3710    }
3711
3712    /// Push a frame and run until it returns.
3713    pub(crate) fn execute(
3714        &mut self,
3715        code: Gc<CompiledCode>,
3716        env: Gc<ClosureEnv>,
3717        this: Value,
3718        args: Vec<Value>,
3719        callee: Value,
3720    ) -> JsResult<Value> {
3721        let depth = self.frames.len();
3722        if depth == 0 {
3723            // A throw that reached the host ends the *active* mode: the next one is catchable
3724            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3725            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3726            // for the throw that evaluation will raise.
3727            self.uncatchable = false;
3728        }
3729        self.push_frame(code, env, this, args, callee)?;
3730        loop {
3731            // The fast loop first: it runs whole runs of records with `pc` in a register.
3732            //
3733            // `step`'s `pc` lives in the frame, so every instruction writes it back and
3734            // reads it again — a store, a load and two bounds checks that a loop body does
3735            // not need, because nothing outside the loop can run in between. This is the
3736            // classic split: advance a register, and only spill it when leaving.
3737            //
3738            // `Some(value)` means the function ended by running off the end of its
3739            // instruction array, which is a normal return.
3740            let step = match self.run_fast() {
3741                Ok(Some(value)) => Ok(Step::Return(value)),
3742                Ok(None) => self.step(),
3743                Err(signal) => Err(signal),
3744            };
3745            match step {
3746                Ok(Step::Continue) => {}
3747                Ok(Step::Return(value)) => {
3748                    self.pop_frame();
3749                    // A frame that ended in a `tail_call` hands its value straight to
3750                    // its caller: nothing after the call can run, so every frame above
3751                    // the callee unwinds with the same value. See [`Frame::tail`] —
3752                    // the reference does not reuse frames either, so recursion depth
3753                    // and the stack-overflow limit behave the same way.
3754                    while self.frames.len() > depth && self.frame().tail {
3755                        self.pop_frame();
3756                    }
3757                    if self.frames.len() == depth {
3758                        return Ok(value);
3759                    }
3760                    // The caller resumes with the value on its stack.
3761                    self.frames
3762                        .last_mut()
3763                        .expect("a caller is live")
3764                        .stack
3765                        .push(value);
3766                }
3767                Err(Signal::Throw(value)) => {
3768                    // The host's standing request becomes the active mode for this unwind,
3769                    // and is consumed here so it does not leak into the next throw.
3770                    if self.uncatchable_next {
3771                        self.uncatchable_next = false;
3772                        self.uncatchable = true;
3773                    }
3774                    // An uncatchable throw walks past every `catch` on the way out. The
3775                    // frames are still popped, because the values they hold have to be
3776                    // dropped — only the search for a handler is skipped.
3777                    if self.uncatchable {
3778                        while self.frames.len() > depth {
3779                            self.frames.pop();
3780                        }
3781                        return Err(Signal::Throw(value));
3782                    }
3783                    // A handler lives on the stack of the frame that is throwing —
3784                    // `catch` pushed it there — so this frame gets the first chance
3785                    // to catch before it is popped.
3786                    let value = value;
3787                    loop {
3788                        if self.frames.len() <= depth {
3789                            return Err(Signal::Throw(value));
3790                        }
3791                        if self.catch_here(value.clone()).is_some() {
3792                            break;
3793                        }
3794                        self.frames.pop();
3795                    }
3796                }
3797                // A `yield` in a frame that `execute` is running directly means a
3798                // generator body was entered as an ordinary call, which only happens if
3799                // the generator check in `call_or_push` was bypassed.
3800                Ok(Step::Suspend(_)) => {
3801                    return Err(Signal::Throw(self.make_error(
3802                        "InternalError",
3803                        "a generator body ran as an ordinary call",
3804                    )));
3805                }
3806                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3807            }
3808        }
3809    }
3810
3811    /// Install a handler for `value` if this frame has one, resuming at it.
3812    ///
3813    /// The scan is the reference's: walk the frame's stack downwards looking for the
3814    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3815    /// `0` is an enumerator marker rather than a handler — it exists so that a
3816    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3817    /// here and the unwinding continues.
3818    fn catch_here(&mut self, value: Value) -> Option<()> {
3819        let frame = self.frames.last_mut()?;
3820        while let Some(top) = frame.stack.pop() {
3821            if let Value::CatchOffset(offset) = top {
3822                if offset == 0 {
3823                    continue;
3824                }
3825                frame.stack.push(value);
3826                frame.pc = offset as usize;
3827                return Some(());
3828            }
3829        }
3830        None
3831    }
3832
3833    fn push_frame(
3834        &mut self,
3835        code: Gc<CompiledCode>,
3836        env: Gc<ClosureEnv>,
3837        this: Value,
3838        mut args: Vec<Value>,
3839        callee: Value,
3840    ) -> JsResult<()> {
3841        // Two bounds, and the byte budget is the one that decides in practice. The
3842        // reference's message is `stack overflow` on an `InternalError`, not V8's
3843        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3844        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3845        let frame_cost = Self::frame_cost(&code);
3846        let stack_base = self.stack_used();
3847        if self.frames.len() >= self.max_frames
3848            || stack_base.saturating_add(frame_cost) > self.stack_limit
3849        {
3850            return Err(Signal::Throw(
3851                self.make_error("InternalError", "stack overflow"),
3852            ));
3853        }
3854        let arg_count = code.code.args.len();
3855        // How many were actually passed, which `arguments.length` reports and
3856        // `assert(x)` depends on: a call with one argument must not look like a call
3857        // with one argument and an explicit `undefined`.
3858        let passed = args.len();
3859        // Missing arguments are `undefined` in their slots; extra ones are dropped
3860        // from the slots but still reachable through `arguments`.
3861        //
3862        // A call that passes no more than the declared parameters needs **no** copy:
3863        // after the resize below, `args[..passed]` *is* the passed values. Only the
3864        // extra ones — which `truncate` is about to drop — have to be kept, and they are
3865        // the rare case. This used to copy every call: one `Value` clone per argument
3866        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3867        let passed_overflow = (passed > arg_count).then(|| {
3868            let mut values = self.take_values(passed, Value::Undefined);
3869            values[..passed].clone_from_slice(&args[..passed]);
3870            values
3871        });
3872        // Only when the counts differ, which for the overwhelmingly common call — as many
3873        // arguments as parameters — is never. `resize` followed by `truncate` on equal
3874        // lengths is two length compares and nothing else, but this is the hottest few
3875        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3876        if passed != arg_count {
3877            args.resize(arg_count, Value::Undefined);
3878            args.truncate(arg_count);
3879        }
3880        let cell_count = code.code.var_ref_count as usize;
3881        let mut cells = Vec::with_capacity(cell_count);
3882        for _ in 0..cell_count {
3883            cells.push(self.new_cell(Value::Undefined));
3884        }
3885        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3886        // A captured argument lives in its cell, not in the argument slot, so the
3887        // incoming value has to be moved there before the body runs.
3888        for (slot, cell) in code.arg_cell.iter().enumerate() {
3889            if *cell >= 0
3890                && let Some(value) = args.get(slot).cloned()
3891            {
3892                cells[*cell as usize].set(value);
3893            }
3894        }
3895        // Sloppy mode substitutes the global object for a missing receiver and boxes a
3896        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3897        // reports `object`. Strict mode passes the value through untouched.
3898        let this = if code.code.strict {
3899            this
3900        } else if this.is_nullish() {
3901            Value::Object(self.realm.global.clone())
3902        } else if matches!(this, Value::Object(_)) {
3903            this
3904        } else {
3905            match crate::builtins::this_object(self, &this) {
3906                Ok(boxed) => Value::Object(boxed),
3907                Err(_) => this,
3908            }
3909        };
3910        let stack_depth = code.code.stack_size as usize + 1;
3911        // Taken before the `push` borrows `self.frames`, because the operand stack comes
3912        // out of the same recycle pool the locals did.
3913        let stack = self.take_values(stack_depth, Value::Undefined);
3914        self.frames.push(Frame {
3915            code,
3916            env,
3917            this,
3918            args,
3919            passed_count: passed,
3920            passed_overflow: passed_overflow.map(Box::new),
3921            locals,
3922            cells,
3923            local_vars: None,
3924            // Exactly the depth the compiler computed, so the operand stack never
3925            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
3926            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
3927            // the buffer between calls, so "exactly" costs nothing after the first one.
3928            stack,
3929            pc: 0,
3930            at: 0,
3931            callee,
3932            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3933            cost: frame_cost,
3934            stack_base,
3935            tail: false,
3936        });
3937        Ok(())
3938    }
3939
3940    /// A value buffer of `len` slots, from the recycle pool when there is one.
3941    ///
3942    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
3943    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
3944        // A frame with no locals asks for nothing, and that is most frames: taking a
3945        // buffer out of the pool, clearing it and resizing it to zero is four operations
3946        // and a pool pop for an empty `Vec`, which is free to construct.
3947        if len == 0 {
3948            return Vec::new();
3949        }
3950        let mut buffer = self.free_values.pop().unwrap_or_default();
3951        buffer.clear();
3952        buffer.resize(len, fill);
3953        buffer
3954    }
3955
3956    /// Return a finished frame's value buffers for the next call to reuse.
3957    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
3958        for mut buffer in [
3959            std::mem::take(&mut frame.locals),
3960            frame
3961                .passed_overflow
3962                .take()
3963                .map(|buffer| *buffer)
3964                .unwrap_or_default(),
3965            std::mem::take(&mut frame.stack),
3966        ] {
3967            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
3968            // GC root: it kept every value the frame held reachable, which is invisible
3969            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
3970            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
3971            // exactly that within one run — the target `{}` of a finished IIFE was still
3972            // in its operand stack, in the pool.
3973            buffer.clear();
3974            // A buffer with no capacity is what `Vec::new` is; putting it back would just
3975            // fill the pool with nothing to offer.
3976            if free_values.len() < RECYCLE_SLOTS
3977                && buffer.capacity() > 0
3978                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
3979            {
3980                free_values.push(buffer);
3981            }
3982        }
3983    }
3984
3985    /// Pop a finished frame and keep its buffers.
3986    ///
3987    /// Every place that drops a frame goes through here: a recycled buffer is also where
3988    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
3989    /// nothing but the reuse.
3990    fn pop_frame(&mut self) -> Option<()> {
3991        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
3992        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
3993        let last = self.frames.len().checked_sub(1)?;
3994        Self::recycle(&mut self.free_values, &mut self.frames[last]);
3995        self.frames.truncate(last);
3996        Some(())
3997    }
3998
3999    /// Poll the host's interrupt handler, if one is installed.
4000    ///
4001    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4002    /// one `Option` test, and with no handler installed the whole function is that test —
4003    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4004    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4005    #[inline]
4006    fn check_interrupt(&mut self) -> JsResult<()> {
4007        if self.interrupt.is_none() {
4008            return Ok(());
4009        }
4010        if self.interrupt_counter > 0 {
4011            self.interrupt_counter -= 1;
4012            return Ok(());
4013        }
4014        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4015        // The closure is taken out for the duration so that a handler which re-enters the
4016        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4017        let mut handler = self.interrupt.take().expect("checked above");
4018        let abort = handler();
4019        self.interrupt = Some(handler);
4020        if abort {
4021            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4022            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4023            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4024            // documentation says.
4025            self.uncatchable = true;
4026            return Err(Signal::Throw(
4027                self.make_error("InternalError", "interrupted"),
4028            ));
4029        }
4030        Ok(())
4031    }
4032
4033    /// A memory checkpoint: does the heap still fit under its limit?
4034    ///
4035    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4036    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4037    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4038    /// only at calls would let it run until the machine died, which is the exact failure
4039    /// `--memory-limit` exists to prevent.
4040    ///
4041    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4042    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4043    /// script that catches it, drops the reference and carries on is legitimate: measured
4044    /// on `qjs --memory-limit 1M`, the engine recovers.
4045    fn check_memory(&mut self) -> JsResult<()> {
4046        // One `Cell` read and a predictable branch when no limit is set, and an integer
4047        // compare when one is. Containers report their own growth as it happens
4048        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4049        // walking it here was the first version and it was O(live) per 256 instructions,
4050        // which turned a 100k-element push loop into a five-minute one.
4051        let Some(limit) = self.heap.memory_limit() else {
4052            return Ok(());
4053        };
4054        let used = self.heap.used_bytes();
4055        if used <= limit {
4056            // Back under the limit — a collection or a dropped reference did it. The next
4057            // time it goes over is a new failure, not a repeat of this one.
4058            self.oom_reported_at = 0;
4059            return Ok(());
4060        }
4061        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4062        // block runs normally after `out of memory` — it allocates nothing, so nothing
4063        // fails. A check that re-fired on every instruction made the handler itself throw,
4064        // which is a dead end: the error became unobservable from script.
4065        //
4066        // Comparing against the total at the last report gives the same behaviour: the
4067        // handler runs while the total is unchanged, and the very next allocation over the
4068        // limit fails.
4069        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4070        {
4071            return Ok(());
4072        }
4073        self.oom_reported_at = used;
4074        Err(Signal::Throw(
4075            self.make_error("InternalError", "out of memory"),
4076        ))
4077    }
4078
4079    /// Fail before allocating `payload` bytes, if they would not fit.
4080    ///
4081    /// For the allocations whose size comes from script data — `new Array(n)`,
4082    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4083    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4084    /// answering NULL for the one big request.
4085    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4086        if self.heap.fits(payload) {
4087            return Ok(());
4088        }
4089        Err(Signal::Throw(
4090            self.make_error("InternalError", "out of memory"),
4091        ))
4092    }
4093
4094    /// Bytes of frame state the live call chain accounts for.
4095    pub fn stack_used(&self) -> usize {
4096        match self.frames.last() {
4097            Some(frame) => frame.stack_base + frame.cost,
4098            None => 0,
4099        }
4100    }
4101
4102    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4103    ///
4104    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4105    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4106    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4107    /// instead. That is the whole difference between the two models: it rations C stack, we
4108    /// ration frame state, and both quantities are dominated by the value slots — which is
4109    /// why the two depths come out comparable rather than merely proportional.
4110    fn frame_cost(code: &CompiledCode) -> usize {
4111        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4112        std::mem::size_of::<Frame>()
4113            + std::mem::size_of::<Value>() * slots
4114            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4115    }
4116
4117    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4118    ///
4119    /// Only names the eval created are here: a name the frame already declared statically
4120    /// is written through to its own slot instead, so this cannot shadow a real local.
4121    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4122        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4123        let (local_vars, phase) = self.visible_local_vars()?;
4124        if !local_vars.contains(name) {
4125            return None;
4126        }
4127        local_vars.get(name, phase)
4128    }
4129
4130    /// The variables a direct `eval` declared, as the code currently running sees them.
4131    ///
4132    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4133    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4134    /// else it is the current frame's, falling back to the frame the closure was created
4135    /// in.
4136    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4137    ///
4138    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4139    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4140    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4141    /// just to be asked `is_none`.
4142    fn has_visible_local_vars(&self) -> bool {
4143        let index = match self.eval_caller.flatten() {
4144            Some(caller) => caller,
4145            None => match self.frames.len().checked_sub(1) {
4146                Some(top) => top,
4147                None => return false,
4148            },
4149        };
4150        match self.frames.get(index) {
4151            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4152            None => false,
4153        }
4154    }
4155
4156    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4157        // While an `eval` runs, its own frame is on top but its variable environment is
4158        // the *caller's* — so the caller is what the lookup has to start from.
4159        let (index, phase) = match self.eval_caller.flatten() {
4160            Some(caller) => (
4161                caller,
4162                if self.in_parameter_list_at(caller) {
4163                    0
4164                } else {
4165                    1
4166                },
4167            ),
4168            None => (
4169                self.frames.len().checked_sub(1)?,
4170                if self.in_parameter_list() { 0 } else { 1 },
4171            ),
4172        };
4173        let frame = self.frames.get(index)?;
4174        // The frame's own variables, or — for an arrow, which has no variable environment
4175        // of its own — the one it was created in, which `ClosureEnv` carries.
4176        if let Some(local_vars) = frame.local_vars.clone() {
4177            return Some((local_vars, phase));
4178        }
4179        frame
4180            .env
4181            .local_vars
4182            .clone()
4183            .map(|local_vars| (local_vars, frame.env.local_phase))
4184    }
4185
4186    /// Whether the innermost frame is still evaluating its parameter list.
4187    ///
4188    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4189    /// and a closure created there may only see that much of [`LocalVars`].
4190    fn in_parameter_list(&self) -> bool {
4191        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4192    }
4193
4194    /// [`Interp::in_parameter_list`] for a specific frame.
4195    fn in_parameter_list_at(&self, frame: usize) -> bool {
4196        let Some(frame) = self.frames.get(frame) else {
4197            return false;
4198        };
4199        let code = &frame.code.code;
4200        if !code.has_parameter_expressions {
4201            return false;
4202        }
4203        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4204        // function as its body and let a direct `eval` act accordingly.
4205        if code.body_start == (0, 0) {
4206            return false;
4207        }
4208        match code.position_at(frame.at as u32) {
4209            Some(position) => position < code.body_start,
4210            None => false,
4211        }
4212    }
4213
4214    fn frame(&self) -> &Frame {
4215        self.frames.last().expect("a frame is live")
4216    }
4217
4218    fn frame_mut(&mut self) -> &mut Frame {
4219        self.frames.last_mut().expect("a frame is live")
4220    }
4221
4222    // -- slot access --------------------------------------------------------
4223
4224    /// Move a local's value out, leaving `undefined` in the slot.
4225    ///
4226    /// `None` for a captured slot: its value lives in a cell shared with every closure
4227    /// that closed over it, so it can never be exclusively ours and must not be taken.
4228    ///
4229    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4230    /// for every read and fatal for this one — a clone is exactly the second handle that
4231    /// rules out growing the string in place.
4232    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4233        let frame = self.frames.last_mut()?;
4234        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4235            return None;
4236        }
4237        frame
4238            .locals
4239            .get_mut(slot)
4240            .map(|value| std::mem::replace(value, Value::Undefined))
4241    }
4242
4243    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4244    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4245    ///
4246    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4247    /// it** — the value is put back before the general path runs — so a `valueOf` that
4248    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4249    /// error as it would have without the fusion. This is why the in-place attempt is a
4250    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4251    /// a wrong answer with a good excuse.
4252    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4253        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4254        // is put back on every path that does not append. An earlier version wrote the two
4255        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4256        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4257        // through with its value already taken and dropped: the general path below then
4258        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4259        // A wrong answer, from an optimisation, with every test green.
4260        if matches!(right, Value::String(_))
4261            && let Some(taken) = self.take_loc(slot)
4262        {
4263            if let Value::String(mut left) = taken {
4264                let appended = match left.get_mut() {
4265                    Some(string) => string.append_in_place(
4266                        // The pattern is the one `matches!` just checked.
4267                        match &right {
4268                            Value::String(text) => text,
4269                            _ => unreachable!("guarded above"),
4270                        },
4271                    ),
4272                    None => None,
4273                };
4274                self.put_loc(slot, Value::String(left));
4275                if let Some(added) = appended {
4276                    // The buffer grew where it stood, so the heap's running total has to
4277                    // be told: `measure_used` would report the new length, and the two must
4278                    // agree or the subtraction at free time leaves the counter wrong.
4279                    self.heap.adjust_payload(added as isize);
4280                    return Ok(());
4281                }
4282            } else {
4283                self.put_loc(slot, taken);
4284            }
4285        }
4286        // The two-number case, without an operand stack round trip. Everything below
4287        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4288        // store it — five operations and two `Value` clones for what is one integer add.
4289        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4290        // for string append and never got the numeric half, so `t += i` — a counting loop
4291        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4292        let left = self.get_loc(slot);
4293        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4294            self.put_loc(
4295                slot,
4296                match a.checked_add(*b) {
4297                    Some(sum) => Value::Int(sum),
4298                    None => Value::Float(*a as f64 + *b as f64),
4299                },
4300            );
4301            return Ok(());
4302        }
4303        self.push(left);
4304        self.push(right);
4305        self.binary_add()?;
4306        let value = self.pop();
4307        self.put_loc(slot, value);
4308        Ok(())
4309    }
4310
4311    fn get_arg(&self, slot: usize) -> Value {
4312        self.frame().read_arg(slot)
4313    }
4314
4315    fn put_arg(&mut self, slot: usize, value: Value) {
4316        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4317        if cell == -1 {
4318            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4319                *slot = value;
4320            }
4321        } else {
4322            self.frame().cells[cell as usize].set(value);
4323        }
4324    }
4325
4326    fn get_loc(&self, slot: usize) -> Value {
4327        // The cell mapping is `-1` for every slot that was not captured — which is all of
4328        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4329        // so the common case is one array read and a clone: 20% of every loop iteration
4330        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4331        // sample of `dispatch:arith`).
4332        self.frame().read_loc(slot)
4333    }
4334
4335    fn put_loc(&mut self, slot: usize, value: Value) {
4336        // One borrow instead of three, and the cell check on the frame we already hold.
4337        let frame = self.frames.last_mut().expect("a frame is live");
4338        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4339        if cell < 0 {
4340            if let Some(slot) = frame.locals.get_mut(slot) {
4341                *slot = value;
4342            }
4343        } else if let Some(cell) = frame.cells.get(cell as usize) {
4344            cell.set(value);
4345        }
4346    }
4347
4348    // -- globals ------------------------------------------------------------
4349
4350    /// The name a global-slot operand refers to.
4351    fn global_name(&self, slot: usize) -> String {
4352        self.frame()
4353            .code
4354            .code
4355            .closure_vars
4356            .get(slot)
4357            .map(|c| c.name.clone())
4358            .unwrap_or_default()
4359    }
4360
4361    /// The facts about a global binding that decide where it lives.
4362    ///
4363    /// A script's globals split in two, and the split is observable: `var` and
4364    /// function declarations become properties of the global object (`globalThis.v`
4365    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4366    /// declarations live in the global *lexical* environment and are invisible there
4367    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4368    /// `is_lexical` flag means the answer is already in the bytecode.
4369    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4370        let name = self.global_name(slot);
4371        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4372        // while forwarding a reference through a nested function is built with the
4373        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4374        // closure. Presence in the realm's lexical table is the same fact, recorded
4375        // once, and every slot sees it.
4376        let lexical = self.realm.globals.contains_key(&name);
4377        let is_const = self.realm.lexical_consts.contains(&name);
4378        (name, lexical, is_const)
4379    }
4380
4381    /// The value of `name` in the innermost active `with` object, if any.
4382    ///
4383    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4384    /// innermost frame first and innermost block first within one. Walking frames rather
4385    /// than keeping a separate stack is what makes a closure called from inside a `with`
4386    /// see it, and what keeps the object alive only as long as the block is.
4387    /// The innermost active `with` object that has `name`, if any.
4388    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4389        let objects = self.eval_with.clone().unwrap_or_default();
4390        for object in objects {
4391            let key = self.string(name.to_string());
4392            if self
4393                .has_property(&key, &Value::Object(object.clone()))
4394                .ok()?
4395            {
4396                return Some(object);
4397            }
4398        }
4399        None
4400    }
4401
4402    /// Every active `with` object, innermost first.
4403    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4404        let mut objects = Vec::new();
4405        for frame in self.frames.iter().rev() {
4406            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4407                if var.kind != js_compile::VarKind::With {
4408                    continue;
4409                }
4410                // A captured binding lives in its cell and not in the slot list, so the
4411                // cell is consulted first — a closure created inside the block is exactly
4412                // what makes the object captured. Before the store runs the slot still
4413                // holds `undefined`, and a `with` object is always boxed, so a non-object
4414                // entry is simply not in scope yet.
4415                let value = frame
4416                    .code
4417                    .loc_cell
4418                    .get(index)
4419                    .copied()
4420                    .filter(|cell| *cell >= 0)
4421                    .and_then(|cell| frame.cells.get(cell as usize))
4422                    .map(|cell| cell.get())
4423                    .or_else(|| frame.locals.get(index).cloned());
4424                if let Some(Value::Object(object)) = value {
4425                    objects.push(object);
4426                }
4427            }
4428        }
4429        objects
4430    }
4431
4432    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4433        for object in self.eval_with.clone().unwrap_or_default() {
4434            let key = self.string(name.to_string());
4435            if self.has_property(&key, &Value::Object(object.clone()))? {
4436                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4437            }
4438        }
4439        Ok(None)
4440    }
4441
4442    /// Whether every scope between here and the global object is an ordinary one.
4443    ///
4444    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4445    /// bytecode resolved; when any is live the general path has to run in full order. When
4446    /// none is — every ordinary program — a global read is a property read and nothing
4447    /// else, and that is worth caching.
4448    fn scopes_are_plain(&self) -> bool {
4449        self.eval_caller.is_none()
4450            && self.eval_with.is_none()
4451            && self.eval_arguments.is_none()
4452            && self.eval_bindings.is_empty()
4453            && self.eval_scope.is_none()
4454            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4455            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4456            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4457            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4458            // upstream corpus caught and no unit test did.
4459            && !self.has_visible_local_vars()
4460            && self.frame().env.eval_scope.is_none()
4461    }
4462
4463    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4464        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4465        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4466        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4467        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4468        // borrow outlive the `&mut self` the lookup needs.
4469        //
4470        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4471        // forwarded through a nested function has its flags cleared, so the flag cannot
4472        // be believed.
4473        let code = self.frame().code.clone();
4474        let name = code
4475            .code
4476            .closure_vars
4477            .get(slot)
4478            .map(|c| c.name.as_str())
4479            .unwrap_or_default();
4480        let lexical = self.realm.globals.contains_key(name);
4481        // The common case, first: an ordinary global `var`, with a cache in front of the
4482        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4483        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4484        // cache hit and return without touching any of it.
4485        if !lexical && self.scopes_are_plain() {
4486            return self.get_plain_global(name, slot);
4487        }
4488        if name == "arguments"
4489            && let Some(arguments) = &self.eval_arguments
4490        {
4491            return Ok(arguments.clone());
4492        }
4493        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4494        // the objects live when the eval started are consulted before anything else. The
4495        // snapshot is taken at entry rather than scanning the frames on every read: a
4496        // block that has already finished still leaves its object in the slot, and a
4497        // bytecode read outside the block must not see it.
4498        if let Some(value) = self.with_lookup(name)? {
4499            return Ok(value);
4500        }
4501        // A variable a direct `eval` declared shadows everything the compiler resolved,
4502        // including an enclosing function's binding: the eval put it in the caller's own
4503        // variable environment, which is nearer than any captured scope.
4504        if let Some((local_vars, phase)) = self.visible_local_vars()
4505            && let Some(cell) = local_vars.get(name, phase)
4506        {
4507            return Ok(cell.get());
4508        }
4509        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4510        // its local `a` wins over a global `a`.
4511        if let Some(value) = self.eval_binding_value(name) {
4512            return Ok(value);
4513        }
4514        // A closure created by an `eval` resolves its free names against the bindings
4515        // that eval saw, even after the eval (and its frames) are gone.
4516        if let Some(cell) = self
4517            .frame()
4518            .env
4519            .eval_scope
4520            .as_ref()
4521            .and_then(|scope| scope.get(name))
4522        {
4523            let value = cell.get();
4524            if matches!(value, Value::Uninitialized) {
4525                return Err(self.throw_reference(name));
4526            }
4527            return Ok(value);
4528        }
4529        // A binding declared by the strict `eval` currently running shadows anything
4530        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4531        if let Some(scope) = &self.eval_scope
4532            && let Some(value) = scope.get(name)
4533        {
4534            return Ok(value.clone());
4535        }
4536        if lexical {
4537            // A lexical global is a binding in a side table, so the dead zone is
4538            // visible and it is nowhere on the global object.
4539            if let Some(cell) = self.realm.globals.get(name) {
4540                let value = cell.get();
4541                if matches!(value, Value::Uninitialized) {
4542                    return Err(self.throw_reference(name));
4543                }
4544                return Ok(value);
4545            }
4546            return Err(self.throw_reference(name));
4547        }
4548        // A `var` global is an ordinary property, so the prototype chain and the
4549        // global object's own builtins are all reachable through it.
4550        match self.get_property(&self.realm.global.clone(), name)? {
4551            Some(value) => Ok(value),
4552            None => Err(self.throw_reference(name)),
4553        }
4554    }
4555
4556    /// Read a plain global `var`: a cached own data property, or the full lookup.
4557    ///
4558    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4559    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4560    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4561        let object = self.realm.global.clone();
4562        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4563        if let Some(cached) = &self.global_cache[site]
4564            && object.upgrades_to(&cached.object)
4565            && let Some(value) = object.data_property_at(cached.index, name)
4566        {
4567            return Ok(value);
4568        }
4569        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4570        // chain exactly as before, then remember the answer if it is worth remembering.
4571        let Some(value) = self.get_property(&object, name)? else {
4572            return Err(self.throw_reference(name));
4573        };
4574        if let Some(index) = object.own_data_index(name) {
4575            self.global_cache[site] = Some(GlobalCache {
4576                object: object.downgrade(),
4577                index,
4578            });
4579        }
4580        Ok(value)
4581    }
4582
4583    /// Store to a global binding.
4584    ///
4585    /// Returns a signal when the store is refused: a `const` global may only be
4586    /// written by its initialiser, and a non-configurable `var` global may not be
4587    /// deleted but is always writable.
4588    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4589        let (name, lexical, is_const) = self.global_binding(slot);
4590
4591        // An assignment inside a `with` writes through to the object that supplies the
4592        // name, which for an `eval` means consulting the same chain `get_global` does.
4593        if let Some(owner) = self.with_owner(&name) {
4594            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4595            return Ok(());
4596        }
4597        // A variable the running eval *declared* takes the write before any caller
4598        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4599        // environment even when an enclosing function has a `var c` of its own.
4600        if self.eval_caller.flatten().is_some()
4601            && let Some((local_vars, phase)) = self.visible_local_vars()
4602            && local_vars.contains(&name)
4603            && let Some(cell) = local_vars.get(&name, phase)
4604        {
4605            cell.set(value);
4606            return Ok(());
4607        }
4608        // A binding of the frame that called `eval` takes the write, which is what
4609        // makes `f("a = 3")` change the caller's `a`.
4610        if self.set_eval_binding(&name, &value)? {
4611            return Ok(());
4612        }
4613        // A closure that outlived its `eval` writes through to the same cell it reads.
4614        if let Some(cell) = self
4615            .frame()
4616            .env
4617            .eval_scope
4618            .as_ref()
4619            .and_then(|scope| scope.get(&name))
4620            .cloned()
4621        {
4622            cell.set(value);
4623            return Ok(());
4624        }
4625        // Inside a strict `eval`, a name it declared itself is stored there. An
4626        // *assignment* to a name nobody declared is not a declaration, so it falls
4627        // through: strict mode raises `ReferenceError` for it, which is what
4628        // `eval("1 + (@not_def = 1)")` has to do.
4629        if let Some(scope) = self.eval_scope.as_mut()
4630            && scope.contains_key(&name)
4631        {
4632            scope.insert(name, value);
4633            return Ok(());
4634        }
4635        if lexical {
4636            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4637                if is_const && !matches!(cell.get(), Value::Uninitialized) {
4638                    return Err(self.read_only_global(&name));
4639                }
4640                cell.set(value);
4641                return Ok(());
4642            }
4643            // Writing an undeclared lexical global is a `ReferenceError` in strict
4644            // mode and a silent global creation otherwise; creating the cell here
4645            // keeps both paths from losing the value.
4646            let cell = self.new_cell(value);
4647            self.realm.globals.insert(name, cell);
4648            return Ok(());
4649        }
4650        // A variable a direct `eval` declared in this call shadows the global object, even
4651        // when the global already has a property of that name — `var c = "global"` at the
4652        // top level must not capture `eval("var c = 1")` inside a function.
4653        if let Some((local_vars, phase)) = self.visible_local_vars()
4654            && local_vars.contains(&name)
4655            && let Some(cell) = local_vars.get(&name, phase)
4656        {
4657            cell.set(value);
4658            return Ok(());
4659        }
4660        let global = self.realm.global.clone();
4661        match global.own_property(&name) {
4662            // A `var` global is writable, so the store goes straight through — but
4663            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4664            // store (a non-writable or accessor-without-setter global) is a silent
4665            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4666            // split every other assignment has.
4667            Some(_) => {
4668                let on_failure = if self.current_strict() {
4669                    DeleteFailure::Throw
4670                } else {
4671                    DeleteFailure::Ignore
4672                };
4673                self.set_property_with(&global, &name, value, on_failure)
4674            }
4675            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4676            // declaration creates a *configurable* property, which is what makes it
4677            // deletable and is the one way a global differs from a declared `var`.
4678            // In strict mode the same store is a `ReferenceError` instead: that is the
4679            // whole point of strict mode, and creating the global silently meant
4680            // `"use strict"; x = 1` looked like it worked.
4681            None => {
4682                if self.current_strict() {
4683                    return Err(self.throw_reference(&name));
4684                }
4685                // A direct eval declares here rather than on the global object: its
4686                // `var`s belong to the caller's variable environment. `declare_eval_local`
4687                // also covers a plain assignment to a variable an earlier eval made.
4688                if let Some(cell) = self.declare_eval_local(&name) {
4689                    cell.set(value);
4690                    return Ok(());
4691                }
4692                global.define_data(&name, value);
4693                Ok(())
4694            }
4695        }
4696    }
4697
4698    /// The value of a binding of the frame that called `eval`, if there is one.
4699    fn eval_binding_value(&self, name: &str) -> Option<Value> {
4700        let binding = self
4701            .eval_bindings
4702            .iter()
4703            .find(|binding| binding.name == name)?;
4704        let owner = self.frames.get(binding.frame)?;
4705        let (slot, index) = (binding.slot, binding.index);
4706        Some(match slot {
4707            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4708                cell if cell >= 0 => owner
4709                    .cells
4710                    .get(cell as usize)
4711                    .map(|cell| cell.get())
4712                    .unwrap_or(Value::Undefined),
4713                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4714            },
4715            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4716                cell if cell >= 0 => owner
4717                    .cells
4718                    .get(cell as usize)
4719                    .map(|cell| cell.get())
4720                    .unwrap_or(Value::Undefined),
4721                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4722            },
4723        })
4724    }
4725
4726    /// Write to a binding of the frame that called `eval`.
4727    ///
4728    /// `Ok(false)` means no binding matched and the caller should keep looking. A
4729    /// matched binding can still refuse the store, which is why this is fallible: a
4730    /// `const` is read-only everywhere, and a named function expression's own name is
4731    /// read-only in strict mode.
4732    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4733        let Some(binding) = self
4734            .eval_bindings
4735            .iter()
4736            .find(|binding| binding.name == name)
4737        else {
4738            return Ok(false);
4739        };
4740        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4741        let strict = self.current_strict();
4742        let Some(owner) = self.frames.get_mut(frame) else {
4743            return Ok(false);
4744        };
4745        match slot {
4746            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4747                cell if cell >= 0 => {
4748                    if let Some(cell) = owner.cells.get(cell as usize) {
4749                        cell.set(value.clone());
4750                    }
4751                }
4752                _ => {
4753                    if let Some(slot) = owner.args.get_mut(index) {
4754                        *slot = value.clone();
4755                    }
4756                }
4757            },
4758            EvalSlot::Local => {
4759                let declared = owner.code.code.vars.get(index);
4760                // A `const` is read-only even through `eval`. The realm records this for
4761                // globals (see `lexical_consts`), but a local's `const`-ness is only in
4762                // the bytecode, so this is where it has to be enforced.
4763                if declared.is_some_and(|var| var.is_const) {
4764                    return Err(self.read_only_local(name));
4765                }
4766                // The name of a named function expression is read-only too, but only
4767                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4768                // such a name is ignored, the same as a direct store would be.
4769                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4770                    return if strict {
4771                        Err(self.read_only_local(name))
4772                    } else {
4773                        Ok(true)
4774                    };
4775                }
4776                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4777                    cell if cell >= 0 => {
4778                        if let Some(cell) = owner.cells.get(cell as usize) {
4779                            cell.set(value.clone());
4780                        }
4781                    }
4782                    _ => {
4783                        if let Some(slot) = owner.locals.get_mut(index) {
4784                            *slot = value.clone();
4785                        }
4786                    }
4787                }
4788            }
4789        }
4790        Ok(true)
4791    }
4792
4793    /// The `TypeError` an assignment to a read-only binding raises.
4794    fn read_only_local(&self, name: &str) -> Signal {
4795        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4796    }
4797
4798    /// Declare `name` as a variable of the frame that called the running `eval`.
4799    ///
4800    /// `None` when there is no direct eval in progress, or it was called from the top
4801    /// level — then the caller's variable environment *is* the global one and the
4802    /// existing path is right.
4803    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4804        let caller = self.eval_caller.flatten()?;
4805        // The bottom frame is the top-level script, whose variable environment *is* the
4806        // global one — so `eval("var x = 1")` at the top level still creates a global.
4807        if caller == 0 {
4808            return None;
4809        }
4810        // A name the eval's *own* variable environment already binds is not a new
4811        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4812        // `arguments`, and creating a second binding would leave the first — the one
4813        // closures read — untouched. A binding of an *outer* frame does not count: a
4814        // declaration shadows it rather than writing through.
4815        if self
4816            .eval_bindings
4817            .iter()
4818            .any(|binding| binding.name == name && binding.frame == caller)
4819        {
4820            return None;
4821        }
4822        let phase = if self.in_parameter_list_at(caller) {
4823            0
4824        } else {
4825            1
4826        };
4827        self.frame_local_vars(caller)?;
4828        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4829        if let Some(cell) = local_vars.get(name, 1) {
4830            return Some(cell);
4831        }
4832        let cell = self.new_cell(Value::Undefined);
4833        Some(local_vars.declare(name, phase, cell))
4834    }
4835
4836    /// Make sure `frame` has a `LocalVars`, creating it on demand.
4837    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4838        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4839            return Some(local_vars.clone());
4840        }
4841        let local_vars = Gc::new(self.heap, LocalVars::new());
4842        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4843        Some(local_vars)
4844    }
4845
4846    /// Whether the realm already has a binding for `name`, lexically or as an *own*
4847    /// property of the global object. Used to decide whether a store inside an
4848    /// `eval` writes through to the realm or declares a binding of its own.
4849    ///
4850    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4851    /// write to `Object.prototype.toString`, and must not shadow it either.
4852    fn global_knows(&mut self, name: &str) -> bool {
4853        if self.realm.globals.contains_key(name) {
4854            return true;
4855        }
4856        self.realm.global.own_property(name).is_some()
4857    }
4858
4859    /// Whether the code currently running is strict.
4860    ///
4861    /// Read off the frame's function, which is where the parser's answer ended up; a
4862    /// native function never runs strict-only checks, and there is no frame at all
4863    /// before the first script.
4864    pub fn current_strict(&self) -> bool {
4865        self.frames
4866            .last()
4867            .is_some_and(|frame| frame.code.code.strict)
4868    }
4869
4870    /// Initialise a declared global, which is what ends its dead zone.
4871    ///
4872    /// A `var` global becomes a property of the global object: writable, so a later
4873    /// assignment goes through, and non-configurable, so `delete` refuses.
4874    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4875        let (name, lexical, _) = self.global_binding(slot);
4876        // A `var` declared by the strict `eval` currently running belongs to the
4877        // eval's scope, not to the global object: `eval("var v = 1")` must not make
4878        // `typeof v` answer `"number"` afterwards. A name the realm already has is
4879        // initialised in place, which is what a re-declaration inside eval does.
4880        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4881            self.eval_scope
4882                .as_mut()
4883                .expect("checked above")
4884                .insert(name, value);
4885            return Ok(());
4886        }
4887        if let Some(scope) = self.eval_scope.as_mut()
4888            && scope.contains_key(&name)
4889        {
4890            scope.insert(name, value);
4891            return Ok(());
4892        }
4893        if lexical {
4894            // The cell exists (created at declaration time) holding the dead-zone
4895            // marker; storing the value is what makes the binding readable.
4896            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4897                cell.set(value);
4898                return Ok(());
4899            }
4900            let cell = self.new_cell(value);
4901            self.realm.globals.insert(name, cell);
4902            return Ok(());
4903        }
4904        let global = self.realm.global.clone();
4905        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4906        // to answer `false` and leave the binding in place. `with_attributes` ties
4907        // `configurable` to `writable`, so the property is built field by field.
4908        global.define(
4909            &name,
4910            Property {
4911                value: Some(value),
4912                writable: true,
4913                enumerable: true,
4914                configurable: false,
4915                ..Property::default()
4916            },
4917        );
4918        Ok(())
4919    }
4920
4921    /// The `TypeError` a store to a `const` global raises.
4922    fn read_only_global(&self, name: &str) -> Signal {
4923        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4924    }
4925
4926    // -- properties ---------------------------------------------------------
4927
4928    /// Read `object[key]`, following the prototype chain.
4929    ///
4930    /// An inherited accessor runs with the *receiver* as `this`, which is why the
4931    /// lookup returns the owner rather than just the value.
4932    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4933        self.get_property_key(object, &PropertyKey::from(key))
4934    }
4935
4936    /// [`Interp::get_property`] with a key that may be a symbol.
4937    pub fn get_property_key(
4938        &mut self,
4939        object: &Gc<JsObject>,
4940        key: &PropertyKey,
4941    ) -> JsResult<Option<Value>> {
4942        self.get_property_key_for(object, None, key)
4943    }
4944
4945    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
4946    ///
4947    /// The receiver matters when the property is found on a *prototype*: a getter has to
4948    /// see the object the read started from. For a primitive that is the primitive
4949    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
4950    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4951    /// the owner.
4952    pub fn get_property_key_for(
4953        &mut self,
4954        object: &Gc<JsObject>,
4955        receiver: Option<&Value>,
4956        key: &PropertyKey,
4957    ) -> JsResult<Option<Value>> {
4958        // A proxy answers for itself, before any of the shortcuts below: `new
4959        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4960        // have.
4961        if object.proxy_state().is_some() {
4962            let receiver = receiver
4963                .cloned()
4964                .unwrap_or_else(|| Value::Object(object.clone()));
4965            return self.proxy_get(object, &receiver, key);
4966        }
4967        // A host class's `get_property` trap replaces the whole read, prototype walk
4968        // included — that is what makes a native accessor free rather than a JavaScript
4969        // getter call.
4970        if let Some(exotic) = object.exotic() {
4971            let receiver_value = receiver
4972                .cloned()
4973                .unwrap_or_else(|| Value::Object(object.clone()));
4974            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
4975                return Ok(Some(value));
4976            }
4977            // With no `get_property` trap, a `get_own_property` trap still answers for the
4978            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
4979            // and the hook lives exactly there. A key the trap reports as absent is still
4980            // looked for on the prototype, which is why the search resumes *above*.
4981            if let Some(property) = exotic.get_own_property(self, object, key)? {
4982                return match property {
4983                    Some(property) => self.read_property(property, object, receiver),
4984                    None => match lookup_key_above(object, key) {
4985                        Some((_, property)) => self.read_property(property, object, receiver),
4986                        None => Ok(None),
4987                    },
4988                };
4989            }
4990        }
4991        // The element-vector and `length` shortcuts are string-only: an array index
4992        // has no symbol spelling.
4993        if let Some(text) = key.as_str() {
4994            if let Some(value) = self.own_element(object, text) {
4995                return Ok(Some(value));
4996            }
4997            // `length` is not stored as a property: an array's length is its element
4998            // count, and keeping one copy of it is what makes `push`/`pop` and
4999            // `a.length = n` agree.
5000            if let Some(length) = object.array_length()
5001                && text == "length"
5002            {
5003                // Not `Value::Int(length as i32)`: see [`length_value`].
5004                return Ok(Some(crate::object::length_value(length)));
5005            }
5006        }
5007        match lookup_key(object, key) {
5008            Some((_, property)) => self.read_property(property, object, receiver),
5009            None => Ok(None),
5010        }
5011    }
5012
5013    /// The value a property read answers.
5014    ///
5015    /// One place rather than three, because an accessor has to run with the *receiver* as
5016    /// `this` whether the descriptor came from the property table, an exotic
5017    /// `get_own_property` trap, or a prototype above one.
5018    fn read_property(
5019        &mut self,
5020        property: Property,
5021        object: &Gc<JsObject>,
5022        receiver: Option<&Value>,
5023    ) -> JsResult<Option<Value>> {
5024        if property.is_accessor() {
5025            match &property.getter {
5026                Some(getter) if !matches!(getter, Value::Undefined) => {
5027                    let receiver = receiver
5028                        .cloned()
5029                        .unwrap_or_else(|| Value::Object(object.clone()));
5030                    self.call_value(getter.clone(), receiver, Vec::new())
5031                        .map(Some)
5032                }
5033                // An accessor with no getter reads as `undefined`.
5034                _ => Ok(Some(Value::Undefined)),
5035            }
5036        } else {
5037            Ok(property.value)
5038        }
5039    }
5040
5041    /// `super.key` — start the search at `proto`, but report to `receiver`.
5042    ///
5043    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5044    /// found on the prototype of a class has to see the *instance* as `this`, and a
5045    /// plain property read off `proto` would lose that.
5046    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5047        let start = self.require_object(proto)?;
5048        let key = self.propkey(key)?;
5049        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5050        if matches!(proto, Value::Null) {
5051            return Ok(Value::Undefined);
5052        }
5053        match lookup_key(&start, &key) {
5054            Some((_, property)) if property.is_accessor() => match &property.getter {
5055                Some(getter) if !matches!(getter, Value::Undefined) => {
5056                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5057                }
5058                _ => Ok(Value::Undefined),
5059            },
5060            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5061            None => Ok(Value::Undefined),
5062        }
5063    }
5064
5065    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5066    ///
5067    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5068    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5069    /// assignment follows.
5070    fn super_write(
5071        &mut self,
5072        receiver: &Value,
5073        proto: &Value,
5074        key: &Value,
5075        value: Value,
5076    ) -> JsResult<()> {
5077        let target = self.require_object(receiver)?;
5078        let key = self.propkey(key)?;
5079        if !matches!(proto, Value::Null)
5080            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5081        {
5082            if property.is_accessor() {
5083                if let Some(setter) = &property.setter
5084                    && !matches!(setter, Value::Undefined)
5085                {
5086                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5087                }
5088                return Ok(());
5089            }
5090            // A data property on the prototype is writable or not; reading `owner` at
5091            // all is only for the attribute check.
5092            if !property.writable {
5093                return Err(self.type_error(format!("'{key}' is read-only")));
5094            }
5095            let _ = owner;
5096        }
5097        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5098    }
5099
5100    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5101    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5102        match value.as_object() {
5103            Some(object) => Ok(object.clone()),
5104            None => Err(Signal::Throw(
5105                self.make_error("TypeError", "value is not an object"),
5106            )),
5107        }
5108    }
5109
5110    /// Build the class object `define_class` produces.
5111    ///
5112    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5113    /// whose prototype property is a fresh object inheriting from the parent's
5114    /// prototype, and whose own prototype is the parent constructor — which is what makes
5115    /// a static method inherited too.
5116    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5117        let ctor = self.pop();
5118        let parent = self.pop();
5119        let Value::Object(function) = &ctor else {
5120            return Err(Signal::Throw(
5121                self.make_error("TypeError", "class constructor must be a function"),
5122            ));
5123        };
5124        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5125        // but gives the instances no prototype at all.
5126        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5127            match &parent {
5128                Value::Null => (Some(self.realm.function_proto.clone()), None),
5129                Value::Object(parent_class) => {
5130                    if !parent_class.is_callable() {
5131                        return Err(Signal::Throw(
5132                            self.make_error("TypeError", "parent class must be constructor"),
5133                        ));
5134                    }
5135                    let proto = self.get_property(parent_class, "prototype")?;
5136                    match proto {
5137                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5138                        Some(Value::Null) => (Some(parent_class.clone()), None),
5139                        _ => {
5140                            return Err(Signal::Throw(self.make_error(
5141                                "TypeError",
5142                                "parent prototype must be an object or null",
5143                            )));
5144                        }
5145                    }
5146                }
5147                _ => {
5148                    return Err(Signal::Throw(
5149                        self.make_error("TypeError", "parent class must be constructor"),
5150                    ));
5151                }
5152            }
5153        } else {
5154            (
5155                Some(self.realm.function_proto.clone()),
5156                Some(self.realm.object_proto.clone()),
5157            )
5158        };
5159        let proto = self.new_object(parent_proto);
5160        function.set_proto(parent_ctor);
5161        // A class is not callable without `new`, and its `prototype` is not writable —
5162        // both follow from being a class and are what `class A {}; A()` throws on.
5163        function.set_class_constructor(true);
5164        function.set_home_object(None);
5165        self.set_function_name(&ctor, name);
5166        self.define_class_properties(function, &ctor, &proto)?;
5167        Ok((ctor, proto))
5168    }
5169
5170    /// Give the constructor its `prototype` and `length`, and the prototype its
5171    /// `constructor` back-pointer.
5172    fn define_class_properties(
5173        &mut self,
5174        function: &Gc<JsObject>,
5175        ctor: &Value,
5176        proto: &Gc<JsObject>,
5177    ) -> JsResult<()> {
5178        proto.define(
5179            "constructor",
5180            Property::with_attributes(ctor.clone(), true, false),
5181        );
5182        function.define(
5183            "prototype",
5184            Property::prototype_of(Value::Object(proto.clone()), false),
5185        );
5186        if let Some((code, _)) = bytecode_of(function) {
5187            let length = code.code.defined_args;
5188            function.define(
5189                "length",
5190                Property::name_or_length(Value::Int(length as i32)),
5191            );
5192        }
5193        Ok(())
5194    }
5195
5196    /// The own array element `key` names, if this object has one.
5197    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5198        let index = array_index(key)?;
5199        // A typed array's elements live in its buffer, not in a property list: reading one
5200        // goes through the view's element type so a bounds check and a detached buffer are
5201        // both handled there.
5202        if object.typed_array_parts().is_some() {
5203            return object.typed_array_element(index as usize);
5204        }
5205        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5206        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5207        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5208        // `[1,,3][1]`.
5209        match object.array_get(index as usize) {
5210            Some(Value::Hole) | None => None,
5211            other => other,
5212        }
5213    }
5214
5215    /// Store `object[key] = value`, honouring setters and inherited properties.
5216    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5217        self.set_property_with(object, key, value, DeleteFailure::Throw)
5218    }
5219
5220    /// Store a property, choosing what to do when the object refuses.
5221    ///
5222    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5223    /// mode, which is the one place assignment differs by mode. Native code (the array
5224    /// methods, `JSON`) always asks for the throw.
5225    pub fn set_property_with(
5226        &mut self,
5227        object: &Gc<JsObject>,
5228        key: &str,
5229        value: Value,
5230        on_failure: DeleteFailure,
5231    ) -> JsResult<()> {
5232        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5233    }
5234
5235    /// [`Interp::set_property_with`] with a key that may be a symbol.
5236    pub fn set_property_with_key(
5237        &mut self,
5238        object: &Gc<JsObject>,
5239        key: &PropertyKey,
5240        value: Value,
5241        on_failure: DeleteFailure,
5242    ) -> JsResult<()> {
5243        self.set_property_with_key_receiver_aware(object, key, value, on_failure, true)
5244    }
5245
5246    /// As [`Interp::set_property_with_key`], with the receiver explicit.
5247    ///
5248    /// `same_receiver` is `SameValue(O, Receiver)` from §10.4.5.5 step 1.b.i, and the two
5249    /// branches it separates are observable in opposite directions: when the receiver *is*
5250    /// the view the element store converts `V` first and then asks whether the index is
5251    /// valid (`Set/resized-out-of-bounds-to-in-bounds-index`, where a `valueOf` puts the
5252    /// index back in bounds), and when it is not, an invalid index returns `true` without
5253    /// converting anything (`key-is-out-of-bounds-receiver-is-not-object`).
5254    fn set_property_with_key_receiver_aware(
5255        &mut self,
5256        object: &Gc<JsObject>,
5257        key: &PropertyKey,
5258        value: Value,
5259        on_failure: DeleteFailure,
5260        same_receiver: bool,
5261    ) -> JsResult<()> {
5262        // A proxy's `set` trap decides, and its `false` means the same thing an
5263        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5264        if object.proxy_state().is_some() {
5265            let receiver = Value::Object(object.clone());
5266            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5267                return match (accepted, on_failure) {
5268                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5269                    (false, DeleteFailure::Throw) => {
5270                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5271                    }
5272                };
5273            }
5274        }
5275        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5276        // refusal and means exactly what a proxy's `false` means.
5277        if let Some(exotic) = object.exotic() {
5278            let receiver = Value::Object(object.clone());
5279            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5280                return match (accepted, on_failure) {
5281                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5282                    (false, DeleteFailure::Throw) => {
5283                        Err(self.type_error(format!("property '{key}' is read-only")))
5284                    }
5285                };
5286            }
5287        }
5288        // The element and `length` shortcuts only exist for string keys: an array
5289        // index has no symbol spelling, and a symbol named `length` is an ordinary
5290        // property.
5291        let text = key.as_str();
5292        // A typed array's elements are a window onto its buffer: the store has to go
5293        // through the view's element type so the value is wrapped (or clamped) and so an
5294        // out-of-range or detached write is a silent no-op, as the spec says.
5295        if let Some(text) = text
5296            && let Some(index) = array_index(text)
5297            && let Some(element) = object.typed_array_element_type()
5298        {
5299            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5300            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5301            // in `Interp`, because it is script-observable and the storage borrow inside
5302            // `typed_array_set` must not be held across it.
5303            //
5304            // It runs even for an index that is out of bounds *now*, because `V` itself can
5305            // put it back in bounds: `TypedArraySetElement` converts first and asks
5306            // `IsValidIntegerIndex` afterwards, which is what
5307            // `Set/resized-out-of-bounds-to-in-bounds-index` asserts (a `valueOf` that
5308            // resizes a 0-byte buffer to 1 makes `ta[0] = value` store 100). The write is
5309            // still a no-op when the index stays out of bounds, which is why the extra
5310            // length check that used to guard this has no job left.
5311            if !same_receiver && index as usize >= object.typed_array_length().unwrap_or(0) {
5312                return Ok(());
5313            }
5314            let stored = self.element_value(element, value)?;
5315            if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5316                return Err(self.type_error(reason));
5317            }
5318            return Ok(());
5319        }
5320        if let Some(text) = text
5321            && let Some(index) = array_index(text)
5322            && object.is_array()
5323        {
5324            // An accessor defined on an index lives in the property table while the
5325            // element slot is a hole, so the store has to go through the property first.
5326            // Writing the vector directly skipped the setter entirely.
5327            if let Some(existing) = object.own_property_key(key) {
5328                if existing.is_accessor() {
5329                    return match existing.setter.clone() {
5330                        Some(setter) if !matches!(setter, Value::Undefined) => {
5331                            let receiver = Value::Object(object.clone());
5332                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5333                        }
5334                        _ => match on_failure {
5335                            DeleteFailure::Throw => Err(self.type_error(format!(
5336                                "cannot set property '{text}', it has only a getter"
5337                            ))),
5338                            DeleteFailure::Ignore => Ok(()),
5339                        },
5340                    };
5341                }
5342                if !existing.writable {
5343                    return match on_failure {
5344                        DeleteFailure::Throw => {
5345                            Err(self.type_error(format!("'{text}' is read-only")))
5346                        }
5347                        DeleteFailure::Ignore => Ok(()),
5348                    };
5349                }
5350            }
5351            {
5352                // Growing the array needs a writable `length`.
5353                if (index as usize) >= object.array_length().unwrap_or(0)
5354                    && !object.length_writable()
5355                {
5356                    return match on_failure {
5357                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5358                        DeleteFailure::Ignore => Ok(()),
5359                    };
5360                }
5361                // Adding an index past the end makes the array longer, which a
5362                // non-extensible array refuses.
5363                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5364                    return match on_failure {
5365                        DeleteFailure::Throw => Err(self.type_error(format!(
5366                            "cannot add property '{key}', object is not extensible"
5367                        ))),
5368                        DeleteFailure::Ignore => Ok(()),
5369                    };
5370                }
5371                if object.element_is_locked(index) {
5372                    return match on_failure {
5373                        DeleteFailure::Throw => {
5374                            Err(self.type_error(format!("'{key}' is read-only")))
5375                        }
5376                        DeleteFailure::Ignore => Ok(()),
5377                    };
5378                }
5379                // The element vector is only half of `[[Set]]` for an index: the
5380                // prototype chain is consulted first, and a setter there answers instead
5381                // of the element store. This branch used to write the element directly, so
5382                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5383                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5384                // the reference calls the setter and the array keeps no own index.
5385                if let Some((owner, property)) = lookup_key(object, key)
5386                    && !owner.ptr_eq(object)
5387                {
5388                    match &property {
5389                        property if property.is_accessor() => {
5390                            match &property.setter {
5391                                Some(setter) if !matches!(setter, Value::Undefined) => {
5392                                    let receiver = Value::Object(object.clone());
5393                                    self.call_value(setter.clone(), receiver, vec![value])?;
5394                                }
5395                                _ => {
5396                                    return match on_failure {
5397                                        DeleteFailure::Throw => Err(self.type_error(format!(
5398                                            "cannot set property '{text}', it has only a getter"
5399                                        ))),
5400                                        DeleteFailure::Ignore => Ok(()),
5401                                    };
5402                                }
5403                            }
5404                            return Ok(());
5405                        }
5406                        property if !property.writable => {
5407                            return match on_failure {
5408                                DeleteFailure::Throw => {
5409                                    Err(self.type_error(format!("'{text}' is read-only")))
5410                                }
5411                                DeleteFailure::Ignore => Ok(()),
5412                            };
5413                        }
5414                        _ => {}
5415                    }
5416                }
5417                if object.array_set(self.heap, index as usize, value.clone()) {
5418                    return Ok(());
5419                }
5420                // Past the dense limit the slot is too far out to be worth one `Value`
5421                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5422                // constant time by keeping the index as an ordinary property. The store
5423                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5424                // to a legal program.
5425                object.define_key(key, Property::with_attributes(value, true, true));
5426                // Extend, never shorten: the index may be *inside* the current length (a
5427                // huge `length` with a sparse store), and shortening would delete the
5428                // sparse properties above it — including the one just stored.
5429                if index as usize + 1 > object.array_length().unwrap_or(0) {
5430                    object.array_set_length(self.heap, index as usize + 1);
5431                }
5432                return Ok(());
5433            }
5434        }
5435        if text == Some("length") && object.is_array() {
5436            if !object.length_writable() {
5437                return match on_failure {
5438                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5439                    DeleteFailure::Ignore => Ok(()),
5440                };
5441            }
5442            let length = value.to_number();
5443            if length.is_finite() && length >= 0.0 {
5444                let length = length as usize;
5445                // `a.length = n` with `n` below a non-configurable element cannot
5446                // drop that element, so the whole assignment fails. The spec makes
5447                // this a `TypeError` rather than a silent no-op, in any mode.
5448                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5449                    // Sloppy mode stops the truncation at the blocking element
5450                    // instead of failing; strict mode raises.
5451                    // Both modes stop at the blocking element; they differ in
5452                    // whether that is reported. The reference truncates *then*
5453                    // throws, so the array is left in the shortened state.
5454                    object.array_truncate(self.heap, blocked + 1);
5455                    return match on_failure {
5456                        DeleteFailure::Throw => {
5457                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5458                        }
5459                        DeleteFailure::Ignore => Ok(()),
5460                    };
5461                }
5462                object.array_set_length(self.heap, length);
5463                return Ok(());
5464            }
5465        }
5466        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5467        {
5468            return match on_failure {
5469                DeleteFailure::Throw => Err(self.type_error(format!(
5470                    "cannot add property {}, object is not extensible",
5471                    key
5472                ))),
5473                DeleteFailure::Ignore => Ok(()),
5474            };
5475        }
5476        if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5477            if property.is_accessor() {
5478                match &property.setter {
5479                    Some(setter) if !matches!(setter, Value::Undefined) => {
5480                        let receiver = Value::Object(object.clone());
5481                        self.call_value(setter.clone(), receiver, vec![value])?;
5482                    }
5483                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5484                    // Sloppy code swallows that refusal, strict code raises — the same
5485                    // rule the read-only *data* property below follows, and skipping it
5486                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5487                    // return silently. The reference answers `TypeError: 'x' is
5488                    // read-only`.
5489                    _ => {
5490                        return match on_failure {
5491                            DeleteFailure::Throw => {
5492                                Err(self.type_error(format!("'{key}' is read-only")))
5493                            }
5494                            DeleteFailure::Ignore => Ok(()),
5495                        };
5496                    }
5497                }
5498                return Ok(());
5499            }
5500            // A non-writable data property refuses the write, own **or inherited**: an
5501            // own one stops here because nothing may change it, and an inherited one
5502            // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5503            //
5504            // The `ptr_eq` this used to carry meant an inherited read-only property fell
5505            // through to `define_data_key` and *did* create the shadow — `var o =
5506            // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5507            // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5508            // and `false`.
5509            if !property.writable {
5510                return match on_failure {
5511                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5512                    DeleteFailure::Ignore => Ok(()),
5513                };
5514            }
5515            // An existing writable own property keeps its attributes: only the value
5516            // moves. Redefining instead would reset them, which is how a
5517            // non-configurable global `var` used to become deletable.
5518            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5519                return Ok(());
5520            }
5521        }
5522        // No own data property: create one, shadowing whatever the prototype holds.
5523        object.define_data_key(key, value);
5524        Ok(())
5525    }
5526
5527    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5528    ///
5529    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5530    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5531    /// a virtual accessor gets its setter run without implementing `set_property` at all.
5532    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5533    /// the prototype, so the walk resumes above the object.
5534    fn lookup_for_write(
5535        &mut self,
5536        object: &Gc<JsObject>,
5537        key: &PropertyKey,
5538    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5539        let Some(exotic) = object.exotic() else {
5540            return Ok(lookup_key(object, key));
5541        };
5542        Ok(match exotic.get_own_property(self, object, key)? {
5543            Some(Some(property)) => Some((object.clone(), property)),
5544            Some(None) => lookup_key_above(object, key),
5545            None => lookup_key(object, key),
5546        })
5547    }
5548
5549    /// Delete `object[key]`.
5550    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5551        self.delete_property_key(object, &PropertyKey::from(key))
5552    }
5553
5554    /// [`Interp::delete_property`] with a key that may be a symbol.
5555    pub fn delete_property_key(
5556        &mut self,
5557        object: &Gc<JsObject>,
5558        key: &PropertyKey,
5559    ) -> JsResult<bool> {
5560        // A proxy decides for itself, and may even throw; the invariant checks live in
5561        // `proxy_delete`.
5562        if let Some(answer) = self.proxy_delete(object, key)? {
5563            return Ok(answer);
5564        }
5565        // A host class's `delete_property` trap decides; `false` is a refusal, which the
5566        // caller reports as a failed delete.
5567        if let Some(exotic) = object.exotic()
5568            && let Some(answer) = exotic.delete_property(self, object, key)?
5569        {
5570            return Ok(answer);
5571        }
5572        if let Some(index) = key.as_str().and_then(array_index)
5573            && let Some(length) = object.array_length()
5574            && (index as usize) < length
5575        {
5576            // An accessor defined on an index lives in the property table rather than the
5577            // element vector, so both have to be cleared: `delete` after
5578            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5579            object.delete_key(key);
5580            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5581            // index stops answering `in`.
5582            if object.element_is_undeletable(index) {
5583                return Ok(false);
5584            }
5585            object.array_set(self.heap, index as usize, Value::Hole);
5586            return Ok(true);
5587        }
5588        Ok(object.delete_key(key))
5589    }
5590
5591    // -- proxy traps --------------------------------------------------------
5592    //
5593    // A proxy's internal methods all look the same: ask the handler for the trap, call it
5594    // with the target and the operation's own arguments, then check the answer against
5595    // the target. The checks are not decoration — they are what stops a proxy from
5596    // reporting a `non-configurable` property as missing, which would let a frozen object
5597    // be rewritten by standing in front of it.
5598
5599    /// The target and handler of `object`, or `None` when it is not a proxy.
5600    ///
5601    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5602    /// one has to fail: the slots the traps would have been read from are gone.
5603    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5604        let Some(state) = object.proxy_state() else {
5605            return Ok(None);
5606        };
5607        let state = state.borrow();
5608        match (&state.target, &state.handler) {
5609            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5610            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5611        }
5612    }
5613
5614    /// Call `handler[name]`, or answer `None` when the trap is absent.
5615    ///
5616    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5617    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5618    /// back to the target.
5619    fn proxy_trap(
5620        &mut self,
5621        handler: &Value,
5622        name: &str,
5623        args: Vec<Value>,
5624    ) -> JsResult<Option<Value>> {
5625        let Value::Object(table) = handler else {
5626            return Err(self.type_error("proxy handler is not an object"));
5627        };
5628        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5629        match trap {
5630            Value::Undefined => Ok(None),
5631            Value::Object(function) if function.is_callable() => {
5632                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5633                Ok(Some(answer))
5634            }
5635            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5636        }
5637    }
5638
5639    /// Whether `object`'s own property `key` is one the target refuses to lose.
5640    ///
5641    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5642    /// its value behind the target's back. This goes through
5643    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5644    /// elements and its `length` — both fixed, both outside the table — are covered.
5645    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5646        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5647    }
5648
5649    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5650    fn proxy_get(
5651        &mut self,
5652        object: &Gc<JsObject>,
5653        receiver: &Value,
5654        key: &PropertyKey,
5655    ) -> JsResult<Option<Value>> {
5656        let Some((target, handler)) = self.proxy_parts(object)? else {
5657            return Ok(None);
5658        };
5659        let key_value = self.key_value(key);
5660        let Some(result) = self.proxy_trap(
5661            &handler,
5662            "get",
5663            vec![Value::Object(target.clone()), key_value, receiver.clone()],
5664        )?
5665        else {
5666            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5667            // inherited getter still sees the proxy.
5668            return Ok(Some(
5669                self.get_property_key_for(&target, Some(receiver), key)?
5670                    .unwrap_or(Value::Undefined),
5671            ));
5672        };
5673        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5674            if fixed.is_accessor() {
5675                // A fixed accessor with no getter must read as `undefined`.
5676                let has_getter = fixed
5677                    .getter
5678                    .as_ref()
5679                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
5680                if !has_getter && !matches!(result, Value::Undefined) {
5681                    return Err(self.type_error(format!(
5682                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
5683                    )));
5684                }
5685            } else if !fixed.writable {
5686                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5687                if !fixed_value.same_value(&result) {
5688                    return Err(self.type_error(format!(
5689                        "proxy 'get' disagrees with the non-configurable property '{key}'"
5690                    )));
5691                }
5692            }
5693        }
5694        Ok(Some(result))
5695    }
5696
5697    /// `[[Set]]` on a proxy.
5698    ///
5699    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5700    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5701    /// read-only store has.
5702    fn proxy_set(
5703        &mut self,
5704        object: &Gc<JsObject>,
5705        key: &PropertyKey,
5706        value: Value,
5707        receiver: &Value,
5708    ) -> JsResult<Option<bool>> {
5709        let Some((target, handler)) = self.proxy_parts(object)? else {
5710            return Ok(None);
5711        };
5712        let key_value = self.key_value(key);
5713        let Some(result) = self.proxy_trap(
5714            &handler,
5715            "set",
5716            vec![
5717                Value::Object(target.clone()),
5718                key_value,
5719                value.clone(),
5720                receiver.clone(),
5721            ],
5722        )?
5723        else {
5724            // No trap: store on the target, which is where an ordinary proxy write lands.
5725            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5726            return Ok(Some(true));
5727        };
5728        if !result.to_boolean() {
5729            return Ok(Some(false));
5730        }
5731        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5732            if fixed.is_accessor() {
5733                let has_setter = fixed
5734                    .setter
5735                    .as_ref()
5736                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
5737                if !has_setter {
5738                    return Err(self.type_error(format!(
5739                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5740                    )));
5741                }
5742            } else if !fixed.writable {
5743                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5744                if !fixed_value.same_value(&value) {
5745                    return Err(self.type_error(format!(
5746                        "proxy 'set' changed the non-configurable property '{key}'"
5747                    )));
5748                }
5749            }
5750        }
5751        // A new property cannot appear on a target that refuses new properties.
5752        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5753            return Err(self.type_error(format!(
5754                "proxy 'set' added '{key}' to a non-extensible target"
5755            )));
5756        }
5757        Ok(Some(true))
5758    }
5759
5760    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5761    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5762        let Some((target, handler)) = self.proxy_parts(object)? else {
5763            return Ok(None);
5764        };
5765        let key_value = self.key_value(key);
5766        let Some(result) = self.proxy_trap(
5767            &handler,
5768            "has",
5769            vec![Value::Object(target.clone()), key_value],
5770        )?
5771        else {
5772            return Ok(Some(self.has_own_or_inherited(&target, key)?));
5773        };
5774        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5775            return Err(self.type_error(format!(
5776                "proxy 'has' denied the non-configurable property '{key}'"
5777            )));
5778        }
5779        // A non-extensible target cannot grow, so every own property it *has* is fixed.
5780        if !result.to_boolean()
5781            && !target.is_extensible()
5782            && Self::ordinary_own_property(&target, key).is_some()
5783        {
5784            return Err(self.type_error(format!(
5785                "proxy 'has' denied the own property '{key}' of a non-extensible target"
5786            )));
5787        }
5788        Ok(Some(result.to_boolean()))
5789    }
5790
5791    /// `[[Delete]]` on a proxy.
5792    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5793        let Some((target, handler)) = self.proxy_parts(object)? else {
5794            return Ok(None);
5795        };
5796        let key_value = self.key_value(key);
5797        let Some(result) = self.proxy_trap(
5798            &handler,
5799            "deleteProperty",
5800            vec![Value::Object(target.clone()), key_value],
5801        )?
5802        else {
5803            return Ok(Some(self.delete_property_key(&target, key)?));
5804        };
5805        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5806            return Err(self.type_error(format!(
5807                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5808            )));
5809        }
5810        if result.to_boolean()
5811            && !target.is_extensible()
5812            && Self::ordinary_own_property(&target, key).is_some()
5813        {
5814            return Err(self.type_error(format!(
5815                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5816            )));
5817        }
5818        Ok(Some(result.to_boolean()))
5819    }
5820
5821    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5822    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5823        let Some((target, handler)) = self.proxy_parts(object)? else {
5824            return Ok(None);
5825        };
5826        let Some(result) =
5827            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5828        else {
5829            // No trap: the target's own keys, already in the order an object reports.
5830            return Ok(Some(self.object_own_property_keys(&target)?));
5831        };
5832        // `CreateListFromArrayLike` with the string-or-symbol restriction.
5833        let list = self.list_from_array_like(&result, true)?;
5834        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5835        for value in list {
5836            let key = self.propkey(&value)?;
5837            if keys.contains(&key) {
5838                return Err(self.type_error(format!(
5839                    "proxy 'ownKeys' returned the duplicate key '{key}'"
5840                )));
5841            }
5842            keys.push(key);
5843        }
5844        for (key, property) in target.property_entries() {
5845            if !property.configurable && !keys.contains(&key) {
5846                return Err(self.type_error(format!(
5847                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5848                )));
5849            }
5850            if !target.is_extensible() && !keys.contains(&key) {
5851                return Err(self.type_error(format!(
5852                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5853                )));
5854            }
5855        }
5856        if !target.is_extensible() {
5857            let own = target.property_entries().len();
5858            if keys.len() != own {
5859                return Err(
5860                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5861                );
5862            }
5863        }
5864        Ok(Some(keys))
5865    }
5866
5867    /// `[[GetOwnProperty]]` on a proxy.
5868    fn proxy_get_own_property(
5869        &mut self,
5870        object: &Gc<JsObject>,
5871        key: &PropertyKey,
5872    ) -> JsResult<Option<Option<Property>>> {
5873        let Some((target, handler)) = self.proxy_parts(object)? else {
5874            return Ok(None);
5875        };
5876        let key_value = self.key_value(key);
5877        let Some(result) = self.proxy_trap(
5878            &handler,
5879            "getOwnPropertyDescriptor",
5880            vec![Value::Object(target.clone()), key_value],
5881        )?
5882        else {
5883            // No trap: the target's own descriptor is the answer. This has to go through
5884            // the same synthesis an ordinary object gets, because a proxy's own property
5885            // table is empty by design — reading it directly reported `undefined` for
5886            // every key, including an array's indices and `length`.
5887            return Ok(Some(Self::ordinary_own_property(&target, key)));
5888        };
5889        let answer = if matches!(result, Value::Undefined) {
5890            None
5891        } else {
5892            Some(self.property_from_descriptor(&result)?)
5893        };
5894        let fixed = Self::is_fixed_property(&target, key);
5895        match (&answer, &fixed) {
5896            // A non-configurable property cannot be reported as absent.
5897            (None, Some(_)) => {
5898                return Err(self.type_error(format!(
5899                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5900                )));
5901            }
5902            (Some(descriptor), Some(fixed)) => {
5903                if descriptor.configurable {
5904                    return Err(self.type_error(format!(
5905                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5906                    )));
5907                }
5908                if fixed.is_accessor() != descriptor.is_accessor() {
5909                    return Err(self.type_error(format!(
5910                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5911                    )));
5912                }
5913                if !fixed.is_accessor() && !fixed.writable {
5914                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5915                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5916                    if !fixed_value.same_value(&reported) {
5917                        return Err(self.type_error(format!(
5918                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5919                        )));
5920                    }
5921                }
5922            }
5923            _ => {}
5924        }
5925        Ok(Some(answer))
5926    }
5927
5928    /// `[[DefineOwnProperty]]` on a proxy.
5929    fn proxy_define_property(
5930        &mut self,
5931        object: &Gc<JsObject>,
5932        key: &PropertyKey,
5933        property: Property,
5934    ) -> JsResult<Option<bool>> {
5935        let Some((target, handler)) = self.proxy_parts(object)? else {
5936            return Ok(None);
5937        };
5938        let key_value = self.key_value(key);
5939        let descriptor = self.descriptor_from_property(&property);
5940        let Some(result) = self.proxy_trap(
5941            &handler,
5942            "defineProperty",
5943            vec![Value::Object(target.clone()), key_value, descriptor],
5944        )?
5945        else {
5946            return Ok(None);
5947        };
5948        if !result.to_boolean() {
5949            return Ok(Some(false));
5950        }
5951        let fixed = Self::is_fixed_property(&target, key);
5952        let creating = Self::ordinary_own_property(&target, key).is_none();
5953        if creating && !target.is_extensible() {
5954            return Err(self.type_error(format!(
5955                "proxy 'defineProperty' added '{key}' to a non-extensible target"
5956            )));
5957        }
5958        if let Some(fixed) = fixed {
5959            if property.configurable {
5960                return Err(self.type_error(format!(
5961                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
5962                )));
5963            }
5964            if !fixed.writable && property.writable && !fixed.is_accessor() {
5965                return Err(self.type_error(format!(
5966                    "proxy 'defineProperty' made the read-only '{key}' writable"
5967                )));
5968            }
5969        }
5970        Ok(Some(true))
5971    }
5972
5973    /// `[[GetPrototypeOf]]` on a proxy.
5974    fn proxy_get_prototype_of(
5975        &mut self,
5976        object: &Gc<JsObject>,
5977    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
5978        let Some((target, handler)) = self.proxy_parts(object)? else {
5979            return Ok(None);
5980        };
5981        let Some(result) = self.proxy_trap(
5982            &handler,
5983            "getPrototypeOf",
5984            vec![Value::Object(target.clone())],
5985        )?
5986        else {
5987            return Ok(Some(target.proto()));
5988        };
5989        let proto = match &result {
5990            Value::Null => None,
5991            Value::Object(proto) => Some(proto.clone()),
5992            _ => {
5993                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
5994            }
5995        };
5996        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
5997            return Err(self.type_error(
5998                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
5999            ));
6000        }
6001        Ok(Some(proto))
6002    }
6003
6004    /// `[[SetPrototypeOf]]` on a proxy.
6005    fn proxy_set_prototype_of(
6006        &mut self,
6007        object: &Gc<JsObject>,
6008        proto: Option<Gc<JsObject>>,
6009    ) -> JsResult<Option<bool>> {
6010        let Some((target, handler)) = self.proxy_parts(object)? else {
6011            return Ok(None);
6012        };
6013        let proto_value = match &proto {
6014            Some(proto) => Value::Object(proto.clone()),
6015            None => Value::Null,
6016        };
6017        let Some(result) = self.proxy_trap(
6018            &handler,
6019            "setPrototypeOf",
6020            vec![Value::Object(target.clone()), proto_value],
6021        )?
6022        else {
6023            target.set_proto(proto);
6024            return Ok(Some(true));
6025        };
6026        if result.to_boolean()
6027            && !target.is_extensible()
6028            && !same_proto(proto.as_ref(), target.proto().as_ref())
6029        {
6030            return Err(self.type_error(
6031                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6032            ));
6033        }
6034        Ok(Some(result.to_boolean()))
6035    }
6036
6037    /// `[[IsExtensible]]` on a proxy.
6038    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6039        let Some((target, handler)) = self.proxy_parts(object)? else {
6040            return Ok(None);
6041        };
6042        let Some(result) = self.proxy_trap(
6043            &handler,
6044            "isExtensible",
6045            vec![Value::Object(target.clone())],
6046        )?
6047        else {
6048            return Ok(Some(target.is_extensible()));
6049        };
6050        // The answer is not the proxy's to invent: it must agree with the target, or a
6051        // script could learn `false` while the target keeps accepting new properties.
6052        if result.to_boolean() != target.is_extensible() {
6053            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6054        }
6055        Ok(Some(result.to_boolean()))
6056    }
6057
6058    /// `[[PreventExtensions]]` on a proxy.
6059    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6060        let Some((target, handler)) = self.proxy_parts(object)? else {
6061            return Ok(None);
6062        };
6063        let Some(result) = self.proxy_trap(
6064            &handler,
6065            "preventExtensions",
6066            vec![Value::Object(target.clone())],
6067        )?
6068        else {
6069            target.set_extensible(false);
6070            return Ok(Some(true));
6071        };
6072        if result.to_boolean() && target.is_extensible() {
6073            return Err(self.type_error(
6074                "proxy 'preventExtensions' reported success but the target is still extensible",
6075            ));
6076        }
6077        Ok(Some(result.to_boolean()))
6078    }
6079
6080    /// `[[Call]]` on a proxy, through the `apply` trap.
6081    fn proxy_apply(
6082        &mut self,
6083        object: &Gc<JsObject>,
6084        this: Value,
6085        args: Vec<Value>,
6086    ) -> JsResult<Option<Value>> {
6087        let Some((target, handler)) = self.proxy_parts(object)? else {
6088            return Ok(None);
6089        };
6090        // The trap gets the arguments as one array, which is the shape the spec passes
6091        // and the shape `apply` traps are written against (`args[0]` is the first one).
6092        let arguments = self.new_array(args.clone());
6093        let this_for_trap = this.clone();
6094        let Some(result) = self.proxy_trap(
6095            &handler,
6096            "apply",
6097            vec![
6098                Value::Object(target.clone()),
6099                this_for_trap,
6100                Value::Object(arguments),
6101            ],
6102        )?
6103        else {
6104            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6105        };
6106        Ok(Some(result))
6107    }
6108
6109    /// `[[Construct]]` on a proxy, through the `construct` trap.
6110    fn proxy_construct(
6111        &mut self,
6112        object: &Gc<JsObject>,
6113        args: Vec<Value>,
6114        new_target: &Value,
6115    ) -> JsResult<Option<Value>> {
6116        let Some((target, handler)) = self.proxy_parts(object)? else {
6117            return Ok(None);
6118        };
6119        if !target.is_callable() {
6120            return Err(self.type_error("proxy target is not a constructor"));
6121        }
6122        let arguments = self.new_array(args.clone());
6123        let Some(result) = self.proxy_trap(
6124            &handler,
6125            "construct",
6126            vec![
6127                Value::Object(target.clone()),
6128                Value::Object(arguments),
6129                new_target.clone(),
6130            ],
6131        )?
6132        else {
6133            return Ok(Some(self.construct(
6134                Value::Object(target),
6135                new_target.clone(),
6136                args,
6137            )?));
6138        };
6139        if !matches!(result, Value::Object(_)) {
6140            return Err(self.type_error("proxy 'construct' must return an object"));
6141        }
6142        Ok(Some(result))
6143    }
6144
6145    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6146    pub(crate) fn has_own_or_inherited(
6147        &mut self,
6148        object: &Gc<JsObject>,
6149        key: &PropertyKey,
6150    ) -> JsResult<bool> {
6151        // The object itself first: it may be a proxy, and then the answer is its trap's.
6152        if let Some(answer) = self.proxy_has(object, key)? {
6153            return Ok(answer);
6154        }
6155        // An integer-indexed exotic object answers a canonical numeric index from
6156        // `IsValidIntegerIndex` alone (§10.4.5.4 step 1.b.i) — **without** walking the
6157        // prototype chain. That is observable: a view the buffer has been resized away from
6158        // has no indices, so `2 in view` is `false` even when
6159        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
6160        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
6161        // The `[[HasProperty]]` that `in` compiles to goes through here, which is why the
6162        // same rule is repeated in `has_property_key` rather than living only there.
6163        if object.typed_array_parts().is_some()
6164            && let Some(index) = key.as_str().and_then(array_index)
6165        {
6166            return Ok(object
6167                .typed_array_length()
6168                .is_some_and(|length| (index as usize) < length));
6169        }
6170        // A host class answers `in` for its own keys, which may live nowhere in a property
6171        // table — `"x" in point` is true because the class says so, not because a property
6172        // exists.
6173        if let Some(exotic) = object.exotic()
6174            && let Some(answer) = exotic.has_property(self, object, key)?
6175        {
6176            return Ok(answer);
6177        }
6178        // `has_own` rather than `own_property_key`: an array's elements and its derived
6179        // `length` are invisible to the property table, and `Array.prototype` is an array.
6180        // A host class's `get_own_property` counts too, because the reference's
6181        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6182        // lives — a class with only `get_own_property` answers `in` through it.
6183        if self.exotic_has_own(object, key)? {
6184            return Ok(true);
6185        }
6186        // A hole is *not* the end of the search: the chain may still have the key, which
6187        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6188        for ancestor in object.chain() {
6189            // A proxy further up the chain answers for itself.
6190            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6191                return Ok(answer);
6192            }
6193            // Same for a host class: a prototype may be one, and `in` reaches it.
6194            if let Some(exotic) = ancestor.exotic()
6195                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6196            {
6197                return Ok(answer);
6198            }
6199            if self.exotic_has_own(&ancestor, key)? {
6200                return Ok(true);
6201            }
6202        }
6203        Ok(false)
6204    }
6205
6206    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6207    /// trap included.
6208    ///
6209    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6210    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6211    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6212        if let Some(exotic) = object.exotic()
6213            && let Some(answer) = exotic.get_own_property(self, object, key)?
6214        {
6215            return Ok(answer.is_some());
6216        }
6217        Ok(has_own(object, key))
6218    }
6219
6220    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6221    ///
6222    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6223    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6224    /// `TypeError` instead of a property named `"1.5"`.
6225    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6226        let object = self.object_from(value)?;
6227        let length = self
6228            .get_property(&object, "length")?
6229            .map(|value| value.to_number())
6230            .unwrap_or(0.0);
6231        if !length.is_finite() || length < 0.0 {
6232            return Err(self.type_error("invalid array-like length"));
6233        }
6234        let length = length as usize;
6235        let mut items = Vec::with_capacity(length.min(1024));
6236        for index in 0..length {
6237            let item = self
6238                .get_property(&object, &index.to_string())?
6239                .unwrap_or(Value::Undefined);
6240            if keys_only && matches!(&item, Value::Symbol(_)) {
6241                items.push(item);
6242                continue;
6243            }
6244            if keys_only && !matches!(&item, Value::String(_)) {
6245                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6246            }
6247            items.push(item);
6248        }
6249        Ok(items)
6250    }
6251
6252    /// A `Property` from the descriptor object a trap returned.
6253    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6254        let object = self.object_from(value)?;
6255        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6256            interp.get_property(&object, name)
6257        };
6258        let getter = field(self, "get")?;
6259        let setter = field(self, "set")?;
6260        let accessor = getter.is_some() || setter.is_some();
6261        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6262            Ok(interp
6263                .get_property(&object, name)?
6264                .is_some_and(|value| value.to_boolean()))
6265        };
6266        let enumerable = boolean(self, "enumerable")?;
6267        let configurable = boolean(self, "configurable")?;
6268        if accessor {
6269            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6270                return Err(
6271                    self.type_error("a descriptor cannot be both a data property and an accessor")
6272                );
6273            }
6274            Ok(Property {
6275                getter: getter.or(Some(Value::Undefined)),
6276                setter: setter.or(Some(Value::Undefined)),
6277                enumerable,
6278                configurable,
6279                writable: false,
6280                value: None,
6281            })
6282        } else {
6283            Ok(Property {
6284                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6285                writable: boolean(self, "writable")?,
6286                enumerable,
6287                configurable,
6288                getter: None,
6289                setter: None,
6290            })
6291        }
6292    }
6293
6294    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6295    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6296        let object = self.new_object(None);
6297        if property.is_accessor() {
6298            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6299            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6300            object.define_data("get", getter);
6301            object.define_data("set", setter);
6302        } else {
6303            let value = property.value.clone().unwrap_or(Value::Undefined);
6304            object.define_data("value", value);
6305            object.define_data("writable", Value::Bool(property.writable));
6306        }
6307        object.define_data("enumerable", Value::Bool(property.enumerable));
6308        object.define_data("configurable", Value::Bool(property.configurable));
6309        Value::Object(object)
6310    }
6311
6312    // -- calling ------------------------------------------------------------
6313
6314    /// Call `callee` with `this` and `args`.
6315    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6316        let Value::Object(function) = &callee else {
6317            // `typeof x === "function"` is not enough to make `x()` legal: only a
6318            // callable object is. `null` and `undefined` need no special wording
6319            // here — their `ToString` already reads the way the reference's does.
6320            let what = format!("{} is not a function", callee.to_js_string());
6321            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6322        };
6323        // A proxy of a function is called through its `apply` trap. It has no
6324        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6325        // below, and a proxy of a non-function has nothing to forward to.
6326        if function.proxy_state().is_some() {
6327            return match self.proxy_apply(function, this, args)? {
6328                Some(result) => Ok(result),
6329                None => Err(Signal::Throw(
6330                    self.make_error("TypeError", "proxy target is not callable"),
6331                )),
6332            };
6333        }
6334        let callable = function.with(|data| match &data.kind {
6335            ObjectKind::Function(callable) => match callable {
6336                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6337                // The `Rc` is cloned out so the borrow of this object's data is released
6338                // before the closure runs: the closure may touch the same object.
6339                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6340                Callable::Bound {
6341                    target,
6342                    this,
6343                    args: leading,
6344                } => Some(NativeCall::Bound {
6345                    target: target.clone(),
6346                    this: this.clone(),
6347                    leading: leading.clone(),
6348                }),
6349                Callable::Bytecode { code, env } => {
6350                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
6351                }
6352                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6353                Callable::PromiseResolve(promise) => {
6354                    Some(NativeCall::PromiseResolve(promise.clone()))
6355                }
6356                Callable::PromiseReject(promise) => {
6357                    Some(NativeCall::PromiseReject(promise.clone()))
6358                }
6359                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6360                    state: state.clone(),
6361                }),
6362                Callable::ThenShim {
6363                    handler,
6364                    resolve,
6365                    reject,
6366                    fulfilled,
6367                } => Some(NativeCall::ThenShim {
6368                    handler: handler.clone(),
6369                    resolve: resolve.clone(),
6370                    reject: reject.clone(),
6371                    fulfilled: *fulfilled,
6372                }),
6373                Callable::AwaitResume {
6374                    coroutine,
6375                    promise,
6376                    kind,
6377                } => Some(NativeCall::AwaitResume {
6378                    coroutine: coroutine.clone(),
6379                    promise: promise.clone(),
6380                    kind: *kind,
6381                }),
6382                Callable::CombinatorSettle {
6383                    state,
6384                    index,
6385                    fulfilled,
6386                } => Some(NativeCall::CombinatorSettle {
6387                    state: state.clone(),
6388                    index: *index,
6389                    fulfilled: *fulfilled,
6390                }),
6391                Callable::FinallyShim {
6392                    callback,
6393                    fulfilled,
6394                    constructor,
6395                } => Some(NativeCall::FinallyShim {
6396                    callback: callback.clone(),
6397                    fulfilled: *fulfilled,
6398                    constructor: constructor.clone(),
6399                }),
6400                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6401                Callable::CompletedReturn {
6402                    generator,
6403                    promise,
6404                    rejected,
6405                } => Some(NativeCall::CompletedReturn {
6406                    generator: generator.clone(),
6407                    promise: promise.clone(),
6408                    rejected: *rejected,
6409                }),
6410                Callable::YieldResult {
6411                    generator,
6412                    promise,
6413                    done,
6414                } => Some(NativeCall::YieldResult {
6415                    generator: generator.clone(),
6416                    promise: promise.clone(),
6417                    done: *done,
6418                }),
6419                Callable::DisposeStep {
6420                    remaining,
6421                    promise,
6422                    error,
6423                    rejected,
6424                } => Some(NativeCall::DisposeStep {
6425                    remaining: remaining.clone(),
6426                    promise: promise.clone(),
6427                    error: error.clone(),
6428                    rejected: *rejected,
6429                }),
6430                Callable::GeneratorResume {
6431                    generator,
6432                    promise,
6433                    kind,
6434                } => Some(NativeCall::GeneratorResume {
6435                    generator: generator.clone(),
6436                    promise: promise.clone(),
6437                    kind: *kind,
6438                }),
6439                Callable::SettlePromise {
6440                    promise,
6441                    value,
6442                    rejected,
6443                } => Some(NativeCall::SettlePromise {
6444                    promise: promise.clone(),
6445                    value: value.clone(),
6446                    rejected: *rejected,
6447                }),
6448            },
6449            _ => None,
6450        });
6451        match callable {
6452            Some(NativeCall::Host(func)) => {
6453                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6454                // function by name rather than stopping at the caller.
6455                let frame_less = function
6456                    .own_property("_frame_less")
6457                    .and_then(|property| property.value)
6458                    .is_some_and(|value| value.to_boolean());
6459                let outer = if frame_less {
6460                    None
6461                } else {
6462                    self.native_frames
6463                        .push((function.clone(), self.frames.len()));
6464                    Some(self.current_native.replace(function.clone()))
6465                };
6466                let result = {
6467                    let mut body = func.borrow_mut();
6468                    body(self, this, &args)
6469                };
6470                if !frame_less {
6471                    self.native_frames.pop();
6472                    self.current_native = outer.flatten();
6473                }
6474                result
6475            }
6476            Some(NativeCall::Native(func)) => {
6477                // A function marked `_frame_less` is one the reference implements
6478                // without a call frame — `eval` is the only one so far.
6479                let frame_less = function
6480                    .own_property("_frame_less")
6481                    .and_then(|property| property.value)
6482                    .is_some_and(|value| value.to_boolean());
6483                let outer = if frame_less {
6484                    None
6485                } else {
6486                    self.native_frames
6487                        .push((function.clone(), self.frames.len()));
6488                    Some(self.current_native.replace(function.clone()))
6489                };
6490                let result = func(self, this, &args);
6491                if !frame_less {
6492                    self.native_frames.pop();
6493                    self.current_native = outer.flatten();
6494                }
6495                result
6496            }
6497            Some(NativeCall::Revoker(slots)) => {
6498                // Idempotent: revoking twice answers `undefined` again rather than
6499                // complaining, which is what the spec says and what a `finally` block
6500                // relies on.
6501                let mut state = slots.borrow_mut();
6502                state.target = None;
6503                state.handler = None;
6504                Ok(Value::Undefined)
6505            }
6506            Some(NativeCall::PromiseResolve(promise)) => {
6507                // One-shot: a second call is silently ignored, which
6508                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6509                let value = args.first().cloned().unwrap_or(Value::Undefined);
6510                self.resolve_promise_with(&promise, value)?;
6511                Ok(Value::Undefined)
6512            }
6513            Some(NativeCall::PromiseReject(promise)) => {
6514                let reason = args.first().cloned().unwrap_or(Value::Undefined);
6515                self.reject_promise(&promise, reason);
6516                Ok(Value::Undefined)
6517            }
6518            Some(NativeCall::ThenShim {
6519                handler,
6520                resolve,
6521                reject,
6522                fulfilled,
6523            }) => {
6524                // `PerformPromiseThen` with a capability: run the handler, then settle
6525                // through the capability's own pair. A throw from the handler is the
6526                // rejection, and a throw from the capability's `resolve` is not caught —
6527                // exactly the spec's `?`.
6528                let value = args.first().cloned().unwrap_or(Value::Undefined);
6529                match handler {
6530                    Some(handler) => {
6531                        match self.call_value(handler, Value::Undefined, vec![value]) {
6532                            Ok(result) => {
6533                                self.call_value(resolve, Value::Undefined, vec![result])?;
6534                            }
6535                            Err(Signal::Throw(reason)) => {
6536                                self.call_value(reject, Value::Undefined, vec![reason])?;
6537                            }
6538                            Err(signal) => return Err(signal),
6539                        }
6540                    }
6541                    None => {
6542                        let handler = if fulfilled { resolve } else { reject };
6543                        self.call_value(handler, Value::Undefined, vec![value])?;
6544                    }
6545                }
6546                Ok(Value::Undefined)
6547            }
6548            Some(NativeCall::CapabilityExecutor { state }) => {
6549                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6550                // slot holds a value yet. The test is on the *values*, not on a call count —
6551                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6552                // called-twice`'s first case does exactly that), while a second call after a
6553                // real pair is the `TypeError`.
6554                let defined = |name: &str| {
6555                    state
6556                        .own_property(name)
6557                        .and_then(|property| property.value)
6558                        .is_some_and(|value| !matches!(value, Value::Undefined))
6559                };
6560                if defined("resolve") || defined("reject") {
6561                    return Err(self.type_error("promise capability executor called twice"));
6562                }
6563                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6564                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6565                state.define_data("resolve", resolve);
6566                state.define_data("reject", reject);
6567                Ok(Value::Undefined)
6568            }
6569            Some(NativeCall::CombinatorSettle {
6570                state,
6571                index,
6572                fulfilled,
6573            }) => {
6574                let value = args.first().cloned().unwrap_or(Value::Undefined);
6575                self.settle_combinator(&state, index, fulfilled, value)?;
6576                Ok(Value::Undefined)
6577            }
6578            Some(NativeCall::AwaitResume {
6579                coroutine,
6580                promise,
6581                kind,
6582            }) => {
6583                // Resume *inline*, in the reaction that delivered the value. Deferring it
6584                // by another job inserts a tick between every `await` and its
6585                // continuation, which reorders `await` against unrelated `then` chains —
6586                // `f().then(g)` then runs before `f`'s own next statement.
6587                self.drive_async(
6588                    &coroutine,
6589                    &promise,
6590                    kind,
6591                    args.first().cloned().unwrap_or(Value::Undefined),
6592                )
6593                .map(|()| Value::Undefined)
6594            }
6595            Some(NativeCall::FinallyShim {
6596                callback,
6597                fulfilled,
6598                constructor,
6599            }) => {
6600                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6601                // that settles with the *original* outcome once the callback's result has
6602                // settled. The callback's own value is discarded — that is the whole
6603                // difference between `finally` and `then`.
6604                let original = args.first().cloned().unwrap_or(Value::Undefined);
6605                let result = match &callback {
6606                    Some(callback) => {
6607                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6608                    }
6609                    None => Value::Undefined,
6610                };
6611                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6612                // already a promise of this constructor is reused rather than rewrapped.
6613                let resolved = self.promise_resolve_for(&constructor, result)?;
6614                let Value::Object(resolved) = resolved else {
6615                    return Ok(original);
6616                };
6617                // The wait is a chained promise rather than a bare return, so a callback
6618                // that returns a slow promise really does delay the continuation.
6619                let waiting = self.new_promise();
6620                let pass = JsObject::function(
6621                    self.heap,
6622                    Some(self.realm.function_proto.clone()),
6623                    Callable::SettlePromise {
6624                        promise: waiting.clone(),
6625                        value: original,
6626                        rejected: !fulfilled,
6627                    },
6628                );
6629                let pass = Value::Object(pass);
6630                // Whichever way the callback's promise settles, the original outcome wins.
6631                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6632                Ok(Value::Object(waiting))
6633            }
6634            Some(NativeCall::DisposeStep {
6635                remaining,
6636                promise,
6637                error,
6638                rejected,
6639            }) => {
6640                let error = if rejected {
6641                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
6642                    self.merge_dispose_error(reason, error)
6643                } else {
6644                    error
6645                };
6646                self.dispose_step(&remaining, &promise, error)?;
6647                Ok(Value::Undefined)
6648            }
6649            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6650            Some(NativeCall::CompletedReturn {
6651                generator,
6652                promise,
6653                rejected,
6654            }) => {
6655                let value = args.first().cloned().unwrap_or(Value::Undefined);
6656                let outcome = if rejected {
6657                    AsyncOutcome::Error(value)
6658                } else {
6659                    AsyncOutcome::Value(self.iterator_result(value, true)?)
6660                };
6661                self.settle_async_request(&generator, &promise, outcome)?;
6662                Ok(Value::Undefined)
6663            }
6664            Some(NativeCall::YieldResult {
6665                generator,
6666                promise,
6667                done,
6668            }) => {
6669                let value = args.first().cloned().unwrap_or(Value::Undefined);
6670                let result = self.iterator_result(value, done)?;
6671                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6672                Ok(Value::Undefined)
6673            }
6674            Some(NativeCall::GeneratorResume {
6675                generator,
6676                promise,
6677                kind,
6678            }) => {
6679                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6680                // tick and reorders the generator against other chains.
6681                self.step_async_generator(
6682                    &generator,
6683                    &promise,
6684                    kind,
6685                    args.first().cloned().unwrap_or(Value::Undefined),
6686                )
6687                .map(|()| Value::Undefined)
6688            }
6689            Some(NativeCall::SettlePromise {
6690                promise,
6691                value,
6692                rejected,
6693            }) => {
6694                if rejected {
6695                    self.reject_promise(&promise, value);
6696                } else {
6697                    self.fulfill_promise(&promise, value);
6698                }
6699                Ok(Value::Undefined)
6700            }
6701            Some(NativeCall::Bound {
6702                target,
6703                this: bound_this,
6704                leading,
6705            }) => {
6706                let mut all = leading;
6707                all.extend(args);
6708                self.call_value(target, bound_this, all)
6709            }
6710            Some(NativeCall::Bytecode(code, env)) => {
6711                if code.code.kind.is_generator() {
6712                    return self.new_generator(callee, this, args);
6713                }
6714                if code.code.kind.is_async() {
6715                    // Same coroutine machinery as a generator; the difference is only in
6716                    // what the completion does — see `new_async_function`.
6717                    return self.new_async_function(callee, this, args);
6718                }
6719                self.execute(code, env, this, args, callee)
6720            }
6721            None => Err(Signal::Throw(
6722                self.make_error("TypeError", "not a function"),
6723            )),
6724        }
6725    }
6726
6727    /// Give a freshly built function its own `prototype` object.
6728    ///
6729    /// Every function that can be used with `new` carries one, and its
6730    /// `constructor` points back at the function — a reference cycle, which is
6731    /// exactly what the collector's cycle pass exists to reclaim.
6732    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6733        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6734        let constructor = Value::Object(function.clone());
6735        prototype.define(
6736            "constructor",
6737            Property::with_attributes(constructor, true, false),
6738        );
6739        let value = Value::Object(prototype);
6740        function.define("prototype", Property::prototype_of(value, true));
6741    }
6742
6743    /// The object `special_object` builds.
6744    ///
6745    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6746    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6747    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6748    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6749    /// write through `arguments` does not reach the parameter.
6750    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6751        match magic {
6752            0 | 1 => {
6753                let args = self.frame().passed().to_vec();
6754                let proto = self.realm.object_proto.clone();
6755                let object = self.new_object(Some(proto));
6756                // The marker `Object.prototype.toString` needs: an arguments object is an
6757                // ordinary object apart from reporting `[object Arguments]`, and that has
6758                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6759                // show up ahead of them in a key listing anyway — it is non-enumerable.
6760                self.internal_set(&object, "_class", self.string("Arguments"));
6761                // `length` is writable and configurable but neither enumerable nor a
6762                // plain data property: `Object.keys(arguments)` lists the indices only,
6763                // which is how `{...arguments}` copies them without the length.
6764                object.define(
6765                    "length",
6766                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
6767                );
6768                for (index, value) in args.into_iter().enumerate() {
6769                    object.define_data(&index.to_string(), value);
6770                }
6771                // An arguments object is iterable: `[...arguments]` and
6772                // `for (const a of arguments)` both work, through the *array* iterator
6773                // because the object is array-like. Without this the whole spread form
6774                // reported "not iterable".
6775                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6776                let values = self
6777                    .realm
6778                    .array_proto
6779                    .own_property("values")
6780                    .and_then(|property| property.value);
6781                if let Some(values) = values {
6782                    object.define_key(
6783                        &iterator_key,
6784                        Property::with_attributes(values, true, false),
6785                    );
6786                }
6787                Ok(Value::Object(object))
6788            }
6789            // `this.active_func`: the constructor `super()` resolves against.
6790            //
6791            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
6792            // own, so it inherits this from the function it was written in along with `this`
6793            // — and that is a lexical relationship, not a stack one: an arrow that escaped
6794            // the constructor and is called back later (`iter.return = () => super()`) has
6795            // the constructor nowhere on the stack. The compiler therefore reads it out of
6796            // a closure variable of the enclosing function, exactly as the reference does
6797            // with its `this_active_func` local.
6798            2 => Ok(self
6799                .current_callee()
6800                .map_or(Value::Undefined, Value::Object)),
6801            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6802            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6803            // its own either, so the lookup walks out to the nearest non-arrow frame for
6804            // the same reason as `this.active_func` above — without that, `super()` inside
6805            // an arrow passed `undefined` as the new target and the parent constructor was
6806            // then rejected for being invoked without `new`.
6807            3 => Ok(self
6808                .eval_new_target
6809                .clone()
6810                .unwrap_or_else(|| self.frame().new_target.clone())),
6811            // `[[HomeObject]]` of the function being run: what `super` is relative to.
6812            // An arrow has none of its own, so the lookup walks out to the enclosing
6813            // method — which is why `super` works inside an arrow inside a method.
6814            4 => Ok(self
6815                .frames
6816                .iter()
6817                .rev()
6818                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6819                .map_or(Value::Undefined, Value::Object)),
6820            // `import.meta`: the innermost module body's meta object. Outside a module
6821            // the compiler never emits this, so an empty fallback is unreachable rather
6822            // than permissive.
6823            6 => {
6824                let name = self.module_stack.last().cloned();
6825                let meta = name
6826                    .and_then(|name| self.modules.get(&name).cloned())
6827                    .and_then(|module| module.with(|r| r.import_meta.clone()));
6828                Ok(meta.map_or(Value::Undefined, Value::Object))
6829            }
6830            other => Err(Signal::Throw(self.make_error(
6831                "InternalError",
6832                &format!("special_object {other} is not implemented yet"),
6833            ))),
6834        }
6835    }
6836
6837    /// `[[HomeObject]]` of the innermost function that has one, if any.
6838    ///
6839    /// An arrow has none, so the search walks out to the enclosing method — the same
6840    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
6841    /// inside a method.
6842    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
6843        self.frames
6844            .iter()
6845            .rev()
6846            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6847    }
6848
6849    /// The dispose method a `using` declaration should snapshot, or an error.
6850    ///
6851    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
6852    /// is what makes a resource that only knows the synchronous protocol usable in both
6853    /// forms.
6854    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
6855        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
6856        if value.is_nullish() {
6857            return Ok(Value::Undefined);
6858        }
6859        let Some(object) = value.as_object() else {
6860            return Err(self.type_error("not an object"));
6861        };
6862        let mut method = if await_form {
6863            let found = self.get_property_key(
6864                object,
6865                &self.realm.well_known_key(WellKnown::AsyncDisposable),
6866            )?;
6867            match found {
6868                Some(found) if !found.is_nullish() => Some(found),
6869                _ => self
6870                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
6871            }
6872        } else {
6873            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
6874        };
6875        let Some(found) = method.take() else {
6876            return Err(self.type_error("value is not disposable"));
6877        };
6878        if found.is_nullish() {
6879            return Err(self.type_error("value is not disposable"));
6880        }
6881        let callable = found.as_object().is_some_and(|object| object.is_callable());
6882        if !callable {
6883            return Err(self.type_error("dispose method is not a function"));
6884        }
6885        Ok(found)
6886    }
6887
6888    /// Call one resource's disposer, folding a failure into `error_state`.
6889    ///
6890    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
6891    /// because a captured `using` binding lives in its reference cell and the local slot is
6892    /// stale — a closure over the resource is legal and must not change what is disposed.
6893    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
6894        let value = self.get_loc(slot);
6895        let method = self.get_loc(slot + 1);
6896        // A resource that was never initialised — its declaration threw — or that is
6897        // `null`/`undefined` has nothing to dispose.
6898        if value.is_nullish() || matches!(value, Value::Uninitialized) {
6899            return Ok(error_state);
6900        }
6901        if matches!(method, Value::Undefined | Value::Uninitialized) {
6902            return Ok(error_state);
6903        }
6904        match self.call_value(method, value, Vec::new()) {
6905            Ok(_) => Ok(error_state),
6906            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
6907            Err(other) => Err(other),
6908        }
6909    }
6910
6911    /// Combine a disposal failure with whatever was already going wrong.
6912    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
6913        if matches!(error_state, Value::Uninitialized) {
6914            return new_error;
6915        }
6916        self.new_suppressed_error(new_error, error_state)
6917    }
6918
6919    /// A `SuppressedError` instance built straight from its prototype.
6920    ///
6921    /// Not through the constructor: a script that rewrites
6922    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
6923    /// error wrapping.
6924    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
6925        let proto = self
6926            .realm
6927            .suppressed_error_proto
6928            .clone()
6929            .unwrap_or_else(|| self.realm.error_proto.clone());
6930        let object = self.new_object(Some(proto));
6931        object.define("error", Property::with_attributes(error, true, true));
6932        object.define(
6933            "suppressed",
6934            Property::with_attributes(suppressed, true, true),
6935        );
6936        object.define(
6937            "message",
6938            Property::with_attributes(self.string("SuppressedError"), true, true),
6939        );
6940        self.internal_set(&object, "_class", self.string("Error"));
6941        self.add_stack(&object);
6942        Value::Object(object)
6943    }
6944
6945    /// Call `callee`, or push its frame and let the main loop run it.
6946    ///
6947    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
6948    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
6949    /// continues, so `function f(){ return f() }` costs heap and stops at
6950    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
6951    /// is entered directly, and natives do not re-enter JavaScript in this
6952    /// milestone.
6953    ///
6954    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
6955    /// because the returning frame will.
6956    /// The elements of an array-like value, as a call argument list.
6957    ///
6958    /// `apply` accepts any array-like, not only a real array: the reference reads
6959    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
6960    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
6961        let Some(object) = value.as_object().cloned() else {
6962            if value.is_nullish() {
6963                // `f.apply(this, null)` passes no arguments at all.
6964                return Ok(Vec::new());
6965            }
6966            return Err(self.type_error("createListFromArrayLike called on non-object"));
6967        };
6968        let length = match self.get_property(&object, "length")? {
6969            Some(length) => length.to_number(),
6970            None => 0.0,
6971        };
6972        if !length.is_finite() || length <= 0.0 {
6973            return Ok(Vec::new());
6974        }
6975        let length = (length as usize).min(1_000_000);
6976        let mut args = Vec::with_capacity(length);
6977        for index in 0..length {
6978            let element = self.get_property(&object, &index.to_string())?;
6979            args.push(element.unwrap_or(Value::Undefined));
6980        }
6981        Ok(args)
6982    }
6983
6984    /// Turn a call to a generator function into a generator object.
6985    ///
6986    /// The frame is built exactly as an ordinary call would build it, then detached and
6987    /// stored in the generator before any body instruction runs — which is what makes
6988    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
6989    /// is `initial_yield`, the first instruction of every suspending body.
6990    pub fn new_generator(
6991        &mut self,
6992        function: Value,
6993        this: Value,
6994        args: Vec<Value>,
6995    ) -> JsResult<Value> {
6996        let Some(object) = function.as_object().cloned() else {
6997            return Err(self.type_error("not a generator function"));
6998        };
6999        let Some((code, env)) = bytecode_of(&object) else {
7000            return Err(self.type_error("not a generator function"));
7001        };
7002        let is_async = code.code.kind.is_async();
7003        self.push_frame(code, env, this, args, function)?;
7004        let frame = self.frames.pop().expect("push_frame just pushed it");
7005        // A fresh generator is *suspended at start*: the body has not run, so a
7006        // `return`/`throw` on it finishes without executing anything.
7007        let mut state = GeneratorState {
7008            frame: Some(frame),
7009            phase: GeneratorPhase::SuspendedStart,
7010            parked_on_await: false,
7011            parked_on_yield_star: false,
7012            requests: std::collections::VecDeque::new(),
7013            async_busy: false,
7014        };
7015        // Run to the first suspension. For a generator that is `initial_yield`, so no
7016        // body code runs; for a malformed body it would be the first `yield`.
7017        // An `async function*` answers an async generator: same coroutine, but its
7018        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7019        let proto = if is_async {
7020            self.realm
7021                .async_generator_proto
7022                .clone()
7023                .unwrap_or_else(|| self.realm.generator_proto.clone())
7024        } else {
7025            self.realm.generator_proto.clone()
7026        };
7027        let generator = self.new_object(Some(proto));
7028        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7029            Ok(_) => {}
7030            Err(error) => return Err(error),
7031        }
7032        generator.with_mut(|data| {
7033            data.kind = ObjectKind::Generator(Box::new(state));
7034        });
7035        Ok(Value::Object(generator))
7036    }
7037
7038    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7039    ///
7040    /// Returns the `{value, done}` object itself rather than the pair, because a
7041    /// `yield*` suspension already has one — the inner iterator's own result — and the
7042    /// protocol says to hand that straight through rather than nest it.
7043    /// Advance a generator and report *why* it parked.
7044    ///
7045    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7046    /// "hand this value to the caller" — but an async generator does: an `await` has to
7047    /// settle before it can answer, while a `yield` is the answer.
7048    fn resume_generator_detailed(
7049        &mut self,
7050        generator: &Gc<JsObject>,
7051        kind: ResumeKind,
7052        value: Value,
7053    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7054        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7055            ObjectKind::Generator(state) => Some(std::mem::replace(
7056                state.as_mut(),
7057                GeneratorState {
7058                    frame: None,
7059                    phase: GeneratorPhase::Executing,
7060                    parked_on_await: false,
7061                    parked_on_yield_star: false,
7062                    requests: std::collections::VecDeque::new(),
7063                    async_busy: false,
7064                },
7065            )),
7066            _ => None,
7067        }) else {
7068            return Err(self.type_error("not a generator"));
7069        };
7070        let result = self.step_generator(&mut state, kind, value);
7071        generator.with_mut(|data| {
7072            data.kind = ObjectKind::Generator(Box::new(state));
7073        });
7074        result
7075    }
7076
7077    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7078    ///
7079    /// Returns the `{value, done}` object itself rather than the pair, because a
7080    /// `yield*` suspension already has one — the inner iterator's own result — and the
7081    /// protocol says to hand that straight through rather than nest it.
7082    pub fn resume_generator(
7083        &mut self,
7084        generator: &Gc<JsObject>,
7085        kind: ResumeKind,
7086        value: Value,
7087    ) -> JsResult<Value> {
7088        let (value, done, ready, _reason) =
7089            self.resume_generator_detailed(generator, kind, value)?;
7090        if ready {
7091            return Ok(value);
7092        }
7093        self.iterator_result(value, done)
7094    }
7095
7096    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7097    ///
7098    /// The body is the same coroutine a sync generator runs; what changes is that an
7099    /// `await` inside it has to settle before the method can answer, so the step is
7100    /// driven off the job queue rather than returning inline.
7101    pub fn resume_async_generator(
7102        &mut self,
7103        generator: &Gc<JsObject>,
7104        kind: ResumeKind,
7105        value: Value,
7106    ) -> JsResult<Value> {
7107        let promise = self.new_promise();
7108        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7109        // that order, and the second value must reach the *second* `yield`.
7110        let idle = generator.with_mut(|data| match &mut data.kind {
7111            ObjectKind::Generator(state) => {
7112                state.requests.push_back(AsyncRequest {
7113                    kind,
7114                    value,
7115                    promise: promise.clone(),
7116                });
7117                !state.async_busy
7118            }
7119            _ => false,
7120        });
7121        if idle {
7122            self.next_async_request(generator)?;
7123        }
7124        Ok(Value::Object(promise))
7125    }
7126
7127    /// Serve the front queued request, if the generator is free to run one.
7128    ///
7129    /// A finished generator answers from the queue without running anything:
7130    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7131    /// first, and `throw(e)` rejects.
7132    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7133        enum Front {
7134            Idle,
7135            Run(ResumeKind, Value, Gc<JsObject>),
7136            Finished(ResumeKind, Value, Gc<JsObject>),
7137        }
7138        let front = generator.with_mut(|data| match &mut data.kind {
7139            ObjectKind::Generator(state) => {
7140                let Some(request) = state.requests.front() else {
7141                    return Front::Idle;
7142                };
7143                // Busy means a request is still in flight — awaiting inside the body, not
7144                // finished. Serving another now would interleave two requests.
7145                if state.async_busy && state.phase != GeneratorPhase::Completed {
7146                    return Front::Idle;
7147                }
7148                let kind = request.kind;
7149                let value = request.value.clone();
7150                let promise = request.promise.clone();
7151                state.async_busy = true;
7152                if state.phase == GeneratorPhase::Completed {
7153                    Front::Finished(kind, value, promise)
7154                } else {
7155                    Front::Run(kind, value, promise)
7156                }
7157            }
7158            _ => Front::Idle,
7159        });
7160        match front {
7161            Front::Idle => Ok(()),
7162            Front::Run(kind, value, promise) => {
7163                self.step_async_generator(generator, &promise, kind, value)
7164            }
7165            Front::Finished(kind, value, promise) => match kind {
7166                ResumeKind::Throw => {
7167                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7168                }
7169                ResumeKind::Next | ResumeKind::Start => {
7170                    let result = self.iterator_result(Value::Undefined, true)?;
7171                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7172                }
7173                ResumeKind::Return => {
7174                    // `js_async_generator_completed_return`: the value is awaited before it
7175                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7176                    // finished generator answers `1`, not a promise.
7177                    let resolved = match self.promise_resolve_value(value) {
7178                        Ok(resolved) => resolved,
7179                        Err(Signal::Throw(reason)) => {
7180                            return self.settle_async_request(
7181                                generator,
7182                                &promise,
7183                                AsyncOutcome::Error(reason),
7184                            );
7185                        }
7186                        Err(other) => return Err(other),
7187                    };
7188                    let done = JsObject::function(
7189                        self.heap,
7190                        Some(self.realm.function_proto.clone()),
7191                        Callable::CompletedReturn {
7192                            generator: generator.clone(),
7193                            promise: promise.clone(),
7194                            rejected: false,
7195                        },
7196                    );
7197                    let failed = JsObject::function(
7198                        self.heap,
7199                        Some(self.realm.function_proto.clone()),
7200                        Callable::CompletedReturn {
7201                            generator: generator.clone(),
7202                            promise: promise.clone(),
7203                            rejected: true,
7204                        },
7205                    );
7206                    let Value::Object(resolved) = resolved else {
7207                        return self.settle_async_request(
7208                            generator,
7209                            &promise,
7210                            AsyncOutcome::Error(Value::Undefined),
7211                        );
7212                    };
7213                    self.perform_then(
7214                        &resolved,
7215                        Some(Value::Object(done)),
7216                        Some(Value::Object(failed)),
7217                    )?;
7218                    Ok(())
7219                }
7220            },
7221        }
7222    }
7223
7224    /// Settle the front request and start the next one.
7225    ///
7226    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7227    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7228    /// generator would strand every later request.
7229    fn settle_async_request(
7230        &mut self,
7231        generator: &Gc<JsObject>,
7232        promise: &Gc<JsObject>,
7233        outcome: AsyncOutcome,
7234    ) -> JsResult<()> {
7235        let settled = generator.with_mut(|data| match &mut data.kind {
7236            ObjectKind::Generator(state) => {
7237                let front = state.requests.front();
7238                debug_assert!(
7239                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7240                    "a request settled outside its turn"
7241                );
7242                state.requests.pop_front();
7243                state.async_busy = false;
7244                true
7245            }
7246            _ => false,
7247        });
7248        if settled {
7249            match outcome {
7250                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7251                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7252            }
7253        }
7254        self.next_async_request(generator)
7255    }
7256
7257    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7258    ///
7259    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7260    /// disposer runs **synchronously** — the reference starts it before returning, which
7261    /// a test can observe by logging after the call — and the rest follow once their
7262    /// predecessor settles.
7263    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7264        let promise = self.new_promise();
7265        let mut pairs = Vec::with_capacity(resources.len());
7266        for (value, method) in resources {
7267            let pair = self.new_array(vec![value, method]);
7268            pairs.push(Value::Object(pair));
7269        }
7270        let remaining = self.new_array(pairs);
7271        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7272        Ok(Value::Object(promise))
7273    }
7274
7275    /// One link of the `disposeAsync` chain.
7276    ///
7277    /// Loops while the disposers finish synchronously, and parks on the first thenable it
7278    /// meets — pushing itself back in as the continuation, with the accumulated error
7279    /// carried along so a later failure can still be folded into the `SuppressedError`.
7280    fn dispose_step(
7281        &mut self,
7282        remaining: &Gc<JsObject>,
7283        promise: &Gc<JsObject>,
7284        mut error: Value,
7285    ) -> JsResult<()> {
7286        loop {
7287            let length = remaining.array_length().unwrap_or(0);
7288            if length == 0 {
7289                if matches!(error, Value::Uninitialized) {
7290                    self.fulfill_promise(promise, Value::Undefined);
7291                } else {
7292                    self.reject_promise(promise, error);
7293                }
7294                return Ok(());
7295            }
7296            let Some(Value::Object(pair)) = remaining
7297                .array_get(length - 1)
7298                .filter(|v| !matches!(v, Value::Hole))
7299            else {
7300                remaining.array_truncate(self.heap, length - 1);
7301                continue;
7302            };
7303            remaining.array_truncate(self.heap, length - 1);
7304            let value = pair.array_get(0).unwrap_or(Value::Undefined);
7305            let Some(Value::Object(method)) = pair.array_get(1) else {
7306                continue;
7307            };
7308            if !method.is_callable() {
7309                continue;
7310            }
7311            match self.call_value(Value::Object(method), value, Vec::new()) {
7312                Ok(result) => {
7313                    if !self.is_thenable(&result)? {
7314                        // Finished synchronously; the next disposer is the next iteration.
7315                        continue;
7316                    }
7317                    let awaited = match self.promise_resolve_value(result) {
7318                        Ok(awaited) => awaited,
7319                        Err(Signal::Throw(reason)) => {
7320                            self.reject_promise(promise, reason);
7321                            return Ok(());
7322                        }
7323                        Err(other) => return Err(other),
7324                    };
7325                    let Value::Object(awaited) = awaited else {
7326                        continue;
7327                    };
7328                    let ok = JsObject::function(
7329                        self.heap,
7330                        Some(self.realm.function_proto.clone()),
7331                        Callable::DisposeStep {
7332                            remaining: remaining.clone(),
7333                            promise: promise.clone(),
7334                            error: error.clone(),
7335                            rejected: false,
7336                        },
7337                    );
7338                    let failed = JsObject::function(
7339                        self.heap,
7340                        Some(self.realm.function_proto.clone()),
7341                        Callable::DisposeStep {
7342                            remaining: remaining.clone(),
7343                            promise: promise.clone(),
7344                            error,
7345                            rejected: true,
7346                        },
7347                    );
7348                    self.perform_then(
7349                        &awaited,
7350                        Some(Value::Object(ok)),
7351                        Some(Value::Object(failed)),
7352                    )?;
7353                    return Ok(());
7354                }
7355                Err(Signal::Throw(thrown)) => {
7356                    error = self.merge_dispose_error(thrown, error);
7357                }
7358                Err(other) => return Err(other),
7359            }
7360        }
7361    }
7362
7363    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7364    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7365        let Value::Object(object) = value else {
7366            return Ok(false);
7367        };
7368        Ok(matches!(
7369            self.get_property(object, "then")?,
7370            Some(Value::Object(then)) if then.is_callable()
7371        ))
7372    }
7373
7374    /// One step of an async generator, settling `promise` with an `{value, done}` result.
7375    fn step_async_generator(
7376        &mut self,
7377        generator: &Gc<JsObject>,
7378        promise: &Gc<JsObject>,
7379        kind: ResumeKind,
7380        value: Value,
7381    ) -> JsResult<()> {
7382        let stepped = self.resume_generator_detailed(generator, kind, value);
7383        let (value, done, ready, reason) = match stepped {
7384            Ok(stepped) => stepped,
7385            Err(Signal::Throw(reason)) => {
7386                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7387            }
7388            Err(other) => return Err(other),
7389        };
7390        // Only an `await` has to wait before the method can answer.
7391        if !done && reason == Some(SuspendKind::Await) {
7392            let awaited = match self.promise_resolve_value(value) {
7393                Ok(awaited) => awaited,
7394                Err(Signal::Throw(reason)) => {
7395                    return self.settle_async_request(
7396                        generator,
7397                        promise,
7398                        AsyncOutcome::Error(reason),
7399                    );
7400                }
7401                Err(other) => return Err(other),
7402            };
7403            let Value::Object(awaited) = awaited else {
7404                return Ok(());
7405            };
7406            let resumed = JsObject::function(
7407                self.heap,
7408                Some(self.realm.function_proto.clone()),
7409                Callable::GeneratorResume {
7410                    generator: generator.clone(),
7411                    promise: promise.clone(),
7412                    kind: ResumeKind::Next,
7413                },
7414            );
7415            let raised = JsObject::function(
7416                self.heap,
7417                Some(self.realm.function_proto.clone()),
7418                Callable::GeneratorResume {
7419                    generator: generator.clone(),
7420                    promise: promise.clone(),
7421                    kind: ResumeKind::Throw,
7422                },
7423            );
7424            self.perform_then(
7425                &awaited,
7426                Some(Value::Object(resumed)),
7427                Some(Value::Object(raised)),
7428            )?;
7429            return Ok(());
7430        }
7431        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7432        // completes it — both arrive as the settled value rather than as the promise
7433        // object. A plain value skips the round trip, which is also what keeps `yield 1`
7434        // from costing an extra tick.
7435        let awaits_value = self.is_thenable(&value)?;
7436        if awaits_value {
7437            let awaited = match self.promise_resolve_value(value) {
7438                Ok(awaited) => awaited,
7439                Err(Signal::Throw(reason)) => {
7440                    return self.settle_async_request(
7441                        generator,
7442                        promise,
7443                        AsyncOutcome::Error(reason),
7444                    );
7445                }
7446                Err(other) => return Err(other),
7447            };
7448            let Value::Object(awaited) = awaited else {
7449                return Ok(());
7450            };
7451            // A rejected yield throws *at the yield* inside the body, so the rejection
7452            // resumes the generator rather than the method's promise.
7453            let answer = JsObject::function(
7454                self.heap,
7455                Some(self.realm.function_proto.clone()),
7456                Callable::YieldResult {
7457                    generator: generator.clone(),
7458                    promise: promise.clone(),
7459                    done,
7460                },
7461            );
7462            let raise = JsObject::function(
7463                self.heap,
7464                Some(self.realm.function_proto.clone()),
7465                Callable::GeneratorResume {
7466                    generator: generator.clone(),
7467                    promise: promise.clone(),
7468                    kind: ResumeKind::Throw,
7469                },
7470            );
7471            self.perform_then(
7472                &awaited,
7473                Some(Value::Object(answer)),
7474                Some(Value::Object(raise)),
7475            )?;
7476            return Ok(());
7477        }
7478        let result = if ready {
7479            // `yield*` handed back the inner iterator's own result object.
7480            value
7481        } else {
7482            self.iterator_result(value, done)?
7483        };
7484        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7485    }
7486
7487    /// The `{value, done}` object an iterator method answers with.
7488    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7489        let result = self.new_object(Some(self.realm.object_proto.clone()));
7490        result.define_data("value", value);
7491        result.define_data("done", Value::Bool(done));
7492        Ok(Value::Object(result))
7493    }
7494
7495    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7496    fn step_generator(
7497        &mut self,
7498        state: &mut GeneratorState,
7499        kind: ResumeKind,
7500        value: Value,
7501    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7502        match state.phase {
7503            GeneratorPhase::Executing => {
7504                return Err(self.type_error("cannot invoke a running generator"));
7505            }
7506            GeneratorPhase::Completed => {
7507                // A finished generator answers every resumption without running.
7508                return Ok(match kind {
7509                    ResumeKind::Throw => return Err(Signal::Throw(value)),
7510                    ResumeKind::Return => (value, true, false, None),
7511                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7512                });
7513            }
7514            GeneratorPhase::SuspendedStart => {
7515                if kind != ResumeKind::Next && kind != ResumeKind::Start {
7516                    // The body never started, so there is nothing to unwind or return
7517                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7518                    state.frame = None;
7519                    state.phase = GeneratorPhase::Completed;
7520                    return Ok(match kind {
7521                        ResumeKind::Throw => return Err(Signal::Throw(value)),
7522                        _ => (value, true, false, None),
7523                    });
7524                }
7525            }
7526            GeneratorPhase::SuspendedYield => {}
7527        }
7528
7529        let Some(mut frame) = state.frame.take() else {
7530            return Ok((Value::Undefined, true, false, None));
7531        };
7532        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7533        // number that says which method resumed it; the emitted `if_false` branches on
7534        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7535        let mut raised = None;
7536        match kind {
7537            ResumeKind::Next | ResumeKind::Start => {
7538                if state.phase == GeneratorPhase::SuspendedYield {
7539                    frame.stack.push(value);
7540                    // An `await` resumes with its value alone; only a `yield` gets the
7541                    // magic number that says which of `next`/`return` resumed it.
7542                    if !state.parked_on_await {
7543                        frame.stack.push(Value::Int(RESUME_NEXT));
7544                    }
7545                }
7546            }
7547            ResumeKind::Return => {
7548                // A `return` on a not-yet-started generator is handled above, so this is
7549                // always a real resumption.
7550                frame.stack.push(value);
7551                frame.stack.push(Value::Int(RESUME_RETURN));
7552            }
7553            ResumeKind::Throw => {
7554                // At a `yield*` the exception is *data* for the delegation: the compiled
7555                // code resumes with the value and magic `2` and calls the inner iterator's
7556                // `throw`. Everywhere else it is raised at the suspension point, so the
7557                // body's own handler sees it.
7558                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7559                    frame.stack.push(value);
7560                    frame.stack.push(Value::Int(RESUME_THROW));
7561                } else {
7562                    raised = Some(value);
7563                }
7564            }
7565        }
7566        state.phase = GeneratorPhase::Executing;
7567
7568        let depth = self.frames.len();
7569        self.frames.push(frame);
7570        // A `throw` unwinds from where the frame parked, exactly as if the exception had
7571        // happened at the `yield`.
7572        if let Some(exception) = raised {
7573            if self.catch_here(exception.clone()).is_none() {
7574                self.pop_frame();
7575                state.phase = GeneratorPhase::Completed;
7576                return Err(Signal::Throw(exception));
7577            }
7578        }
7579
7580        // Only the generator's *own* frame ends the generator. The body may call ordinary
7581        // functions, and those push frames of their own: a `Step::Return` from one of them
7582        // is a nested call finishing, not the generator completing. Miscounting that is
7583        // silent — the generator reports the callee's value as its own result and marks
7584        // itself done — so the depth comparison is load-bearing, not defensive.
7585        let own_frame = depth + 1;
7586        loop {
7587            match self.step() {
7588                Ok(Step::Continue) => {}
7589                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7590                    let mut frame = self.frames.pop().expect("a frame is live");
7591                    // `yield` left the value on the stack; `initial_yield` left nothing.
7592                    let yielded = if reason == SuspendKind::Initial {
7593                        Value::Undefined
7594                    } else {
7595                        frame.stack.pop().unwrap_or(Value::Undefined)
7596                    };
7597                    state.frame = Some(frame);
7598                    state.parked_on_await = reason == SuspendKind::Await;
7599                    state.parked_on_yield_star =
7600                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7601                    state.phase = if reason == SuspendKind::Initial {
7602                        GeneratorPhase::SuspendedStart
7603                    } else {
7604                        GeneratorPhase::SuspendedYield
7605                    };
7606                    // `yield*` hands the inner iterator's own result object straight
7607                    // back, so the caller sees one `{value, done}` rather than a nested
7608                    // one — which is why the third field says "already a result".
7609                    return Ok((
7610                        yielded,
7611                        false,
7612                        reason == SuspendKind::YieldStar,
7613                        Some(reason),
7614                    ));
7615                }
7616                Ok(Step::Suspend(_)) => {
7617                    // A `yield` in a frame other than the generator's would mean a
7618                    // generator body entered as an ordinary call, which
7619                    // `call_or_push` prevents.
7620                    self.unwind_to(depth);
7621                    state.phase = GeneratorPhase::Completed;
7622                    return Err(Signal::Throw(self.make_error(
7623                        "InternalError",
7624                        "a generator body ran as an ordinary call",
7625                    )));
7626                }
7627                Ok(Step::Return(value)) => {
7628                    self.pop_frame();
7629                    if self.frames.len() > depth {
7630                        // A nested call finished: hand the value back to its caller and
7631                        // keep running the generator body.
7632                        self.frames
7633                            .last_mut()
7634                            .expect("a caller is live")
7635                            .stack
7636                            .push(value);
7637                        continue;
7638                    }
7639                    state.phase = GeneratorPhase::Completed;
7640                    // The reference closes the generator's closure variables here; ours
7641                    // live in cells the frame owned, which the drop below releases.
7642                    return Ok((value, true, false, None));
7643                }
7644                Err(Signal::Throw(exception)) => {
7645                    // The frame that threw gets the first chance to catch, exactly as in
7646                    // the ordinary call loop; a frame above the generator's is popped and
7647                    // the exception carries on down.
7648                    let exception = exception;
7649                    loop {
7650                        if self.frames.len() <= depth {
7651                            // The generator's own frame is gone, so nothing here caught it.
7652                            state.phase = GeneratorPhase::Completed;
7653                            return Err(Signal::Throw(exception));
7654                        }
7655                        if self.catch_here(exception.clone()).is_some() {
7656                            break;
7657                        }
7658                        self.pop_frame();
7659                    }
7660                }
7661                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7662            }
7663        }
7664    }
7665
7666    /// Pop frames until `depth` are left, keeping their buffers.
7667    fn unwind_to(&mut self, depth: usize) {
7668        while self.frames.len() > depth {
7669            self.pop_frame();
7670        }
7671    }
7672    fn call_or_push(
7673        &mut self,
7674        callee: Value,
7675        this: Value,
7676        args: Vec<Value>,
7677    ) -> JsResult<Option<Value>> {
7678        if let Value::Object(function) = &callee
7679            && let Some((code, env)) = bytecode_of(function)
7680        {
7681            // Calling a generator function does not run anything: it captures the
7682            // arguments in a frame and hands back the generator object.
7683            if code.code.kind.is_generator() {
7684                return self.new_generator(callee, this, args).map(Some);
7685            }
7686            // An async function answers a promise and runs its body as a coroutine, so it
7687            // takes the same path as a plain call into it.
7688            if code.code.kind.is_async() {
7689                return self.new_async_function(callee, this, args).map(Some);
7690            }
7691            self.push_frame(code, env, this, args, callee)?;
7692            return Ok(None);
7693        }
7694        self.call_value(callee, this, args).map(Some)
7695    }
7696
7697    /// `new callee(args)`.
7698    ///
7699    /// A constructor differs from a plain call in three ways: it gets a fresh object
7700    /// as `this` whose prototype is the constructor's `prototype` property, its
7701    /// return value is *replaced* by that object unless it returns an object itself,
7702    /// and a native constructor is expected to initialise the object it is given
7703    /// rather than build one.
7704    pub fn construct(
7705        &mut self,
7706        callee: Value,
7707        new_target: Value,
7708        args: Vec<Value>,
7709    ) -> JsResult<Value> {
7710        // `new` on a bound function constructs its *target*, prepending the arguments
7711        // the bind fixed and ignoring the bound `this` — a bound function is a
7712        // constructor only when its target is one, and `new` always makes a fresh
7713        // object of the target's prototype rather than reusing the bound receiver.
7714        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7715        // ran the body with `this === null` and threw on `this.x = a`.
7716        let mut callee = callee;
7717        let mut new_target = new_target;
7718        let mut args = args;
7719        loop {
7720            let Some(object) = callee.as_object().cloned() else {
7721                return Err(Signal::Throw(
7722                    self.make_error("TypeError", "not a constructor"),
7723                ));
7724            };
7725            // A proxy of a function constructs through its `construct` trap, and the
7726            // trap's answer is the result directly — no fresh object is made here.
7727            if object.proxy_state().is_some() {
7728                return match self.proxy_construct(&object, args, &new_target)? {
7729                    Some(result) => Ok(result),
7730                    None => Err(Signal::Throw(
7731                        self.make_error("TypeError", "proxy target is not a constructor"),
7732                    )),
7733                };
7734            }
7735            // A generator function has no `[[Construct]]`, and the reference names it in
7736            // the message: `new (function* G(){})()` reports "G is not a constructor".
7737            if object.with(|data| match &data.kind {
7738                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7739                    code.code.kind.is_generator()
7740                }
7741                _ => false,
7742            }) {
7743                let name = object
7744                    .own_property("name")
7745                    .and_then(|property| property.value)
7746                    .map(|value| value.to_js_string())
7747                    .unwrap_or_default();
7748                return Err(Signal::Throw(
7749                    self.make_error("TypeError", &format!("{name} is not a constructor")),
7750                ));
7751            }
7752            let bound = object.with(|data| match &data.kind {
7753                ObjectKind::Function(Callable::Bound {
7754                    target,
7755                    args: leading,
7756                    ..
7757                }) => Some((target.clone(), leading.clone())),
7758                _ => None,
7759            });
7760            let Some((target, leading)) = bound else {
7761                // Not a bound function, so this object is the callee. §7.2.4
7762                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7763                // refusals above cover only the built-ins the reference also refuses by
7764                // name. Everything else — a method, an arrow, an async function — has no
7765                // `[[Construct]]` either, and answering "yes" here made
7766                // `new (Array.prototype.map)` build an object instead of throwing.
7767                if !object.is_constructor() {
7768                    let name = object
7769                        .own_property("name")
7770                        .and_then(|property| property.value)
7771                        .map(|value| value.to_js_string())
7772                        .unwrap_or_default();
7773                    return Err(Signal::Throw(
7774                        self.make_error("TypeError", &format!("{name} is not a constructor")),
7775                    ));
7776                }
7777                break;
7778            };
7779            let mut all = leading;
7780            all.extend(args);
7781            args = all;
7782            // A bound function that is its own `new.target` stands in for its target:
7783            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
7784            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
7785            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
7786                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
7787                _ => false,
7788            };
7789            if same_wrapper {
7790                new_target = target.clone();
7791            }
7792            callee = target;
7793        }
7794        let Value::Object(function) = &callee else {
7795            unreachable!("the loop above only breaks on an object");
7796        };
7797        // The fresh object's prototype comes from `new.target`, not from the callee: a
7798        // derived constructor reaches here through `super()`, and the instance must be a
7799        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7800        // an object inheriting `D.prototype` rather than `C.prototype`.
7801        let prototype_source = match new_target.as_object() {
7802            Some(target) => target.clone(),
7803            None => function.clone(),
7804        };
7805        // A native constructor builds its own instance, through `new_ctor_instance`, once it
7806        // has validated its arguments. Pre-building one here would read
7807        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7808        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7809        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7810        let is_native = function.native_creates_own_instance();
7811        let this = if is_native {
7812            Value::Undefined
7813        } else {
7814            let prototype = self.get_property(&prototype_source, "prototype")?;
7815            let prototype = match prototype {
7816                Some(Value::Object(proto)) => Some(proto),
7817                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7818                // object, the answer is the realm's *intrinsic* prototype for this
7819                // constructor, not `%Object.prototype%`.
7820                _ => {
7821                    let fallback = self.get_property(function, "prototype")?;
7822                    match fallback {
7823                        Some(Value::Object(proto)) => Some(proto),
7824                        _ => Some(self.realm.object_proto.clone()),
7825                    }
7826                }
7827            };
7828            Value::Object(self.new_object(prototype))
7829        };
7830        // `new.target` inside the body is the constructor that was written, so a bound
7831        // function's target sees itself rather than the bound wrapper.
7832        //
7833        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7834        // `?`, so assigning `None` after the call would be skipped and the failed
7835        // `new.target` would stay visible to every later native call. The symptom was a
7836        // native constructor refusing a plain call — `var s = Symbol(); new
7837        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
7838        // "FinalizationRegistry is not a constructor".
7839        let outer_new_target = self.pending_new_target.replace(new_target);
7840        let result = self.call_value(callee, this.clone(), args);
7841        self.pending_new_target = outer_new_target;
7842        let result = result?;
7843        // A constructor that returns an object overrides `this`; any other return
7844        // value (including `undefined`) is ignored.
7845        Ok(match result {
7846            Value::Object(_) => result,
7847            _ => this,
7848        })
7849    }
7850
7851    /// `new.target` for the call currently being made.
7852    ///
7853    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
7854    /// it as `this`), but a *host* constructor that builds its own instance is handed
7855    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
7856    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
7857    /// it here.
7858    ///
7859    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
7860    /// receives for a plain call.
7861    pub fn current_new_target(&self) -> Value {
7862        self.pending_new_target.clone().unwrap_or(Value::Undefined)
7863    }
7864
7865    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
7866    ///
7867    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
7868    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
7869    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
7870        let constructor = self.realm.errors.get("AggregateError").cloned();
7871        let Some(constructor) = constructor else {
7872            return self.make_error("AggregateError", message);
7873        };
7874        let list = self.new_array(errors);
7875        match self.construct(
7876            Value::Object(constructor.clone()),
7877            Value::Object(constructor),
7878            vec![Value::Object(list), self.string(message)],
7879        ) {
7880            Ok(value) => value,
7881            // A user could have replaced `AggregateError` with something that throws; the
7882            // engine still owes the caller a rejection, so it falls back rather than
7883            // turning `Promise.any`'s rejection into a throw.
7884            Err(_) => self.make_error("AggregateError", message),
7885        }
7886    }
7887
7888    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
7889    ///
7890    /// The error classes themselves arrive with the builtins milestone; what
7891    /// matters here is that the thrown value stringifies the way a script printing
7892    /// the caught value expects.
7893    ///
7894    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
7895    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
7896    /// rely on when they print a caught value.
7897    pub fn make_error(&self, name: &str, message: &str) -> Value {
7898        let proto = self
7899            .realm
7900            .errors
7901            .get(name)
7902            .map(|constructor| self.prototype_of(constructor))
7903            .unwrap_or_else(|| self.realm.error_proto.clone());
7904        let error = self.new_object(Some(proto));
7905        // `name` and `message` are own properties of the instance, which is what
7906        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
7907        // `Error`.
7908        error.define(
7909            "name",
7910            Property::with_attributes(self.string(name), true, false),
7911        );
7912        error.define(
7913            "message",
7914            Property::with_attributes(self.string(message), true, false),
7915        );
7916        // The internal class, which is what tells a printer this is an error rather than a
7917        // plain object with `name` and `message` properties. The constructor path sets it
7918        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
7919        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
7920        // literally `"Error"` in both places — the *name* is read from `name`, which is why
7921        // a `RangeError` still prints as `RangeError`.
7922        self.internal_set(&error, "_class", self.string("Error"));
7923        // The trace is captured where the error is *made*, which is where the reference
7924        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
7925        // way out, so a caught engine error already has its stack even if the handler
7926        // never rethrows it.
7927        self.add_stack(&error);
7928        Value::Object(error)
7929    }
7930
7931    /// Give an error object its `stack` property, from the current frame stack.
7932    ///
7933    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
7934    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
7935    /// `stack` a script set, is not rewritten.
7936    pub fn add_stack(&self, object: &Gc<JsObject>) {
7937        self.add_stack_skipping(object, 0);
7938    }
7939
7940    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
7941    ///
7942    /// An `Error` constructor passes 1: the reference builds those traces with
7943    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
7944    /// constructor itself, while a `RangeError` raised inside `toISOString` does
7945    /// report `at toISOString (native)`.
7946    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
7947        if object.has_own("stack") {
7948            return;
7949        }
7950        let trace = self.stack_trace_skipping(skip);
7951        let text = self.string(trace);
7952        object.define("stack", Property::with_attributes(text, true, true));
7953    }
7954
7955    /// The function object currently being called, if any.
7956    ///
7957    /// A native function is a bare `fn` pointer, so it cannot capture which class
7958    /// it belongs to; it reads that from the callee instead. This is also what a
7959    /// stack trace would use.
7960    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
7961        match &self.frames.last()?.callee {
7962            Value::Object(object) => Some(object.clone()),
7963            _ => None,
7964        }
7965    }
7966
7967    /// The `prototype` property of a constructor, falling back to
7968    /// `Object.prototype` for anything that is not shaped like one.
7969    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
7970        constructor
7971            .own_property("prototype")
7972            .and_then(|property| property.value)
7973            .and_then(|value| value.as_object().cloned())
7974            .unwrap_or_else(|| self.realm.object_proto.clone())
7975    }
7976
7977    /// Throw a `TypeError` carrying `message`.
7978    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
7979        Signal::Throw(self.make_error("TypeError", message.as_ref()))
7980    }
7981
7982    /// Throw a `RangeError` carrying `message`.
7983    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
7984        Signal::Throw(self.make_error("RangeError", message.as_ref()))
7985    }
7986
7987    /// The `ReferenceError` a read of an uninitialised binding raises.
7988    /// The name of the binding `slot` refers to, for an error message.
7989    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
7990        match kind {
7991            VarSlot::Loc => self
7992                .frame()
7993                .code
7994                .code
7995                .vars
7996                .get(slot)
7997                .map(|v| v.name.clone()),
7998            VarSlot::Closure => self
7999                .frame()
8000                .code
8001                .code
8002                .closure_vars
8003                .get(slot)
8004                .map(|c| c.name.clone()),
8005        }
8006        .unwrap_or_default()
8007    }
8008
8009    /// Whether `slot` names a `const` binding, which rejects every store after its
8010    /// initialiser.
8011    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8012        match kind {
8013            VarSlot::Loc => self
8014                .frame()
8015                .code
8016                .code
8017                .vars
8018                .get(slot)
8019                .is_some_and(|v| v.is_const),
8020            VarSlot::Closure => self
8021                .frame()
8022                .code
8023                .code
8024                .closure_vars
8025                .get(slot)
8026                .is_some_and(|c| c.is_const),
8027        }
8028    }
8029
8030    /// The `TypeError` a store to a `const` binding raises.
8031    ///
8032    /// `const` is enforced here rather than at compile time because the binding can be
8033    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8034    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8035    /// both halves of what "checked store" means: the dead zone is over, and the
8036    /// binding is writable.
8037    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8038        let name = self.binding_name(slot, kind);
8039        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8040    }
8041
8042    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8043        let name = match kind {
8044            VarSlot::Loc => self
8045                .frame()
8046                .code
8047                .code
8048                .vars
8049                .get(slot)
8050                .map(|v| v.name.clone()),
8051            VarSlot::Closure => self
8052                .frame()
8053                .code
8054                .code
8055                .closure_vars
8056                .get(slot)
8057                .map(|c| c.name.clone()),
8058        }
8059        .unwrap_or_default();
8060        Signal::Throw(self.make_error(
8061            "ReferenceError",
8062            &format!("cannot access '{name}' before initialization"),
8063        ))
8064    }
8065
8066    fn throw_reference(&self, name: &str) -> Signal {
8067        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8068    }
8069
8070    // -- the instruction loop -----------------------------------------------
8071
8072    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8073    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8074    // measured at 16% of a tight arithmetic loop's total time.
8075    #[inline(always)]
8076    fn step(&mut self) -> JsResult<Step> {
8077        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8078        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8079        // borrow lives across the boundary; nothing is cloned.
8080        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8081        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8082        // write, and once more inside the handler), and each is a bounds check plus an
8083        // `Option` unwrap — on the one path every instruction takes.
8084        let Some((insn, next)) = ({
8085            let frame = self
8086                .frames
8087                .last_mut()
8088                .expect("step() is only called with a live frame");
8089            // Past the last instruction is a normal return: the compiler ends a function
8090            // with `return`, and a jump to the end of a block lands here.
8091            let insn = frame.insns().get(frame.pc).copied();
8092            match insn {
8093                None => None,
8094                Some(insn) => {
8095                    // A fused record stands for the next few instructions, so the next
8096                    // `pc` is its width ahead — the instructions it replaces are never
8097                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8098                    // an offset because the line table is keyed by bytes.
8099                    frame.at = insn.offset as usize;
8100                    frame.pc += insn.width();
8101                    Some((insn, frame.pc))
8102                }
8103            }
8104        }) else {
8105            return Ok(Step::Return(Value::Undefined));
8106        };
8107        self.check_memory()?;
8108        self.check_interrupt()?;
8109        if insn.fused == crate::insn::Fused::None {
8110            self.execute_instruction(insn.op, insn.a, insn.b, next)
8111        } else {
8112            self.execute_fused(insn)
8113        }
8114    }
8115
8116    /// Run a fused instruction: several bytecode instructions in one dispatch.
8117    ///
8118    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8119    /// it cannot throw and cannot allocate — and anything else falls back to the real
8120    /// instructions, in their real order, so an exception leaves the operand stack
8121    /// exactly as it would have been.
8122    #[inline]
8123    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8124        use crate::insn::Fused;
8125        let slot = insn.a as usize;
8126        match insn.fused {
8127            // `x = k`: `push k; put_loc x`.
8128            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8129            // `x += k`: `get_loc x; push k; add; put_loc x`.
8130            Fused::AddImmLoc => {
8131                let delta = insn.b as i32;
8132                match self.get_loc(slot) {
8133                    Value::Int(left) => {
8134                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8135                        // that built two `Value`s, called a function, and matched on them
8136                        // again to reach this same `checked_add`. It is the innermost
8137                        // operation of every accumulator in every program.
8138                        let answer = match left.checked_add(delta) {
8139                            Some(sum) => Value::Int(sum),
8140                            None => Value::Float(left as f64 + delta as f64),
8141                        };
8142                        self.put_loc(slot, answer);
8143                    }
8144                    other => {
8145                        self.push(other);
8146                        self.push(Value::Int(delta));
8147                        self.binary_add()?;
8148                        let value = self.pop();
8149                        self.put_loc(slot, value);
8150                    }
8151                }
8152            }
8153            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8154            Fused::AddAtomLoc => {
8155                let text = self.atom_wtf8(insn.b as usize);
8156                let right = self.string_wtf8(text);
8157                self.add_into_loc(slot, right)?;
8158            }
8159            Fused::AddLocLoc => {
8160                let source = (insn.a & 0xFFFF) as usize;
8161                let target = (insn.a >> 16) as usize;
8162                let right = self.get_loc(source);
8163                self.add_into_loc(target, right)?;
8164            }
8165            Fused::AddArgLoc => {
8166                let source = (insn.a & 0xFFFF) as usize;
8167                let target = (insn.a >> 16) as usize;
8168                let right = self.get_arg(source);
8169                self.add_into_loc(target, right)?;
8170            }
8171            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8172            Fused::PostIncLoc => match self.get_loc(slot) {
8173                Value::Int(left) => {
8174                    let answer = match left.checked_add(1) {
8175                        Some(sum) => Value::Int(sum),
8176                        None => Value::Float(left as f64 + 1.0),
8177                    };
8178                    self.put_loc(slot, answer);
8179                }
8180                other => {
8181                    self.push(other);
8182                    let raw = self.pop();
8183                    let (old, updated) = self.advance_numeric(raw, true)?;
8184                    self.push(old);
8185                    self.push(updated);
8186                    let value = self.pop();
8187                    self.put_loc(slot, value);
8188                    self.pop();
8189                }
8190            },
8191            // `if (!(x < arg)) goto target`: a loop header.
8192            //
8193            // The comparison is computed rather than replayed on the operand stack. That
8194            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8195            // that throws: the effects happen in the same order, and a handler truncates
8196            // the stack down to its marker, so the intermediate values are unobservable.
8197            Fused::LtLocArgJump => {
8198                let loc = (insn.a >> 16) as usize;
8199                let arg = (insn.a & 0xFFFF) as usize;
8200                let left = self.get_loc(loc);
8201                let right = self.get_arg(arg);
8202                let taken = match (&left, &right) {
8203                    (Value::Int(left), Value::Int(right)) => !(left < right),
8204                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8205                };
8206                if taken {
8207                    self.frame_mut().pc = insn.b as usize;
8208                }
8209            }
8210            // `i < k` in a loop header, where `k` is an integer literal.
8211            Fused::LtLocImmJump => {
8212                let left = self.get_loc(insn.a as usize);
8213                let right = Value::Int(insn.imm as i32);
8214                let taken = match &left {
8215                    Value::Int(left) => !(*left < insn.imm as i32),
8216                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8217                };
8218                if taken {
8219                    self.frame_mut().pc = insn.b as usize;
8220                }
8221            }
8222            Fused::None => unreachable!("only called for a fused record"),
8223        }
8224        Ok(Step::Continue)
8225    }
8226
8227    /// Run records that cannot call script, cannot throw and cannot change frames.
8228    ///
8229    /// Returns `Some(value)` when the function ran off the end of its instructions (a
8230    /// normal return), and `None` when it stopped in front of an instruction the slow path
8231    /// has to handle — `pc` is written back either way, so `step` resumes at the right
8232    /// place.
8233    ///
8234    /// **The invariant is the whole point.** Every arm here is restricted to work that
8235    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8236    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8237    /// that the memory limit has to see. An opcode whose operands turn out to need any of
8238    /// that **stops the loop** instead of trying, so the slow path gets the instruction
8239    /// untouched and with its operands still on the stack. That is why the fallback is a
8240    /// `break` and not a duplicated slow arm: a second implementation of the same
8241    /// semantics is how a wrong answer gets in with no test noticing.
8242    ///
8243    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8244    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8245    fn run_fast(&mut self) -> JsResult<Option<Value>> {
8246        use crate::insn::Fused;
8247        // The outer loop exists only so a `Call` can come back through here: once a
8248        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8249        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8250        // frame. Re-entering re-reads both from whichever frame is now on top. Every
8251        // other exit from the inner loop returns, so this costs one loop per call.
8252        'outer: loop {
8253            // One reference-count bump per *slow* instruction (a call, an allocation, a
8254            // property access), never one per instruction — that distinction is worth
8255            // two orders of magnitude and was measured as such.
8256            let (code, mut pc) = {
8257                let frame = self.frame();
8258                (frame.code.clone(), frame.pc)
8259            };
8260            let insns = &code.insns;
8261            loop {
8262                let Some(insn) = insns.get(pc).copied() else {
8263                    self.frame_mut().pc = pc;
8264                    return Ok(Some(Value::Undefined));
8265                };
8266                match insn.fused {
8267                    // `x = k`
8268                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8269                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8270                    // object — stops the loop so `binary_add` can decide.
8271                    Fused::AddImmLoc => {
8272                        let slot = insn.a as usize;
8273                        let delta = insn.b as i32;
8274                        let Value::Int(left) = self.get_loc(slot) else {
8275                            return Ok(self.stop(pc));
8276                        };
8277                        let sum = match left.checked_add(delta) {
8278                            Some(sum) => Value::Int(sum),
8279                            None => Value::Float(left as f64 + delta as f64),
8280                        };
8281                        self.put_loc(slot, sum);
8282                    }
8283                    // `x += "literal"` / `x += y`: the operand is a string, so the append
8284                    // either allocates one or grows one. Both are the slow path's business;
8285                    // the fusion's job is only to make the *slot* the sole owner, which is what
8286                    // `execute_fused` needs and what `get_loc` alone destroys.
8287                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8288                        return Ok(self.stop(pc));
8289                    }
8290                    // `x++` on an integer, old value dropped.
8291                    Fused::PostIncLoc => {
8292                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8293                        // value is read in place and overwritten in place, so the reference
8294                        // count it held is released by the same assignment that stores the
8295                        // new one. `get_loc` plus `put_loc` did two borrows, two table
8296                        // lookups and a clone, and this arm is the whole body of a counting
8297                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8298                        let slot = insn.a as usize;
8299                        let frame = self.frames.last_mut().expect("a frame is live");
8300                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8301                        let target = if cell < 0 {
8302                            frame.locals.get_mut(slot)
8303                        } else {
8304                            None
8305                        };
8306                        let Some(target) = target else {
8307                            return Ok(self.stop(pc));
8308                        };
8309                        let Value::Int(left) = *target else {
8310                            return Ok(self.stop(pc));
8311                        };
8312                        *target = match left.checked_add(1) {
8313                            Some(sum) => Value::Int(sum),
8314                            None => Value::Float(left as f64 + 1.0),
8315                        };
8316                    }
8317                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
8318                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8319                    // bound stayed small integers.
8320                    Fused::LtLocArgJump => {
8321                        let loc = (insn.a >> 16) as usize;
8322                        let arg = (insn.a & 0xFFFF) as usize;
8323                        // One borrow for both slots: this arm *is* the whole loop of a
8324                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
8325                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
8326                        // `dispatch:empty-loop`.
8327                        let (left, right) = {
8328                            let frame = self.frame();
8329                            (frame.read_loc(loc), frame.read_arg(arg))
8330                        };
8331                        // Heavily measured: the bound is very often a `Float` even when the
8332                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8333                        // `JSON.parse` or a division is one — so requiring both sides to be
8334                        // `Int` sent every iteration of those loops down the slow path. The
8335                        // comparison below is the same one `relational` makes for two numbers.
8336                        if !is_number(&left) || !is_number(&right) {
8337                            return Ok(self.stop(pc));
8338                        }
8339                        // `if_false` branches on the comparison being false, which is **not**
8340                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8341                        // `>=` is also false and would keep it running forever. Clippy wants the
8342                        // negation folded; that would be a wrong answer.
8343                        let ordered = left.to_number() < right.to_number();
8344                        let take_branch = !ordered;
8345                        if take_branch {
8346                            pc = insn.b as usize;
8347                            continue;
8348                        }
8349                    }
8350                    // The same header with a literal bound: `if (!(x < k)) goto target`.
8351                    // The bound is an immediate, so only the counter needs a type test.
8352                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
8353                    Fused::LtLocImmJump => {
8354                        let left = self.get_loc(insn.a as usize);
8355                        if !is_number(&left) {
8356                            return Ok(self.stop(pc));
8357                        }
8358                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8359                        if take_branch {
8360                            pc = insn.b as usize;
8361                            continue;
8362                        }
8363                    }
8364                    Fused::None => match insn.op {
8365                        // -- branches ---------------------------------------------------
8366                        // A jump is an assignment now, because the target is an instruction
8367                        // index. No arithmetic, no resolution table.
8368                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8369                            let target = insn.a as usize;
8370                            // A **back-edge** is a loop, and it is the only place an
8371                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
8372                            // to a jump to itself and never leaves this loop, so the
8373                            // per-instruction checks in `step` never run. That is exactly the
8374                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
8375                            // nothing to a `for(;;){}` until it did, which is what
8376                            // `tests/c/embed.c` is for.
8377                            //
8378                            // Polling here rather than on every instruction in this loop is
8379                            // also the reference's choice (`OP_goto` calls
8380                            // `js_poll_interrupts`), and it costs one compare per branch
8381                            // instead of one decrement per instruction.
8382                            if target <= pc {
8383                                self.frame_mut().pc = target;
8384                                self.check_memory()?;
8385                                self.check_interrupt()?;
8386                            }
8387                            pc = target;
8388                            continue;
8389                        }
8390                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8391                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8392                            let taken = self.pop().to_boolean();
8393                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8394                            if taken == want {
8395                                pc = insn.a as usize;
8396                                continue;
8397                            }
8398                        }
8399                        // -- slot access -------------------------------------------------
8400                        // A load's slot is already an operand (see `insn::implicit_operand`);
8401                        // a captured one goes through its cell, which runs no script.
8402                        Opcode::GetLoc
8403                        | Opcode::GetLoc8
8404                        | Opcode::GetLoc0
8405                        | Opcode::GetLoc1
8406                        | Opcode::GetLoc2
8407                        | Opcode::GetLoc3 => {
8408                            let value = self.get_loc(insn.a as usize);
8409                            self.push(value);
8410                        }
8411                        Opcode::PutLoc
8412                        | Opcode::PutLoc8
8413                        | Opcode::PutLoc0
8414                        | Opcode::PutLoc1
8415                        | Opcode::PutLoc2
8416                        | Opcode::PutLoc3 => {
8417                            let value = self.pop();
8418                            self.put_loc(insn.a as usize, value);
8419                        }
8420                        Opcode::GetArg
8421                        | Opcode::GetArg0
8422                        | Opcode::GetArg1
8423                        | Opcode::GetArg2
8424                        | Opcode::GetArg3 => {
8425                            let value = self.get_arg(insn.a as usize);
8426                            self.push(value);
8427                        }
8428                        Opcode::PutArg
8429                        | Opcode::PutArg0
8430                        | Opcode::PutArg1
8431                        | Opcode::PutArg2
8432                        | Opcode::PutArg3 => {
8433                            let value = self.pop();
8434                            self.put_arg(insn.a as usize, value);
8435                        }
8436                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
8437                        // for why a non-hole own element is exactly the slow path's answer.
8438                        // The two operands are *peeked*, so a miss leaves the stack as the
8439                        // slow path expects to find it.
8440                        Opcode::GetArrayEl => {
8441                            // One lookup, not two. The guard used `if …is_some()` and the arm
8442                            // then called it again to get the value — two `peek`s, two
8443                            // `array_get`s and two `Value` clones for one element.
8444                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
8445                            // double call was the first version of the `get_field` fast path.
8446                            let Some(value) = self.fast_array_get() else {
8447                                return Ok(self.stop(pc));
8448                            };
8449                            // `a[i]` consumes both operands and leaves the element in their
8450                            // place: one `truncate` and one write, no `pop`/`push` pair.
8451                            let frame = self.frame_mut();
8452                            frame.stack.truncate(frame.stack.len() - 2);
8453                            frame.stack.push(value);
8454                        }
8455                        // `a[i] = v` on a dense array with an integer index: see
8456                        // `fast_array_set` for why the whole store is one step.
8457                        Opcode::PutArrayEl if self.fast_array_set() => {}
8458                        // `o.x` resolved from the inline cache without leaving the loop.
8459                        //
8460                        // The cache is keyed by `(receiver identity, atom, site)` and a
8461                        // monomorphic read re-validates the same chain every iteration, so
8462                        // each one used to cost a `stop(pc)` — a write of `pc` into the
8463                        // frame, a return out of this loop, a re-dispatch through `step` and
8464                        // a re-entry. `property:monomorphic` spent 18% in
8465                        // `read_field_cached` and 21% in `push`, both across that boundary.
8466                        //
8467                        // The site is `pc + width`, which is exactly the `next` the slow arm
8468                        // passes — the two must agree or every fast lookup misses and
8469                        // re-records the same entry forever.
8470                        //
8471                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8472                        // slow arm finds the receiver where it expects it.
8473                        // `name` resolved from the global-variable cache inside the loop.
8474                        //
8475                        // Same shape as `get_field` above and for the same reason: `get_var`
8476                        // was not in the fast loop, so reading a global — which `fib` does
8477                        // once per recursive call, for its own name — cost a `stop(pc)`, a
8478                        // return out of the loop, a `step` re-dispatch and a re-entry, before
8479                        // `get_global` even started its `scopes_are_plain` checks.
8480                        //
8481                        // Everything here is exactly `get_global`'s first branch: not lexical,
8482                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
8483                        // and lets the slow arm decide.
8484                        Opcode::GetVar => {
8485                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8486                                return Ok(self.stop(pc));
8487                            };
8488                            self.push(value);
8489                        }
8490                        Opcode::GetField | Opcode::GetField2 => {
8491                            let Some(value) =
8492                                self.fast_field_get(insn.a as usize, pc + insn.width())
8493                            else {
8494                                return Ok(self.stop(pc));
8495                            };
8496                            if insn.op == Opcode::GetField2 {
8497                                // `get_field2` keeps the receiver for the `call_method` that
8498                                // follows.
8499                                self.push(value);
8500                            } else {
8501                                // `get_field` replaces the receiver, so this is one store over
8502                                // the top slot rather than a `pop` and a `push`: the length
8503                                // never changes, so neither `Vec` arm has a capacity check or a
8504                                // drop to run beyond the one the overwrite itself does.
8505                                let frame = self.frame_mut();
8506                                match frame.stack.last_mut() {
8507                                    Some(slot) => *slot = value,
8508                                    None => return Ok(self.stop(pc)),
8509                                }
8510                            }
8511                        }
8512                        // -- constants ---------------------------------------------------
8513                        Opcode::PushMinus1
8514                        | Opcode::Push0
8515                        | Opcode::Push1
8516                        | Opcode::Push2
8517                        | Opcode::Push3
8518                        | Opcode::Push4
8519                        | Opcode::Push5
8520                        | Opcode::Push6
8521                        | Opcode::Push7
8522                        | Opcode::PushI8
8523                        | Opcode::PushI16
8524                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8525                        // -- stack shuffling ---------------------------------------------
8526                        Opcode::Drop => {
8527                            self.pop();
8528                        }
8529                        // -- arithmetic on two integers ----------------------------------
8530                        //
8531                        // The operands are *looked at* before they are popped, so a non-integer
8532                        // pair leaves the stack exactly as the slow path expects to find it.
8533                        Opcode::Add if self.numeric_pair() => {
8534                            let right = self.pop();
8535                            let left = self.pop();
8536                            // Exactly [`add_numbers`], which is what the slow arm reaches.
8537                            let answer = match (&left, &right) {
8538                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8539                                    Some(sum) => Value::Int(sum),
8540                                    None => Value::Float(*a as f64 + *b as f64),
8541                                },
8542                                _ => Value::Float(left.to_number() + right.to_number()),
8543                            };
8544                            self.push(answer);
8545                        }
8546                        Opcode::Sub
8547                        | Opcode::And
8548                        | Opcode::Or
8549                        | Opcode::Xor
8550                        | Opcode::Shl
8551                        | Opcode::Sar
8552                        | Opcode::Shr
8553                            if self.numeric_pair() =>
8554                        {
8555                            let right = self.pop();
8556                            let left = self.pop();
8557                            let answer =
8558                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
8559                            self.push(answer);
8560                        }
8561                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8562                            if self.numeric_pair() =>
8563                        {
8564                            let right = self.pop();
8565                            let left = self.pop();
8566                            let answer = self
8567                                .relational(insn.op, left, right)
8568                                .expect("numbers cannot throw");
8569                            self.push(answer);
8570                        }
8571                        // -- calls -------------------------------------------------------
8572                        //
8573                        // A plain call: `callee(arg0, …, argN) -> result`.
8574                        //
8575                        // This arm exists because of one measurement. `call:recursion` had
8576                        // **20.4% of its profile in `execute_instruction`** — the *slow*
8577                        // executor — and `fib`'s recursive call is the only thing in that
8578                        // function which is not a fast arm. Every call therefore left this
8579                        // loop via `stop()`, went through `step()`'s dispatch and
8580                        // `execute_instruction`'s match over every opcode, and came back here
8581                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8582                        //
8583                        // Two things make it safe to do here rather than only in the slow path:
8584                        //
8585                        // * the caller's `pc` is stored *before* the call, which is what
8586                        //   `step` does too — so when the callee returns, the caller resumes
8587                        //   after the call and not at it;
8588                        // * `check_memory` runs, because `step` calls it once per instruction
8589                        //   and a call allocates a frame, its locals and its cells. Skipping
8590                        //   the checkpoint here would let a `--memory-limit` script overshoot
8591                        //   by one call per instruction.
8592                        Opcode::Call
8593                        | Opcode::Call0
8594                        | Opcode::Call1
8595                        | Opcode::Call2
8596                        | Opcode::Call3 => {
8597                            let argc = self.argc_operand(insn.op, insn.a);
8598                            let next = pc + insn.width();
8599                            {
8600                                let frame = self
8601                                    .frames
8602                                    .last_mut()
8603                                    .expect("run_fast() is only called with a live frame");
8604                                // `at` is what a stack trace reports for this frame, so a throw
8605                                // inside the callee has to see the call site and not whatever
8606                                // the last `stop()` left there.
8607                                frame.at = insn.offset as usize;
8608                                frame.pc = next;
8609                            }
8610                            self.check_memory()?;
8611                            self.check_interrupt()?;
8612                            let args = self.pop_n(argc);
8613                            let callee = self.pop();
8614                            // A plain call has no receiver; the callee decides what to do with
8615                            // `undefined` (a sloppy function substitutes the global object).
8616                            if let Some(result) =
8617                                self.call_or_push(callee, Value::Undefined, args)?
8618                            {
8619                                // Native, host, generator, async, bound — no frame was pushed,
8620                                // so this loop is still describing the right function. `pc`
8621                                // is advanced by the loop tail like every other arm; only the
8622                                // frame's copy had to be written here, and it already was.
8623                                self.push(result);
8624                            } else {
8625                                // A bytecode callee: its frame is on top now, and `insns` and
8626                                // `pc` both belong to the caller. Start over on the new frame.
8627                                continue 'outer;
8628                            }
8629                        }
8630                        // -- return ------------------------------------------------------
8631                        Opcode::Return => {
8632                            let value = self.pop();
8633                            self.frame_mut().pc = pc + insn.width();
8634                            return Ok(Some(value));
8635                        }
8636                        Opcode::ReturnUndef => {
8637                            self.frame_mut().pc = pc + insn.width();
8638                            return Ok(Some(Value::Undefined));
8639                        }
8640                        // Everything else needs the slow path.
8641                        _ => return Ok(self.stop(pc)),
8642                    },
8643                }
8644                pc += insn.width();
8645            }
8646        }
8647    }
8648
8649    /// Whether the top two operand-stack values are both numbers.
8650    ///
8651    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8652    /// cannot run script, so the arm may not throw and may not change frames.
8653    fn numeric_pair(&self) -> bool {
8654        is_number(&self.peek(0)) && is_number(&self.peek(1))
8655    }
8656
8657    /// `a[i]` for a dense array and an integer index, without the string round trip.
8658    ///
8659    /// The slow path answers this by turning `i` into a string (`propkey` →
8660    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8661    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8662    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8663    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8664    /// without even the cheap `Int` formatting.
8665    ///
8666    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8667    /// unambiguously the one the slow path would give:
8668    ///
8669    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8670    ///   `2^32-1` is the length, not an index),
8671    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8672    ///   typed array or an ordinary object, all of which have their own rules),
8673    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8674    ///   starts walking the prototype chain, and `a[i]` on a hole must find
8675    ///   `Array.prototype[i]` if it exists rather than `undefined`.
8676    ///
8677    /// The last condition is the one that makes this safe rather than merely fast: an own
8678    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8679    /// `get_var` answered from the global-variable cache, or `None`.
8680    ///
8681    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8682    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8683    /// records nothing — the slow arm is about to walk the chain and record it.
8684    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8685        let frame = self.frame();
8686        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8687        // "Lexical" is presence in the realm's table, not the closure var's flag: a
8688        // `GlobalRef` forwarded through a nested function has its flags cleared.
8689        if self.realm.globals.contains_key(name) {
8690            return None;
8691        }
8692        if !self.scopes_are_plain() {
8693            return None;
8694        }
8695        let object = &self.realm.global;
8696        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8697        let cached = self.global_cache[site].as_ref()?;
8698        if !object.upgrades_to(&cached.object) {
8699            return None;
8700        }
8701        object.data_property_at(cached.index, name)
8702    }
8703
8704    /// `o.x` answered entirely from the inline cache, or `None`.
8705    ///
8706    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8707    /// about to do exactly that and recording it twice would rebuild the chain for every
8708    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8709    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8710    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8711        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8712        // an object receiver is a reference-count bump that the answer never needs.
8713        let frame = self.frame();
8714        let object = frame.stack.last()?;
8715        let Value::Object(target) = object else {
8716            return None;
8717        };
8718        // A proxy traps the lookup, so no cache entry ever describes it.
8719        if target.proxy_state().is_some() {
8720            return None;
8721        }
8722        let key = frame.code.atom_keys.get(atom)?;
8723        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8724        if cached.key != *key {
8725            return None;
8726        }
8727        Self::cached_hit(target, cached)
8728    }
8729
8730    fn fast_array_get(&self) -> Option<Value> {
8731        let Value::Int(index) = self.peek(0) else {
8732            return None;
8733        };
8734        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8735        // set for an `i32`.
8736        if index < 0 {
8737            return None;
8738        }
8739        let Value::Object(object) = self.peek(1) else {
8740            return None;
8741        };
8742        match object.array_get(index as usize) {
8743            Some(value) if !matches!(value, Value::Hole) => Some(value),
8744            _ => None,
8745        }
8746    }
8747
8748    /// `a[i] = v` on a dense array with an integer index, as one store.
8749    ///
8750    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8751    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8752    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8753    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8754    /// reference at the time it was measured (14.7x).
8755    ///
8756    /// Every condition here is one the slow path would also have to satisfy before
8757    /// storing into the element vector:
8758    ///
8759    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8760    ///   accepts as an index;
8761    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8762    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8763    ///   one inside a recorded descriptor, reports `false` and the caller stops.
8764    ///
8765    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8766    /// writes the own element too once `array_set` says it did.
8767    fn fast_array_set(&mut self) -> bool {
8768        // Every test runs *before* anything is popped: a refusal has to leave the stack
8769        // exactly as the slow path expects to find it. Popping first and reporting the
8770        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8771        // then ran the slow path with nothing to write.
8772        let Value::Int(index) = self.peek(1) else {
8773            return false;
8774        };
8775        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8776        if index < 0 {
8777            return false;
8778        }
8779        // Only a real array: a typed array's elements live in its buffer, a string-like
8780        // object has no element vector, and `array_set` on either does nothing.
8781        let Value::Object(object) = self.peek(2) else {
8782            return false;
8783        };
8784        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
8785            return false;
8786        }
8787        // A non-extensible array reports `false` here, but the *slow* path has to decide
8788        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
8789        // that with the key and the stack still intact.
8790        if !object.is_extensible() {
8791            return false;
8792        }
8793        // Inside the logical length, so the store cannot change `length`. Combined with
8794        // extensibility above, the only growth left for `array_set` is filling a hole in
8795        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
8796        // shape this fast path exists for. A store past the length would grow the array,
8797        // and whether that is allowed is the slow path's question.
8798        if index as usize >= object.array_length().unwrap_or(0) {
8799            return false;
8800        }
8801        // The bound `array_set` refuses past. Checking it here keeps that arm from having
8802        // to report a failure after the operands are gone.
8803        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
8804            return false;
8805        }
8806        let value = self.pop();
8807        self.pop();
8808        self.pop();
8809        object.array_store(self.heap, index as usize, value)
8810    }
8811
8812    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
8813    fn stop(&mut self, pc: usize) -> Option<Value> {
8814        self.frame_mut().pc = pc;
8815        None
8816    }
8817
8818    fn push(&mut self, value: Value) {
8819        self.frame_mut().stack.push(value);
8820    }
8821
8822    fn pop(&mut self) -> Value {
8823        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
8824    }
8825
8826    fn pop_n(&mut self, count: usize) -> Vec<Value> {
8827        let frame = self.frame_mut();
8828        let start = frame.stack.len().saturating_sub(count);
8829        frame.stack.split_off(start)
8830    }
8831
8832    fn peek(&self, back: usize) -> Value {
8833        let frame = self.frame();
8834        frame
8835            .stack
8836            .get(frame.stack.len().wrapping_sub(1 + back))
8837            .cloned()
8838            .unwrap_or(Value::Undefined)
8839    }
8840
8841    #[allow(clippy::too_many_lines)]
8842    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
8843        use Opcode::*;
8844        match op {
8845            // -- constants and stack shuffling -----------------------------
8846            Nop => {}
8847            PushMinus1 => self.push(Value::Int(-1)),
8848            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
8849                let value = match op {
8850                    Push0 => 0,
8851                    Push1 => 1,
8852                    Push2 => 2,
8853                    Push3 => 3,
8854                    Push4 => 4,
8855                    Push5 => 5,
8856                    Push6 => 6,
8857                    _ => 7,
8858                };
8859                self.push(Value::Int(value));
8860            }
8861            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
8862            PushBigintI32 => {
8863                // The immediate form of a `BigInt` literal; the reference has the same
8864                // split between this and a constant-pool entry.
8865                let value = crate::bigint::BigInt::from_i64(a as i64);
8866                self.push(self.bigint(value));
8867            }
8868            PushTrue => self.push(Value::Bool(true)),
8869            PushFalse => self.push(Value::Bool(false)),
8870            PushEmptyString => self.push(self.string("")),
8871            Undefined => self.push(Value::Undefined),
8872            Null => self.push(Value::Null),
8873            Object => {
8874                let proto = self.realm.object_proto.clone();
8875                self.push(Value::Object(self.new_object(Some(proto))));
8876            }
8877            PushThis => {
8878                let this = self.frame().this.clone();
8879                self.push(this);
8880            }
8881            PushConst | PushConst8 => {
8882                let value = self.constant(a as usize)?;
8883                self.push(value);
8884            }
8885            PushAtomValue => {
8886                let text = self.atom_wtf8(a as usize);
8887                self.push(self.string_wtf8(text));
8888            }
8889            Dup => {
8890                let value = self.peek(0);
8891                self.push(value);
8892            }
8893            Dup2 => {
8894                // `a b -> a b a b`
8895                let b = self.peek(0);
8896                let a = self.peek(1);
8897                self.push(a);
8898                self.push(b);
8899            }
8900            Dup3 => {
8901                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
8902                // prototype and key while reading the current value through them.
8903                let c = self.peek(0);
8904                let b = self.peek(1);
8905                let a = self.peek(2);
8906                self.push(a);
8907                self.push(b);
8908                self.push(c);
8909            }
8910            Swap => {
8911                // `a b -> b a`
8912                let bottom = self.pop();
8913                let top = self.pop();
8914                self.push(bottom);
8915                self.push(top);
8916            }
8917            Perm3 => {
8918                // `a b c -> b a c`, the reference's reordering for a spread method
8919                // call: `obj func array` becomes the `func this array` that `apply`
8920                // takes.
8921                let c = self.pop();
8922                let b = self.pop();
8923                let a = self.pop();
8924                self.push(b);
8925                self.push(a);
8926                self.push(c);
8927            }
8928            Dup1 => {
8929                let value = self.peek(1);
8930                self.push(value);
8931            }
8932            Drop => {
8933                self.pop();
8934            }
8935            Nip => {
8936                // `a b -> b`
8937                let top = self.pop();
8938                self.pop();
8939                self.push(top);
8940            }
8941            Perm4 => {
8942                // `obj prop a b -> a obj prop b`, the reference's reordering for a
8943                // postfix update of a computed element: it puts the *old* value
8944                // underneath the receiver and key so `put_array_el` can consume them
8945                // and leave the old value as the expression's result.
8946                let d = self.pop();
8947                let c = self.pop();
8948                let b = self.pop();
8949                let a = self.pop();
8950                self.push(c);
8951                self.push(a);
8952                self.push(b);
8953                self.push(d);
8954            }
8955            Insert2 => {
8956                // `obj a -> a obj a`
8957                let value = self.pop();
8958                let object = self.pop();
8959                self.push(value.clone());
8960                self.push(object);
8961                self.push(value);
8962            }
8963            Insert3 => {
8964                // `obj prop a -> a obj prop a`
8965                let value = self.pop();
8966                let key = self.pop();
8967                let object = self.pop();
8968                self.push(value.clone());
8969                self.push(object);
8970                self.push(key);
8971                self.push(value);
8972            }
8973            Insert4 => {
8974                // `this obj prop a -> a this obj prop a`
8975                //
8976                // `put_super_value` consumes all four and yields nothing, so the copy
8977                // underneath is what leaves the assignment an expression value.
8978                let value = self.pop();
8979                let key = self.pop();
8980                let object = self.pop();
8981                let receiver = self.pop();
8982                self.push(value.clone());
8983                self.push(receiver);
8984                self.push(object);
8985                self.push(key);
8986                self.push(value);
8987            }
8988            Swap2 => {
8989                // `a b c d -> c d a b`
8990                let d = self.pop();
8991                let c = self.pop();
8992                let b = self.pop();
8993                let a = self.pop();
8994                self.push(c);
8995                self.push(d);
8996                self.push(a);
8997                self.push(b);
8998            }
8999            Rot3l => {
9000                // `x a b -> a b x`
9001                let b = self.pop();
9002                let a = self.pop();
9003                let x = self.pop();
9004                self.push(a);
9005                self.push(b);
9006                self.push(x);
9007            }
9008            Rot3r => {
9009                // `a b c -> c a b`
9010                let c = self.pop();
9011                let b = self.pop();
9012                let a_value = self.pop();
9013                self.push(c);
9014                self.push(a_value);
9015                self.push(b);
9016            }
9017
9018            Rest => {
9019                // `...rest` in a parameter list: the arguments from index `a` on, as a
9020                // real array. It takes nothing off the stack — the arguments are in the
9021                // frame, not on it.
9022                let frame = self.frame();
9023                let from = a as usize;
9024                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9025                let array = self.new_array(collected);
9026                self.push(Value::Object(array));
9027            }
9028
9029            // -- slots ------------------------------------------------------
9030            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9031                let slot = self.slot_operand(op, a);
9032                let value = self.get_loc(slot);
9033                self.push(value);
9034            }
9035            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9036                let slot = self.slot_operand(op, a);
9037                let value = self.pop();
9038                self.put_loc(slot, value);
9039            }
9040            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9041                let slot = self.slot_operand(op, a);
9042                let value = self.pop();
9043                self.put_loc(slot, value.clone());
9044                self.push(value);
9045            }
9046            // The `_check` forms are the temporal dead zone: they throw when the
9047            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9048            // *reads*, so only the two writes may pop — mishandling that quietly
9049            // consumes the value the caller pushed just before.
9050            GetLocCheck => {
9051                let slot = self.slot_operand(op, a);
9052                let value = self.get_loc(slot);
9053                if matches!(value, Value::Uninitialized) {
9054                    return Err(self.dead_zone(slot, VarSlot::Loc));
9055                }
9056                self.push(value);
9057            }
9058            PutLocCheck | SetLocCheck => {
9059                let slot = self.slot_operand(op, a);
9060                let value = self.pop();
9061                if matches!(value, Value::Uninitialized) {
9062                    return Err(self.dead_zone(slot, VarSlot::Loc));
9063                }
9064                // The initialiser goes through `put_loc`, not this, so any store that
9065                // reaches here is a later assignment — which a `const` refuses.
9066                if self.is_read_only(slot, VarSlot::Loc) {
9067                    return Err(self.read_only(slot, VarSlot::Loc));
9068                }
9069                if op == SetLocCheck {
9070                    self.put_loc(slot, value.clone());
9071                    self.push(value);
9072                } else {
9073                    self.put_loc(slot, value);
9074                }
9075            }
9076            PutLocCheckInit => {
9077                // The one store that *initialises* a lexical slot: `this` in a derived
9078                // constructor, which only exists after `super()` has run. A second
9079                // initialisation is the error the reference reports as
9080                // "'this' can be initialized only once".
9081                let slot = self.slot_operand(op, a);
9082                let value = self.pop();
9083                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9084                    return Err(Signal::Throw(self.make_error(
9085                        "ReferenceError",
9086                        "'this' can be initialized only once",
9087                    )));
9088                }
9089                self.put_loc(slot, value);
9090            }
9091            CheckCtor => {
9092                // A class constructor may only run under `new`, which is what makes
9093                // `class A {}; A()` a TypeError.
9094                if matches!(self.frame().new_target, Value::Undefined) {
9095                    return Err(Signal::Throw(self.make_error(
9096                        "TypeError",
9097                        "class constructors must be invoked with 'new'",
9098                    )));
9099                }
9100            }
9101            InitCtor => {
9102                // The body a derived class gets when it declares no constructor:
9103                // forward every argument to the parent constructor, keeping `new.target`.
9104                if matches!(self.frame().new_target, Value::Undefined) {
9105                    return Err(Signal::Throw(self.make_error(
9106                        "TypeError",
9107                        "class constructors must be invoked with 'new'",
9108                    )));
9109                }
9110                let Some(callee) = self.current_callee() else {
9111                    return Err(Signal::Throw(
9112                        self.make_error("TypeError", "no constructor to inherit from"),
9113                    ));
9114                };
9115                let parent = callee.proto().map_or(Value::Null, Value::Object);
9116                let new_target = self.frame().new_target.clone();
9117                let args = self.frame().passed().to_vec();
9118                let result = self.construct(parent, new_target, args)?;
9119                self.push(result);
9120            }
9121            SetLocUninitialized => {
9122                let slot = self.slot_operand(op, a);
9123                self.put_loc(slot, Value::Uninitialized);
9124            }
9125            CloseLoc => {
9126                // "Close" a binding: give it a *fresh* cell holding the current
9127                // value. Closures created before this point keep the old cell and the
9128                // ones created after see the new one, which is what makes every
9129                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9130                // a block-scoped binding when the block ends.
9131                //
9132                // Clearing the slot instead (which this used to do) broke both: a
9133                // closure over a captured block variable read `undefined`, and a loop
9134                // terminated after one iteration.
9135                let slot = self.slot_operand(op, a);
9136                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9137                if index >= 0 {
9138                    let current = self.frame().cells[index as usize].get();
9139                    let fresh = self.new_cell(current);
9140                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9141                        *cell = fresh;
9142                    }
9143                }
9144            }
9145            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9146                let slot = self.slot_operand(op, a);
9147                let value = self.get_arg(slot);
9148                self.push(value);
9149            }
9150            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9151                let slot = self.slot_operand(op, a);
9152                let value = self.pop();
9153                self.put_arg(slot, value);
9154            }
9155            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9156                let slot = self.slot_operand(op, a);
9157                let value = self.pop();
9158                self.put_arg(slot, value.clone());
9159                self.push(value);
9160            }
9161
9162            // -- closure variables ------------------------------------------
9163            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9164                let slot = self.slot_operand(op, a);
9165                // A name a direct `eval` created shadows the binding the compiler chose.
9166                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9167                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9168                // and only a runtime lookup can know that.
9169                if let Some(cell) = self.eval_created_local(slot) {
9170                    self.push(cell.get());
9171                    return self.step();
9172                }
9173                let value = self.cell_value(slot)?;
9174                self.push(value);
9175            }
9176            GetVarRefCheck => {
9177                let slot = self.slot_operand(op, a);
9178                let value = self.cell_value(slot)?;
9179                if matches!(value, Value::Uninitialized) {
9180                    return Err(self.dead_zone(slot, VarSlot::Closure));
9181                }
9182                self.push(value);
9183            }
9184            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9185                let slot = self.slot_operand(op, a);
9186                let value = self.pop();
9187                if let Some(cell) = self.eval_created_local(slot) {
9188                    cell.set(value);
9189                    return self.step();
9190                }
9191                // Same rule as `PutLocCheck`: a checked store to a captured binding
9192                // refuses a `const` once its initialiser has run.
9193                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9194                    return Err(self.read_only(slot, VarSlot::Closure));
9195                }
9196                self.set_cell(slot, value)?;
9197            }
9198            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9199                let slot = self.slot_operand(op, a);
9200                let value = self.pop();
9201                if let Some(cell) = self.eval_created_local(slot) {
9202                    cell.set(value.clone());
9203                    self.push(value);
9204                    return self.step();
9205                }
9206                self.set_cell(slot, value.clone())?;
9207                self.push(value);
9208            }
9209
9210            // -- globals ----------------------------------------------------
9211            GetVar => {
9212                let value = self.get_global(a as usize)?;
9213                self.push(value);
9214            }
9215            GetVarUndef => {
9216                let value = self
9217                    .get_global(a as usize)
9218                    .or_else(|_| Ok(Value::Undefined))?;
9219                self.push(value);
9220            }
9221            DeleteVar => {
9222                // `delete name` for a name that is not a declared binding. A lexical
9223                // global lives in the reference table and cannot be deleted; anything
9224                // reachable only as a property of the global object is *implicit* —
9225                // `x = 1` with no declaration — and goes away if it is configurable,
9226                // which is what `delete` on an implicit global answers.
9227                let name = self.atom_text(a as usize);
9228                let global = self.realm.global.clone();
9229                let deleted = if self.realm.globals.contains_key(&name) {
9230                    false
9231                } else if global.own_property(&name).is_some() {
9232                    self.delete_property(&global, &name)?
9233                } else {
9234                    true
9235                };
9236                self.push(Value::Bool(deleted));
9237            }
9238            PutVar => {
9239                let value = self.pop();
9240                self.put_global(a as usize, value)?;
9241            }
9242            PutVarInit => {
9243                let slot = a as usize;
9244                let value = self.pop();
9245                self.init_global(slot, value)?;
9246            }
9247
9248            // -- arithmetic -------------------------------------------------
9249            Add => self.binary_add()?,
9250            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9251                let raw_right = self.pop();
9252                let raw_left = self.pop();
9253                // BigInt arithmetic is a separate path, and not only for the type of the
9254                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9255                // rather than a silent conversion.
9256                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9257                    let left = self.primitive_of(raw_left)?;
9258                    let right = self.primitive_of(raw_right)?;
9259                    let value = self.bigint_arithmetic(op, left, right)?;
9260                    self.push(value);
9261                } else {
9262                    let right = self.numeric(raw_right)?;
9263                    let left = self.numeric(raw_left)?;
9264                    self.push(arithmetic(op, left, right)?);
9265                }
9266            }
9267            Neg => {
9268                let raw = self.pop();
9269                match raw {
9270                    // A bigint negates exactly, however wide it is.
9271                    Value::BigInt(big) => {
9272                        let negated = big.negate();
9273                        self.push(self.bigint(negated));
9274                    }
9275                    other => {
9276                        let value = self.numeric(other)?;
9277                        self.push(negate(value));
9278                    }
9279                }
9280            }
9281            Plus => {
9282                let value = self.pop();
9283                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9284                // unary plus is defined to produce a *number*, which a bigint cannot
9285                // become without loss. It used to fall through to `NaN`.
9286                if matches!(value, Value::BigInt(_)) {
9287                    return Err(self.type_error("cannot convert bigint to number"));
9288                }
9289                let numeric = self.numeric_of(value)?;
9290                self.push(numeric);
9291            }
9292            Inc => {
9293                let raw = self.pop();
9294                let (_, updated) = self.advance_numeric(raw, true)?;
9295                self.push(updated);
9296            }
9297            Dec => {
9298                let raw = self.pop();
9299                let (_, updated) = self.advance_numeric(raw, false)?;
9300                self.push(updated);
9301            }
9302            PostInc | PostDec => {
9303                // `x -> x x+1`: the *new* value ends up on top, so the store the
9304                // compiler emits right after (`put_var`) writes the incremented
9305                // one, while the old value stays underneath for the expression's
9306                // own result. Getting this backwards makes `i++` a no-op, which
9307                // turns `while (i < 3)` into an infinite loop.
9308                let raw = self.pop();
9309                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9310                self.push(old);
9311                self.push(updated);
9312            }
9313            Not => {
9314                let raw = self.pop();
9315                match raw {
9316                    // `~x` on a bigint is `-x - 1`, exact at any width.
9317                    Value::BigInt(big) => {
9318                        let inverted = big.bitnot();
9319                        self.push(self.bigint(inverted));
9320                    }
9321                    other => {
9322                        let value = self.numeric(other)?;
9323                        self.push(Value::Int(!value.to_int32()));
9324                    }
9325                }
9326            }
9327            Lnot => {
9328                let value = self.pop();
9329                self.push(Value::Bool(!value.to_boolean()));
9330            }
9331
9332            // -- comparison -------------------------------------------------
9333            Lt | Lte | Gt | Gte => {
9334                let right = self.pop();
9335                let left = self.pop();
9336                let answer = self.relational(op, left, right)?;
9337                self.push(answer);
9338            }
9339            Eq | Neq => {
9340                let right = self.pop();
9341                let left = self.pop();
9342                let equal = self.abstract_equals(left, right)?;
9343                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9344            }
9345            StrictEq => {
9346                let right = self.pop();
9347                let left = self.pop();
9348                self.push(Value::Bool(left.strict_equals(&right)));
9349            }
9350            StrictNeq => {
9351                let right = self.pop();
9352                let left = self.pop();
9353                self.push(Value::Bool(!left.strict_equals(&right)));
9354            }
9355            IsUndefined => {
9356                // `=== undefined`, which is what a destructuring default tests. It is
9357                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9358                let value = self.pop();
9359                self.push(Value::Bool(matches!(value, Value::Undefined)));
9360            }
9361            IsUndefinedOrNull => {
9362                let value = self.pop();
9363                self.push(Value::Bool(value.is_nullish()));
9364            }
9365            Typeof => {
9366                let value = self.pop();
9367                self.push(self.string(value.type_of()));
9368            }
9369            ToObject => {
9370                // A destructuring *object* pattern starts here, which is why
9371                // `var {} = null` throws. Only `undefined` and `null` are refused; a
9372                // primitive is boxed.
9373                let value = self.pop();
9374                let object = self.object_from(&value)?;
9375                self.push(Value::Object(object));
9376            }
9377            Instanceof => {
9378                let constructor = self.pop();
9379                let object = self.pop();
9380                let answer = self.instance_of(&object, &constructor)?;
9381                self.push(Value::Bool(answer));
9382            }
9383            In => {
9384                let object = self.pop();
9385                let key = self.pop();
9386                let answer = self.has_property(&key, &object)?;
9387                self.push(Value::Bool(answer));
9388            }
9389
9390            // -- control flow -----------------------------------------------
9391            Goto | Goto8 | Goto16 => {
9392                self.frame_mut().pc = a as usize;
9393            }
9394            IfTrue | IfTrue8 => {
9395                let value = self.pop();
9396                if value.to_boolean() {
9397                    self.frame_mut().pc = a as usize;
9398                }
9399            }
9400            IfFalse | IfFalse8 => {
9401                let value = self.pop();
9402                if !value.to_boolean() {
9403                    self.frame_mut().pc = a as usize;
9404                }
9405            }
9406            Catch => {
9407                // Pushes the handler target onto the value stack; `unwind` finds it.
9408                self.push(Value::CatchOffset(a));
9409            }
9410            Gosub => {
9411                self.push(Value::ReturnAddress(next as u32));
9412                self.frame_mut().pc = a as usize;
9413            }
9414            Ret => {
9415                let value = self.pop();
9416                match value {
9417                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9418                    _ => {
9419                        return Err(Signal::Throw(
9420                            self.make_error("InternalError", "invalid return address"),
9421                        ));
9422                    }
9423                }
9424            }
9425            NipCatch => {
9426                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9427                // including the marker, keeping the top value.
9428                let top = self.pop();
9429                loop {
9430                    match self.pop() {
9431                        Value::CatchOffset(_) | Value::Undefined => break,
9432                        _ => {}
9433                    }
9434                    if self.frame().stack.is_empty() {
9435                        break;
9436                    }
9437                }
9438                self.push(top);
9439            }
9440            Throw => {
9441                let value = self.pop();
9442                return Err(Signal::Throw(value));
9443            }
9444            ThrowError => {
9445                let name = self.atom_text(a as usize);
9446                let (class, message) = match b {
9447                    0 => ("TypeError", format!("'{name}' is read-only")),
9448                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9449                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
9450                    // `delete super.x` is a syntax-level mistake the reference reports
9451                    // with this wording, not a property-access failure.
9452                    3 => (
9453                        "ReferenceError",
9454                        "unsupported reference to 'super'".to_string(),
9455                    ),
9456                    4 => (
9457                        "TypeError",
9458                        "iterator does not have a throw method".to_string(),
9459                    ),
9460                    5 => (
9461                        "ReferenceError",
9462                        "invalid assignment left-hand side".to_string(),
9463                    ),
9464                    _ => ("TypeError", format!("invalid operation on '{name}'")),
9465                };
9466                return Err(Signal::Throw(self.make_error(class, &message)));
9467            }
9468            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9469            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9470            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9471            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9472            Await => return Ok(Step::Suspend(SuspendKind::Await)),
9473            ReturnAsync => {
9474                // The reference's `return_async` returns `undefined` and lets the resume
9475                // machinery pick the real value off `sp[-1]`, which is how it tells a
9476                // completion from a suspension. Carrying the value explicitly says the
9477                // same thing without the implicit stack slot.
9478                let value = self.pop();
9479                return Ok(Step::Return(value));
9480            }
9481            Return => {
9482                let value = self.pop();
9483                return Ok(Step::Return(value));
9484            }
9485            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9486
9487            // -- calls ------------------------------------------------------
9488            Call | Call0 | Call1 | Call2 | Call3 => {
9489                let argc = self.argc_operand(op, a);
9490                let args = self.pop_n(argc);
9491                let callee = self.pop();
9492                // A plain call has no receiver; the callee decides what to do with
9493                // `undefined` (a sloppy function substitutes the global object).
9494                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9495                    self.push(result);
9496                }
9497            }
9498            CallConstructor => {
9499                // `constructor this_obj args… -> object`. The duplicated
9500                // constructor is `new.target`; this milestone does not expose it,
9501                // so the extra copy is simply consumed here.
9502                let argc = a as usize;
9503                let args = self.pop_n(argc);
9504                let new_target = self.pop();
9505                let callee = self.pop();
9506                let result = self.construct(callee, new_target, args)?;
9507                self.push(result);
9508            }
9509            CallMethod => {
9510                let argc = a as usize;
9511                let args = self.pop_n(argc);
9512                let callee = self.pop();
9513                let this = self.pop();
9514                if let Some(result) = self.call_or_push(callee, this, args)? {
9515                    self.push(result);
9516                }
9517            }
9518            Apply => {
9519                // `func this array -> result`, the spread-call form: the compiler
9520                // builds one array of arguments, and all that is left here is to
9521                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9522                let array = self.pop();
9523                let this = self.pop();
9524                let callee = self.pop();
9525                let args = self.array_like_to_args(&array)?;
9526                if a & 1 != 0 {
9527                    let result = self.construct(callee, this, args)?;
9528                    self.push(result);
9529                } else if let Some(result) = self.call_or_push(callee, this, args)? {
9530                    self.push(result);
9531                }
9532            }
9533            TailCall | TailCallMethod => {
9534                // `tail_call` is `call` whose result is returned immediately — the
9535                // reference jumps straight to `done` instead of storing the value and
9536                // running on. The callee still gets its own frame, so deep tail
9537                // recursion hits the stack limit exactly like plain recursion does;
9538                // marking this frame lets the return path unwind without needing
9539                // instructions after the call.
9540                let argc = if op == TailCallMethod {
9541                    a as usize
9542                } else {
9543                    self.argc_operand(op, a)
9544                };
9545                let args = self.pop_n(argc);
9546                let callee = self.pop();
9547                let this = if op == TailCallMethod {
9548                    self.pop()
9549                } else {
9550                    Value::Undefined
9551                };
9552                if let Value::Object(function) = &callee
9553                    && let Some((code, env)) = bytecode_of(function)
9554                {
9555                    // A generator or async body is not run here at all: calling it only
9556                    // *creates* the generator/coroutine, so it must not inherit this
9557                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
9558                    // onto `f`'s frame, and the first `yield`/`await` then reported
9559                    // "a generator body ran as an ordinary call".
9560                    if code.code.kind.is_generator() || code.code.kind.is_async() {
9561                        let value = self.call_value(callee, this, args)?;
9562                        return Ok(Step::Return(value));
9563                    }
9564                    self.frame_mut().tail = true;
9565                    self.push_frame(code, env, this, args, callee)?;
9566                    return Ok(Step::Continue);
9567                }
9568                // A native callee has no frame to reuse, so its value is simply
9569                // returned.
9570                let value = self.call_value(callee, this, args)?;
9571                return Ok(Step::Return(value));
9572            }
9573
9574            // -- objects ----------------------------------------------------
9575            SpecialObject => {
9576                let value = self.special_object(a)?;
9577                self.push(value);
9578            }
9579            PrivateSymbol => {
9580                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9581                // symbol each time it is evaluated, which is why the compiler evaluates it
9582                // once (at class definition) and stores it in a class-scope binding.
9583                let name = self.atom_text(a as usize);
9584                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9585                self.push(Value::Symbol(symbol));
9586            }
9587            GetPrivateField => {
9588                // `obj symbol -> value`. A missing private field is a TypeError, which is what
9589                // makes `#x` inaccessible on any object not built by this class.
9590                let symbol = self.pop();
9591                let object = self.pop();
9592                let value = self.read_private_field(&object, &symbol)?;
9593                self.push(value);
9594            }
9595            PutPrivateField => {
9596                // `obj value symbol ->`, and the store is a plain assignment to a property the
9597                // class already created, so there is no setter to consult.
9598                let symbol = self.pop();
9599                let value = self.pop();
9600                let object = self.pop();
9601                self.write_private_field(&object, &symbol, value)?;
9602            }
9603            DefinePrivateField => {
9604                // `obj symbol value -> obj`: a field initialiser creates the property, and
9605                // redefining one is a TypeError ("already exists").
9606                let value = self.pop();
9607                let symbol = self.pop();
9608                let object = self.pop();
9609                self.define_private_field(&object, &symbol, value)?;
9610                self.push(object);
9611            }
9612            PrivateIn => {
9613                // `obj key -> bool`: `#x in o`. The second operand decides which question is
9614                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9615                // is a field, so this is an own-property test; a *function* is a method or
9616                // accessor, so this is a brand check.
9617                let key = self.pop();
9618                let object = self.pop();
9619                let Some(target) = object.as_object() else {
9620                    return Err(Signal::Throw(
9621                        self.make_error("TypeError", "invalid 'in' operand"),
9622                    ));
9623                };
9624                let present = match &key {
9625                    Value::Object(_) => self.check_brand(target, &key)?,
9626                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9627                };
9628                self.push(Value::Bool(present));
9629            }
9630            AddBrand => {
9631                // `obj home ->`: create the class brand on `home` if it has none, then give
9632                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9633                // class definition: only the prototype's copy of the symbol is wanted.
9634                let home = self.pop();
9635                let object = self.pop();
9636                self.add_brand(&object, &home)?;
9637            }
9638            CheckBrand => {
9639                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9640                // Both stay, because the caller needs them — `nip` halves a read into its
9641                // value and `call_method` uses the pair as receiver and callee.
9642                let function = self.peek(0);
9643                let object = self.peek(1);
9644                let Some(target) = object.as_object() else {
9645                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9646                };
9647                if !self.check_brand(target, &function)? {
9648                    return Err(Signal::Throw(
9649                        self.make_error("TypeError", "invalid brand on object"),
9650                    ));
9651                }
9652            }
9653            GetLength => {
9654                // `get_length` is the `.length` read; an array and a string answer
9655                // from their own length, anything else from the property.
9656                let target = self.pop();
9657                let value = match &target {
9658                    Value::Object(object) => match object.array_length() {
9659                        Some(length) => crate::object::length_value(length),
9660                        None => self.read_field(&target, "length")?,
9661                    },
9662                    Value::String(text) => Value::Int(text.utf16_len() as i32),
9663                    _ => self.read_field(&target, "length")?,
9664                };
9665                self.push(value);
9666            }
9667            GetField | GetField2 => {
9668                let object = self.pop();
9669                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9670                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9671                // just below is what lets the borrow outlive the `&mut self` the lookup
9672                // needs — one refcount bump instead of a key clone plus its drop, on the
9673                // hottest property path there is: every `o.x` and every `o.m()` receiver.
9674                let code = self.frame().code.clone();
9675                let key = &code.atom_keys[a as usize];
9676                let value = self.read_field_cached(&object, key, next)?;
9677                if op == GetField2 {
9678                    self.push(object);
9679                }
9680                self.push(value);
9681            }
9682            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9683                let key = self.pop();
9684                let object = self.pop();
9685                let key = self.propkey(&key)?;
9686                let value = self.read_field_key(&object, &key)?;
9687                if matches!(op, GetArrayEl2 | GetArrayEl3) {
9688                    self.push(object);
9689                }
9690                if op == GetArrayEl3 {
9691                    // The key goes back in its *value* form, which the compiler stores
9692                    // into the target of a destructuring assignment.
9693                    self.push(match &key {
9694                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9695                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
9696                    });
9697                }
9698                self.push(value);
9699            }
9700            PutField => {
9701                let value = self.pop();
9702                let object = self.pop();
9703                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9704                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9705                // only reads. `this.value = …` is the write half of the hottest loop in
9706                // `property:method-call`, and `own_property_key` was 4.8% of the case.
9707                let code = self.frame().code.clone();
9708                let key = &code.atom_keys[a as usize];
9709                self.write_field_key(&object, key, value)?;
9710            }
9711            PutArrayEl => {
9712                let value = self.pop();
9713                let key = self.pop();
9714                let object = self.pop();
9715                let key = self.propkey(&key)?;
9716                self.write_field_key(&object, &key, value)?;
9717            }
9718            DefineField => {
9719                let value = self.pop();
9720                let object = self.pop();
9721                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9722                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9723                // three U+FFFD — a property under a different name from the one
9724                // `o["\uD800"]` reads.
9725                let code = self.frame().code.clone();
9726                let key = code.atom_keys[a as usize].clone();
9727                // No naming here. `{m: function(){}}` is named by the *compiler*, which
9728                // emits `set_name` — and only where `NamedEvaluation` applies, so
9729                // `{m: (0, function(){})}` stays anonymous. Naming every function that
9730                // reaches a property definition got that case wrong, and the compiler is
9731                // the only place that can tell the two apart.
9732                if let Some(target) = object.as_object() {
9733                    // Only an *array* stores into the element vector. A numeric key
9734                    // on an ordinary object is an ordinary property, which is what
9735                    // makes `{1: 'a'}` iterate as a key rather than disappear.
9736                    let stored = target.is_array()
9737                        && key.as_str().and_then(array_index).is_some_and(|index| {
9738                            target.array_set(self.heap, index as usize, value.clone())
9739                        });
9740                    if !stored {
9741                        target.define_data_key(&key, value);
9742                    }
9743                }
9744                self.push(object);
9745            }
9746            DefineArrayEl => {
9747                // `obj key value -> obj key`. The *value* form of the key is what goes
9748                // back on the stack — the compiler stores it into the pattern's binding —
9749                // so the symbol is not stringified on the way through.
9750                let value = self.pop();
9751                let key_value = self.pop();
9752                let object = self.peek(0);
9753                let key = self.propkey(&key_value)?;
9754                self.write_field_key(&object, &key, value)?;
9755                self.push(key_value);
9756            }
9757            SetHomeObject => {
9758                // `obj func -> obj func`: records the object a method was defined on so
9759                // `super` inside it resolves against that object's prototype.
9760                let function = self.peek(0);
9761                let home = self.peek(1);
9762                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9763                    function.set_home_object(Some(home.clone()));
9764                }
9765            }
9766            Regexp => {
9767                // `pattern flags -> regexp`. A literal compiles here rather than through the
9768                // constructor, which is both what the reference's dedicated opcode is for
9769                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9770                let flags = self.pop();
9771                let pattern = self.pop();
9772                let pattern = self.to_js_string(&pattern)?;
9773                let flags = self.to_js_string(&flags)?;
9774                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9775                self.push(Value::Object(object));
9776            }
9777            UsingDisposeInit => {
9778                // The error state a disposal accumulates into. Uninitialised means "no
9779                // failure yet"; anything else is the exception being propagated.
9780                self.push(Value::Uninitialized);
9781            }
9782            UsingCheck => {
9783                // `value -> value, method`: validate and snapshot the disposer now, so a
9784                // later change to `Symbol.dispose` cannot change what gets called, and so a
9785                // value that is not disposable fails before the body runs.
9786                let value = self.pop();
9787                let method = self.using_method_for(&value, a as u8 == 1)?;
9788                self.push(value);
9789                self.push(method);
9790            }
9791            UsingDispose => {
9792                // `error_state -> error_state'`: dispose the variable at `slot` — its value
9793                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
9794                // the pending error.
9795                let slot = self.slot_operand(op, a);
9796                let error_state = self.pop();
9797                let merged = self.using_dispose_once(slot, error_state)?;
9798                self.push(merged);
9799            }
9800            UsingDisposeMerge => {
9801                let new_error = self.pop();
9802                let error_state = self.pop();
9803                let merged = self.merge_dispose_error(new_error, error_state);
9804                self.push(merged);
9805            }
9806            UsingDisposeEnd => {
9807                // A disposal that failed replaces the block's normal completion, so the
9808                // error state becomes a real throw here rather than at the call site.
9809                let error_state = self.pop();
9810                if !matches!(error_state, Value::Uninitialized) {
9811                    return Err(Signal::Throw(error_state));
9812                }
9813            }
9814            UsingDisposeAsync => {
9815                // `await using` needs a promise to await and this runtime has no
9816                // `Promise` builtin, so the disposer is called synchronously and its result
9817                // discarded. That is correct for a disposer that returns nothing and is
9818                // reported as a gap rather than silently skipped.
9819                let slot = self.slot_operand(op, a);
9820                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
9821                self.push(error_state);
9822            }
9823            GetSuper => {
9824                // `obj -> obj's prototype`: the starting point of a `super` lookup.
9825                let object = self.pop();
9826                let proto = match &object {
9827                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
9828                    _ => Value::Null,
9829                };
9830                self.push(proto);
9831            }
9832            GetSuperValue => {
9833                // `receiver proto key -> value`, searching from `proto` but reporting to
9834                // `receiver`, which is what `super.g` must do for a getter to see `this`.
9835                //
9836                // Three values in, one out: the receiver is *consumed*, not left under the
9837                // result. Leaving it there was invisible for `super.x` in `return` or
9838                // statement position (the result is what gets popped) and corrupted the
9839                // frame everywhere else — `print(super.x)` left the class where the call
9840                // opcode looks for the receiver and called the class itself.
9841                let key = self.pop();
9842                let proto = self.pop();
9843                let receiver = self.pop();
9844                let value = self.super_read(&receiver, &proto, &key)?;
9845                self.push(value);
9846            }
9847            PutSuperValue => {
9848                // `receiver proto key value ->`: a store that starts at `proto` but
9849                // assigns to `receiver`.
9850                let value = self.pop();
9851                let key = self.pop();
9852                let proto = self.pop();
9853                let receiver = self.pop();
9854                self.super_write(&receiver, &proto, &key, value)?;
9855            }
9856            DefineClass => {
9857                // `parent ctor -> ctor proto`: the constructor becomes the class and a
9858                // fresh prototype object lands on top for the methods to go on.
9859                let name = self.atom_text(a as usize);
9860                let (ctor, proto) = self.define_class(&name, b)?;
9861                self.push(ctor);
9862                self.push(Value::Object(proto));
9863            }
9864            DefineClassComputed => {
9865                // `parent ctor key -> ctor proto key`: the computed name stays put so
9866                // `define_field`-style consumers can still read it.
9867                let key = self.pop();
9868                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9869                let (ctor, proto) = self.define_class(&name, b)?;
9870                self.push(ctor);
9871                self.push(Value::Object(proto));
9872                self.push(key);
9873            }
9874            DefineMethod => {
9875                let function = self.pop();
9876                let object = self.pop();
9877                // The exact key, like `define_field`: a quoted method key may hold an
9878                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
9879                // that `o["\uD800"]` finds.
9880                let code = self.frame().code.clone();
9881                let key = code.atom_keys[a as usize].clone();
9882                // A method's `[[HomeObject]]` is the object it was defined on, which is
9883                // what `super` inside it resolves against.
9884                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9885                    function.set_home_object(Some(object.clone()));
9886                }
9887                if let Some(text) = key.as_wtf8() {
9888                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
9889                } else {
9890                    self.set_function_name(
9891                        &function,
9892                        &key_with_accessor_prefix(&key.to_string(), b),
9893                    );
9894                }
9895                if let Some(array) = object.as_object() {
9896                    define_function_property(array, &key, function, b);
9897                }
9898                self.push(object);
9899            }
9900            DefineMethodComputed => {
9901                let function = self.pop();
9902                let key = self.pop();
9903                let object = self.pop();
9904                let key = self.propkey(&key)?;
9905                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
9906                // the name: `super` inside a computed method resolves through it. Without
9907                // this, `class B extends A { [k]() { return super.m() } }` read the
9908                // home object as null and threw.
9909                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9910                    function.set_home_object(Some(object.clone()));
9911                }
9912                match key.as_wtf8() {
9913                    Some(text) => {
9914                        let name = accessor_prefixed(text, a);
9915                        self.set_function_name_wtf8(&function, &name);
9916                    }
9917                    None => self.set_function_name(
9918                        &function,
9919                        &key_with_accessor_prefix(&key.to_string(), a),
9920                    ),
9921                }
9922                if let Some(array) = object.as_object() {
9923                    define_function_property(array, &key, function, a);
9924                }
9925                self.push(object);
9926            }
9927            SetProto => {
9928                let proto = self.pop();
9929                let object = self.pop();
9930                if let Some(target) = object.as_object() {
9931                    target.set_proto(proto.as_object().cloned());
9932                }
9933                self.push(object);
9934            }
9935            CopyDataProperties => {
9936                let exclusion = self.pop();
9937                let source = self.pop();
9938                let target = self.peek(0);
9939                self.copy_properties(&target, &source, &exclusion)?;
9940                self.push(source);
9941                self.push(exclusion);
9942            }
9943            ToPropkey => {
9944                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
9945                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
9946                // ordinary `"Symbol(b)"` property.
9947                let value = self.pop();
9948                let key = match self.propkey(&value)? {
9949                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
9950                    PropertyKey::String(text) => self.string_wtf8(text),
9951                };
9952                self.push(key);
9953            }
9954            SetName => {
9955                let function = self.peek(0);
9956                let name = self.atom_wtf8(a as usize);
9957                self.set_function_name_wtf8(&function, &name);
9958            }
9959            SetNameComputed => {
9960                let key = self.peek(1);
9961                let function = self.peek(0);
9962                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9963                self.set_function_name(&function, &name);
9964            }
9965
9966            // -- arrays -----------------------------------------------------
9967            ArrayFrom => {
9968                let count = a as usize;
9969                let elements = self.pop_n(count);
9970                let array = self.new_array(elements);
9971                self.push(Value::Object(array));
9972            }
9973            Append => {
9974                // `array index iterable -> array new_index`
9975                let iterable = self.pop();
9976                self.pop();
9977                let array = self.peek(0);
9978                let added = self.append_enumerate(&array, &iterable)?;
9979                self.push(Value::Int(added));
9980            }
9981
9982            // -- iteration --------------------------------------------------
9983            ForInStart => {
9984                let value = self.pop();
9985                let record = self.for_in_record(&value)?;
9986                self.push(Value::Object(record));
9987            }
9988            ForInNext => {
9989                // `record -> record key done`. The flag is *done*, not "found":
9990                // the compiler tests it with `if_false` to jump back into the body,
9991                // so reporting `true` while keys remain would end the loop at once.
9992                let record = self.peek(0);
9993                match self.for_in_advance(&record)? {
9994                    Some(key) => {
9995                        let text = self.string(key);
9996                        self.push(text);
9997                        self.push(Value::Bool(false));
9998                    }
9999                    None => {
10000                        self.push(Value::Undefined);
10001                        self.push(Value::Bool(true));
10002                    }
10003                }
10004            }
10005            ForOfStart => {
10006                let value = self.pop();
10007                let iterator = self.get_iterator(&value)?;
10008                self.push(iterator.object);
10009                self.push(iterator.next);
10010                self.push(Value::CatchOffset(0));
10011            }
10012            ForOfNext => {
10013                // `iter next catch_offset -> iter next catch_offset value done`.
10014                //
10015                // The operand is how many values sit *above* the iterator triple: a
10016                // destructuring rest element keeps its target array and running index
10017                // there while draining the iterator, so the triple is not at the top.
10018                let extra = a as usize;
10019                let iterator_slot = 2 + extra;
10020                // An exhausted iterator is replaced by `undefined` (see below), so a
10021                // second step must not call `next` again — `Array.from` and a
10022                // destructuring pattern both keep stepping past the end.
10023                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10024                    (Value::Undefined, true)
10025                } else {
10026                    let iterator = Iterator {
10027                        object: self.peek(iterator_slot),
10028                        next: self.peek(1 + extra),
10029                    };
10030                    self.iterator_step(&iterator)?
10031                };
10032                if done {
10033                    // The result's `value` is meaningless once the iterator is done:
10034                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10035                    // rather than binding the generator's return value.
10036                    let top = self.frame().stack.len() - 1 - iterator_slot;
10037                    self.frame_mut().stack[top] = Value::Undefined;
10038                    self.push(Value::Undefined);
10039                    self.push(Value::Bool(true));
10040                } else {
10041                    self.push(value);
10042                    self.push(Value::Bool(false));
10043                }
10044            }
10045            IteratorNext => {
10046                // `iter next catch val -> iter next catch val'`: replace the argument with
10047                // the result of `next(val)`. The triple below stays put, which is why the
10048                // three instructions of the `yield*` loop all address the stack the same way.
10049                let value = self.pop();
10050                let object = self.peek(2);
10051                let next = self.peek(1);
10052                let result = self.call_value(next, object, vec![value])?;
10053                self.push(result);
10054            }
10055            IteratorCall => {
10056                // `iter next catch val -> iter next catch val' flag`.
10057                //
10058                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10059                // The flag is `true` when the method was missing, which is how the
10060                // caller learns that the inner iterator cannot take part in the
10061                // unwinding.
10062                let value = self.pop();
10063                let object = self.peek(2);
10064                let key = if a & 1 != 0 { "throw" } else { "return" };
10065                let method = self.read_field(&object, key)?;
10066                if matches!(method, Value::Undefined | Value::Null) {
10067                    self.push(value);
10068                    self.push(Value::Bool(true));
10069                } else {
10070                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10071                    let result = self.call_value(method, object, argument)?;
10072                    self.push(result);
10073                    self.push(Value::Bool(false));
10074                }
10075            }
10076            IteratorCheckObject => {
10077                if !matches!(self.peek(0), Value::Object(_)) {
10078                    return Err(Signal::Throw(
10079                        self.make_error("TypeError", "iterator must return an object"),
10080                    ));
10081                }
10082            }
10083            IteratorClose => {
10084                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10085                // calling the iterator's `return` so it can release whatever it holds.
10086                //
10087                // The catch offset goes first, so an exception from `return` is not caught
10088                // by the loop being abandoned. This used to pop the three operands and call
10089                // nothing at all, which made `break` out of a `for of` invisible to an
10090                // iterator with a `return` method.
10091                self.pop();
10092                self.pop();
10093                let iterator = self.pop();
10094                if !matches!(iterator, Value::Undefined) {
10095                    let method = self.read_field(&iterator, "return")?;
10096                    if !matches!(method, Value::Undefined | Value::Null) {
10097                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10098                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10099                        if !matches!(result, Value::Object(_)) {
10100                            return Err(Signal::Throw(
10101                                self.make_error("TypeError", "iterator must return an object"),
10102                            ));
10103                        }
10104                    }
10105                }
10106            }
10107            Import => {
10108                // `import(specifier)`: the options slot is on top and is not read yet.
10109                let _options = self.pop();
10110                let specifier = self.pop();
10111                let promise = self.dynamic_import(specifier)?;
10112                self.push(promise);
10113            }
10114            ForAwaitOfStart => {
10115                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10116                // `Symbol.iterator` fallback.
10117                let value = self.pop();
10118                let iterator = self.get_async_iterator(&value)?;
10119                self.push(iterator.object);
10120                self.push(iterator.next);
10121                self.push(Value::CatchOffset(0));
10122            }
10123            ForAwaitOfNext => {
10124                // `for await` steps the iterator and leaves the *result* wrapped in a
10125                // promise, so the `await` the compiler emits right after this can suspend
10126                // on it. Unwrapping happens in `iterator_get_value_done`.
10127                let extra = a as usize;
10128                let iterator_slot = 2 + extra;
10129                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10130                    Value::Undefined
10131                } else {
10132                    let iterator = Iterator {
10133                        object: self.peek(iterator_slot),
10134                        next: self.peek(1 + extra),
10135                    };
10136                    let next = iterator.next.clone();
10137                    self.call_value(next, iterator.object, Vec::new())?
10138                };
10139                let promise = self.promise_resolve_value(result)?;
10140                self.push(promise);
10141            }
10142            IteratorGetValueDone => {
10143                // `result -> value done`. A missing result object means the iterator was
10144                // already exhausted, which the loop treats as `done`.
10145                let result = self.pop();
10146                let done = match &result {
10147                    Value::Object(object) => self
10148                        .get_property(object, "done")?
10149                        .is_some_and(|value| value.to_boolean()),
10150                    _ => true,
10151                };
10152                if done {
10153                    // Clear the iterator object so the `iterator_close` the loop emits on
10154                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10155                    // on normal completion, and this is where a normal completion is
10156                    // recognised — the same trick `for_of_next` uses, which also replaces
10157                    // the slot with `undefined`.
10158                    //
10159                    // The layout is fixed because only `for await` emits this opcode:
10160                    // `iter next catch [result]`, so the iterator is three below the top.
10161                    let depth = self.frame().stack.len();
10162                    if depth >= 3 {
10163                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10164                    }
10165                    self.push(Value::Undefined);
10166                    self.push(Value::Bool(true));
10167                } else {
10168                    let Value::Object(object) = &result else {
10169                        self.push(Value::Undefined);
10170                        self.push(Value::Bool(true));
10171                        return Ok(Step::Continue);
10172                    };
10173                    let value = self
10174                        .get_property(object, "value")?
10175                        .unwrap_or(Value::Undefined);
10176                    self.push(value);
10177                    self.push(Value::Bool(false));
10178                }
10179            }
10180
10181            Delete => {
10182                // `delete obj[key]`, where the key was just pushed. Deleting an array
10183                // index leaves a *hole* rather than closing the gap, and a
10184                // non-configurable property answers `false` and stays.
10185                let key = self.pop();
10186                let target = self.pop();
10187                let key = self.propkey(&key)?;
10188                let text_label = key.as_str().unwrap_or("").to_string();
10189                let deleted = match &target {
10190                    Value::Object(object) => {
10191                        let object = object.clone();
10192                        self.delete_property_key(&object, &key)?
10193                    }
10194                    // A string's `length` and its index properties are
10195                    // non-configurable, so deleting one answers `false`.
10196                    Value::String(text) => {
10197                        !(text_label == "length"
10198                            || array_index(&text_label)
10199                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10200                    }
10201                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10202                    // object to delete from, and only a *boxable* primitive has one.
10203                    Value::Undefined | Value::Null => {
10204                        return Err(Signal::Throw(
10205                            self.make_error("TypeError", "cannot convert to object"),
10206                        ));
10207                    }
10208                    // Any other primitive has no own properties; deleting nothing
10209                    // succeeds.
10210                    _ => true,
10211                };
10212                self.push(Value::Bool(deleted));
10213            }
10214
10215            // -- exceptions and bookkeeping ---------------------------------
10216            Fclosure | Fclosure8 => {
10217                let value = self.closure(a as usize)?;
10218                self.push(value);
10219            }
10220
10221            other => {
10222                let name = other.info().name;
10223                return Err(Signal::Throw(self.make_error(
10224                    "InternalError",
10225                    &format!("{name} is not implemented yet"),
10226                )));
10227            }
10228        }
10229        Ok(Step::Continue)
10230    }
10231
10232    // -- operand helpers ----------------------------------------------------
10233
10234    /// The slot index an operand names, taking short forms into account.
10235    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10236        use Opcode::*;
10237        match op {
10238            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10239            | SetVarRef0 => 0,
10240            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10241            | SetVarRef1 => 1,
10242            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10243            | SetVarRef2 => 2,
10244            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10245            | SetVarRef3 => 3,
10246            _ => a as usize,
10247        }
10248    }
10249
10250    /// The argument count of a call, taking `call0`…`call3` into account.
10251    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10252        use Opcode::*;
10253        match op {
10254            Call0 => 0,
10255            Call1 => 1,
10256            Call2 => 2,
10257            Call3 => 3,
10258            _ => a as usize,
10259        }
10260    }
10261
10262    /// The atom's name as a property key.
10263    ///
10264    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10265    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10266    /// `String::clone` was a heap allocation and a copy — per property access.
10267    /// The atom at `index`, as a property key.
10268    ///
10269    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10270    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10271    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10272    /// 5.3% of `property:monomorphic`.
10273    /// The atom's text, exactly — including an unpaired surrogate.
10274    ///
10275    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10276    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10277    /// `atom_text` below is for the other kind of use, where the atom is a key in the
10278    /// engine's own tables.
10279    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10280        self.frame()
10281            .code
10282            .code
10283            .atoms
10284            .get(index)
10285            .map(|atom| match atom {
10286                Atom::Str(text) => text.clone(),
10287                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10288                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10289                Atom::Null => crate::value::Wtf8::new(String::new()),
10290            })
10291            .unwrap_or_default()
10292    }
10293
10294    fn atom_text(&self, index: usize) -> String {
10295        self.frame()
10296            .code
10297            .code
10298            .atoms
10299            .get(index)
10300            .map(|atom| match atom {
10301                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10302                // compare it to an identifier, and a surrogate-bearing name is reachable
10303                // through `atom_wtf8` where it matters.
10304                Atom::Str(text) => text.to_string_lossy().into_owned(),
10305                Atom::Index(value) => value.to_string(),
10306                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10307                // `throw_error`, `delete super.x`) never read it.
10308                Atom::Null => String::new(),
10309            })
10310            .unwrap_or_default()
10311    }
10312
10313    fn constant(&mut self, index: usize) -> JsResult<Value> {
10314        let constant = self.frame().code.code.cpool.get(index).cloned();
10315        Ok(match &constant {
10316            Some(Constant::Number(number)) => Value::Float(*number),
10317            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10318            Some(Constant::BigInt { digits, radix }) => {
10319                match crate::bigint::BigInt::from_radix(digits, *radix) {
10320                    Some(big) => self.bigint(big),
10321                    // A literal the parser accepted is always parseable; a failure here
10322                    // would be a compiler bug, so it reads as an `InternalError`.
10323                    None => {
10324                        return Err(Signal::Throw(
10325                            self.make_error("InternalError", "unparseable bigint literal"),
10326                        ));
10327                    }
10328                }
10329            }
10330            Some(Constant::Function(_)) => {
10331                return Err(Signal::Throw(
10332                    self.make_error("InternalError", "a bare function constant"),
10333                ));
10334            }
10335            // A tagged template's call site: a frozen array of the cooked chunks with a
10336            // frozen `raw` array beside it, which is what `String.raw` reads back.
10337            Some(Constant::Template { cooked, raw }) => {
10338                let cooked_values: Vec<Value> = cooked
10339                    .iter()
10340                    .map(|chunk| match chunk {
10341                        Some(text) => self.string_wtf8(text.clone()),
10342                        None => Value::Undefined,
10343                    })
10344                    .collect();
10345                let raw_values: Vec<Value> =
10346                    raw.iter().map(|text| self.string(text.clone())).collect();
10347                let raw_array = self.new_array(raw_values);
10348                raw_array.set_extensible(false);
10349                let template = self.new_array(cooked_values);
10350                template.define(
10351                    "raw",
10352                    Property::with_attributes(Value::Object(raw_array), false, false),
10353                );
10354                template.set_extensible(false);
10355                Value::Object(template)
10356            }
10357            _ => Value::Undefined,
10358        })
10359    }
10360
10361    /// The reference cell a closure-variable slot names.
10362    ///
10363    /// Two kinds of binding share this addressing: a genuine closure variable
10364    /// (captured from an enclosing function) lives in this frame's environment,
10365    /// while a *declared global* lives in the realm so that a script, a function
10366    /// declaration and their uses all see one binding. A plain `Global` — an
10367    /// undeclared name that may be satisfied by the global object — has no cell at
10368    /// all, which is how `typeof x` still works for a name that does not exist.
10369    /// The reference cell a closure-variable slot names.
10370    ///
10371    /// The environment is resolved once, when the closure is built, and this is
10372    /// just the lookup afterwards. A *declared global* is in there too, pointing at
10373    /// the realm's cell, so a script, a hoisted function declaration and their uses
10374    /// all share one binding. A plain `Global` — a name the script never declared —
10375    /// is read and written through `get_var`/`put_var` by name instead, which is
10376    /// what lets the global object satisfy it.
10377    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10378        self.frame().env.cells.get(slot).cloned()
10379    }
10380
10381    /// Whether `slot` refers to a global binding through the reference table.
10382    ///
10383    /// A global's cell in the closure environment only exists so the slot has
10384    /// something to point at; the binding itself lives on the global object (a `var`)
10385    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10386    /// be routed, not performed on the placeholder.
10387    fn is_global_slot(&self, slot: usize) -> bool {
10388        self.frame()
10389            .code
10390            .code
10391            .closure_vars
10392            .get(slot)
10393            .is_some_and(|c| {
10394                // A module's declarations and imports are *not* globals: their cells are
10395                // the module environment's, filled by the host, so the placeholder routing
10396                // must not apply to them.
10397                matches!(
10398                    c.closure_type,
10399                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10400                )
10401            })
10402    }
10403
10404    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10405        if self.is_global_slot(slot) {
10406            return self.get_global(slot);
10407        }
10408        Ok(self
10409            .var_ref_cell(slot)
10410            .map(|cell| cell.get())
10411            .unwrap_or(Value::Undefined))
10412    }
10413
10414    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10415        // A function declaration is hoisted by storing into a global reference before
10416        // the body runs, so this path is also what puts it on the global object.
10417        if self.is_global_slot(slot) {
10418            return self.put_global(slot, value);
10419        }
10420        if let Some(cell) = self.var_ref_cell(slot) {
10421            cell.set(value);
10422        }
10423        Ok(())
10424    }
10425
10426    // -- closures -----------------------------------------------------------
10427
10428    /// Build the closure for the function constant `index`.
10429    ///
10430    /// Every entry in the child's closure table names where its binding lives in
10431    /// *this* frame: a local or argument slot that was marked captured, or a cell
10432    /// this frame is itself holding. That is how a variable three functions deep
10433    /// stays one binding.
10434    fn closure(&mut self, index: usize) -> JsResult<Value> {
10435        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10436        else {
10437            return Err(Signal::Throw(
10438                self.make_error("InternalError", "fclosure of a non-function"),
10439            ));
10440        };
10441        let mut cells = Vec::with_capacity(function.closure_vars.len());
10442        for closure_var in &function.closure_vars {
10443            let cell = match closure_var.closure_type {
10444                ClosureType::Arg => {
10445                    let slot = closure_var.var_idx as usize;
10446                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10447                }
10448                ClosureType::Local => {
10449                    let slot = closure_var.var_idx as usize;
10450                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10451                }
10452                ClosureType::Ref | ClosureType::GlobalRef => {
10453                    // A `Ref` names a cell in this frame's own closure table; a
10454                    // `GlobalRef` also starts there, then resolves by name below.
10455                    let slot = closure_var.var_idx as usize;
10456                    if let Some(cell) = self.frame().env.cells.get(slot) {
10457                        cells.push(cell.clone());
10458                        continue;
10459                    }
10460                    -1
10461                }
10462                _ => -1,
10463            };
10464            if cell >= 0 {
10465                let cell = self.frame().cells[cell as usize].clone();
10466                cells.push(cell);
10467                continue;
10468            }
10469            // A global: the cell is created on demand and shared through the realm,
10470            // so every function sees one binding.
10471            let name = closure_var.name.clone();
10472            let cell = match self.realm.globals.get(&name) {
10473                Some(cell) => cell.clone(),
10474                None => {
10475                    let cell = self.new_cell(Value::Undefined);
10476                    self.realm.globals.insert(name.clone(), cell.clone());
10477                    cell
10478                }
10479            };
10480            cells.push(cell);
10481        }
10482        let name = function.name.clone();
10483        // `.length` is the arity before any default or rest parameter, not the number
10484        // of slots a pattern parameter needs.
10485        let length = function.defined_args;
10486        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10487        // function and an arrow function do not. A *method* also does not, but that is not
10488        // known here — the method is marked when the `[[HomeObject]]` is attached (see
10489        // `set_home_object`), which is the moment it becomes a method.
10490        let function_kind = function.kind;
10491        let constructible =
10492            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10493        let code = Gc::new(self.heap, CompiledCode::new(*function));
10494        // A closure built inside an `eval` inherits the eval's view of the enclosing
10495        // bindings, so it can still read them once the eval has returned.
10496        let eval_scope = self
10497            .active_eval_scope
10498            .clone()
10499            .or_else(|| self.frame().env.eval_scope.clone());
10500        // A closure sees the variables a direct `eval` declared in the frame it was
10501        // created in — the ones declared before *and after* it, so the same object is
10502        // shared; only the phase bounds which of them are visible.
10503        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10504        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10505        let env = Gc::new(
10506            self.heap,
10507            ClosureEnv {
10508                cells,
10509                eval_scope,
10510                local_vars,
10511                local_phase,
10512            },
10513        );
10514        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10515        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10516        // the only thing that carries `Symbol.toStringTag`, so without it
10517        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10518        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10519        let proto = match function_kind {
10520            js_compile::bytecode::FunctionKind::AsyncGenerator => self
10521                .realm
10522                .async_generator_function_proto
10523                .clone()
10524                .or_else(|| self.realm.function_proto.clone().into()),
10525            js_compile::bytecode::FunctionKind::Generator => self
10526                .realm
10527                .generator_function_proto
10528                .clone()
10529                .or_else(|| self.realm.function_proto.clone().into()),
10530            js_compile::bytecode::FunctionKind::Async => self
10531                .realm
10532                .async_function_proto
10533                .clone()
10534                .or_else(|| self.realm.function_proto.clone().into()),
10535            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10536        };
10537        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10538        object.set_constructible(constructible);
10539        object.define(
10540            "length",
10541            Property::name_or_length(Value::Int(length as i32)),
10542        );
10543        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10544        // that checks the own-property descriptor fails if the property is missing.
10545        object.define("name", Property::name_or_length(self.string(name)));
10546        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10547        // when `[[Construct]]` is created, so a generator, an async function and an arrow
10548        // function have none of their own. Installing it unconditionally gave
10549        // `Array.fromAsync` (an async function) an own `prototype` property, which
10550        // `builtin.js` checks for absence.
10551        if constructible {
10552            self.install_function_prototype(&object);
10553        }
10554        Ok(Value::Object(object))
10555    }
10556
10557    // -- conversions used by the operators ----------------------------------
10558
10559    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10560        // `+x` is `ToNumber`, which for a string parses it and for an object runs
10561        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10562        // string, which then behaves differently in every later comparison.
10563        match value {
10564            Value::Int(_) | Value::Float(_) => Ok(value),
10565            other => Ok(Value::Float(self.to_js_number(&other)?)),
10566        }
10567    }
10568
10569    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10570    ///
10571    /// Returns the *converted* old value and the new one, because the two callers need
10572    /// different halves: `++x` yields the new value, while `x++` yields the old one and
10573    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10574    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10575    /// boolean.
10576    ///
10577    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10578    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10579    /// a bigint algorithm then ran exactly once.
10580    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10581        if let Value::BigInt(big) = &value {
10582            let one = crate::bigint::BigInt::from_i64(1);
10583            let next = if up { big.add(&one) } else { big.sub(&one) };
10584            return Ok((value, self.bigint(next)));
10585        }
10586        let old = self.numeric(value)?;
10587        let new = if up {
10588            increment(old.clone())
10589        } else {
10590            decrement(old.clone())
10591        };
10592        Ok((old, new))
10593    }
10594
10595    fn numeric(&mut self, value: Value) -> JsResult<Value> {
10596        // `ToNumber` on an object runs `ToPrimitive` first, which is how
10597        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10598        // heard at all. Reading the object's own tag instead (`other.to_number()`)
10599        // turned the whole operand into `NaN` and swallowed the exception.
10600        match value {
10601            Value::Int(_) | Value::Float(_) => Ok(value),
10602            other => Ok(Value::Float(self.to_js_number(&other)?)),
10603        }
10604    }
10605
10606    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10607    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10608        match value {
10609            Value::BigInt(big) => Ok((**big).clone()),
10610            // The reference words this the same way for every operator, so a failing
10611            // script reads identically; the operator itself adds nothing a caller can use.
10612            _ => Err(Signal::Throw(
10613                self.make_error("TypeError", "cannot convert bigint to number"),
10614            )),
10615        }
10616    }
10617
10618    /// Arithmetic where at least one operand is a `BigInt`.
10619    ///
10620    /// The two numeric types never mix, so a bigint paired with anything else is an error
10621    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10622    /// that the relational operators handle it separately.
10623    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10624        use Opcode::*;
10625        let a = self.bigint_operand(&left)?;
10626        let b = self.bigint_operand(&right)?;
10627        let result = match op {
10628            Add => a.add(&b),
10629            Sub => a.sub(&b),
10630            Mul => a.mul(&b),
10631            Div | Mod => {
10632                let Some((quotient, remainder)) = a.div_rem(&b) else {
10633                    return Err(Signal::Throw(
10634                        self.make_error("RangeError", "division by zero"),
10635                    ));
10636                };
10637                if op == Div { quotient } else { remainder }
10638            }
10639            Pow => {
10640                let Some(value) = a.pow(&b) else {
10641                    return Err(Signal::Throw(self.make_error(
10642                        "RangeError",
10643                        "BigInt exponent must be non-negative and not absurdly large",
10644                    )));
10645                };
10646                value
10647            }
10648            And => a.bitand(&b),
10649            Or => a.bitor(&b),
10650            Xor => a.bitxor(&b),
10651            Shl | Sar => {
10652                // A shift count is a `BigInt` here, and both directions are exact; a
10653                // negative count would be the other direction, which the spec forbids.
10654                let Some(count) = b.to_i64() else {
10655                    return Err(Signal::Throw(
10656                        self.make_error("RangeError", "BigInt shift count is too large"),
10657                    ));
10658                };
10659                if count < 0 {
10660                    return Err(Signal::Throw(self.make_error(
10661                        "RangeError",
10662                        "BigInt shift count must be non-negative",
10663                    )));
10664                }
10665                if op == Shl {
10666                    a.shl(count as u64)
10667                } else {
10668                    a.shr(count as u64)
10669                }
10670            }
10671            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10672            _ => {
10673                return Err(Signal::Throw(self.make_error(
10674                    "TypeError",
10675                    "BigInts have no unsigned right shift, use >> instead",
10676                )));
10677            }
10678        };
10679        Ok(self.bigint(result))
10680    }
10681
10682    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10683    ///
10684    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10685    /// is on the mathematical values, and nothing is rounded first.
10686    /// `<`, `<=`, `>`, `>=`.
10687    ///
10688    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10689    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10690    /// It is a `?`-returning function for exactly that reason: an object operand can run
10691    /// script, and script can throw. The old version compared `to_number` of the raw
10692    /// values, which answered `false` for every object instead of calling `valueOf` —
10693    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10694    /// never ran.
10695    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10696        // The hot arm first: `i < n` with both sides already integers. No conversion, no
10697        // call, nothing that can throw.
10698        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10699            let ordering = Some(left.cmp(right));
10700            return Ok(ordering_answer(op, ordering));
10701        }
10702        // Anything that can run script has to be converted first, in this order.
10703        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10704        {
10705            (
10706                self.to_primitive(left, Hint::Number)?,
10707                self.to_primitive(right, Hint::Number)?,
10708            )
10709        } else {
10710            (left, right)
10711        };
10712        let ordering = match (&left, &right) {
10713            // The loop condition `i < n` is integer against integer, and it runs once
10714            // per iteration of every loop in every program. Without this arm it took the
10715            // `to_number` path twice, which is a `match` plus a conversion each.
10716            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10717            (Value::String(a), Value::String(b)) => {
10718                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10719            }
10720            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10721            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10722            // is true even though `2.5` has no bigint form.
10723            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10724                let b = other.to_number();
10725                if b.is_nan() {
10726                    None
10727                } else {
10728                    compare_bigint_and_f64(a, b)
10729                }
10730            }
10731            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10732                let a = other.to_number();
10733                if a.is_nan() {
10734                    None
10735                } else {
10736                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10737                }
10738            }
10739            _ => left.to_number().partial_cmp(&right.to_number()),
10740        };
10741        Ok(ordering_answer(op, ordering))
10742    }
10743
10744    fn binary_add(&mut self) -> JsResult<()> {
10745        let right = self.pop();
10746        let left = self.pop();
10747        // Two integers add without any of the machinery below: no `ToPrimitive` (an
10748        // `Int` is already primitive), no string check, no bigint check, no allocation.
10749        // `x += 1` in a loop is the single most common instruction sequence in real
10750        // script, and it used to walk every one of those checks before reaching the
10751        // same `checked_add`.
10752        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10753            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10754            return Ok(());
10755        }
10756        let left = self.primitive_of(left)?;
10757        let right = self.primitive_of(right)?;
10758        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10759        // that check comes before the bigint one: `"" + 1n` is a string, not a
10760        // mixed-type error.
10761        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10762            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10763            // `TypeError`, the one place a symbol and a string do not mix.
10764            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10765            // between a copy and a rope from their lengths, and a rope is what turns
10766            // `text += "abc"` in a loop from quadratic into linear.
10767            if let (Value::String(left), Value::String(right)) = (&left, &right) {
10768                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10769                // reports as `InternalError: string too long`.
10770                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10771                    return Err(Signal::Throw(
10772                        self.make_error("InternalError", "string too long"),
10773                    ));
10774                };
10775                self.push(Value::String(Gc::new(self.heap, joined)));
10776                return Ok(());
10777            }
10778            // At least one operand was not a string, so `ToString` it. This rejects a
10779            // symbol, which is the one place a symbol and a string do not mix.
10780            let left = self.checked_to_wtf8(&left)?;
10781            let right = self.checked_to_wtf8(&right)?;
10782            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
10783            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
10784            let text = left.concat(&right);
10785            self.push(self.string_wtf8(text));
10786            return Ok(());
10787        }
10788        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
10789        // not a conversion.
10790        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
10791            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
10792            self.push(value);
10793            return Ok(());
10794        }
10795        let left = self.numeric(left)?;
10796        let right = self.numeric(right)?;
10797        self.push(add_numbers(left, right));
10798        Ok(())
10799    }
10800
10801    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
10802        self.to_primitive(value, Hint::Default)
10803    }
10804
10805    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
10806    ///
10807    /// The order depends on the hint: the "number" order tries `valueOf` first and
10808    /// `toString` second, the "string" order the other way round, and the default
10809    /// hint uses the number order. A result that is still an object is a `TypeError`,
10810    /// because no built-in `valueOf`/`toString` returns one.
10811    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
10812        let Value::Object(object) = &value else {
10813            return Ok(value);
10814        };
10815        // A Date overrides the default hint to mean "string", which is what
10816        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
10817        // this, `"" + new Date()` would print the milliseconds, not the date.
10818        let hint = if hint == Hint::Default && is_date_object(self, object) {
10819            Hint::String
10820        } else {
10821            hint
10822        };
10823        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
10824        // handed the hint as a string. This is the hook a Date uses for its default hint
10825        // and a script uses to take over conversion entirely.
10826        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
10827        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
10828            if !function.is_callable() {
10829                return Err(self.type_error("Symbol.toPrimitive is not a function"));
10830            }
10831            let hint = match hint {
10832                Hint::String => "string",
10833                Hint::Number => "number",
10834                Hint::Default => "default",
10835            };
10836            let hint = self.string(hint);
10837            let result = self.call_value(
10838                Value::Object(function),
10839                Value::Object(object.clone()),
10840                vec![hint],
10841            )?;
10842            if matches!(result, Value::Object(_)) {
10843                return Err(self.type_error("cannot convert object to primitive value"));
10844            }
10845            return Ok(result);
10846        }
10847        let order: [&str; 2] = match hint {
10848            Hint::String => ["toString", "valueOf"],
10849            Hint::Number | Hint::Default => ["valueOf", "toString"],
10850        };
10851        let receiver = object.clone();
10852        for method in order {
10853            if let Some(function) = self.get_property(&receiver, method)?
10854                && matches!(&function, Value::Object(object) if object.is_callable())
10855            {
10856                let result =
10857                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
10858                if !matches!(result, Value::Object(_)) {
10859                    return Ok(result);
10860                }
10861            }
10862        }
10863        Err(self.type_error("cannot convert object to primitive value"))
10864    }
10865
10866    /// `ToString` with the object case going through `ToPrimitive`.
10867    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
10868        if matches!(value, Value::Object(_)) {
10869            let primitive = self.to_primitive(value.clone(), Hint::String)?;
10870            return Ok(primitive.to_js_string());
10871        }
10872        Ok(value.to_js_string())
10873    }
10874
10875    /// `ToString` that keeps the string's code units instead of flattening them.
10876    ///
10877    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
10878    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
10879    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10880        if matches!(value, Value::Symbol(_)) {
10881            return Err(Signal::Throw(
10882                self.make_error("TypeError", "cannot convert symbol to string"),
10883            ));
10884        }
10885        // An object runs `ToPrimitive` first, which may itself produce a symbol.
10886        let value = self.to_primitive(value.clone(), Hint::String)?;
10887        match value {
10888            Value::Symbol(_) => Err(Signal::Throw(
10889                self.make_error("TypeError", "cannot convert symbol to string"),
10890            )),
10891            Value::String(text) => Ok(text.wtf8().clone()),
10892            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
10893        }
10894    }
10895
10896    /// `ToNumber` with the object case going through `ToPrimitive`.
10897    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
10898        let value = if matches!(value, Value::Object(_)) {
10899            self.to_primitive(value.clone(), Hint::Number)?
10900        } else {
10901            value.clone()
10902        };
10903        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
10904        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
10905        // `NaN` to stay total, and the operators check for the bigint themselves — but
10906        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
10907        // refuse, and answering `NaN` made them silently wrong instead.
10908        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
10909        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
10910        match value {
10911            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
10912            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
10913            other => Ok(other.to_number()),
10914        }
10915    }
10916
10917    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
10918    /// [`ElementType::write`].
10919    ///
10920    /// This is separated from the write because both conversions are observable script —
10921    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
10922    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
10923    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
10924    /// setters, and a plain `a[i] = v`.
10925    pub(crate) fn element_value(
10926        &mut self,
10927        element: crate::builtins::typedarray::ElementType,
10928        value: Value,
10929    ) -> JsResult<Value> {
10930        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
10931        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
10932        let primitive = match &value {
10933            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
10934            _ => value,
10935        };
10936        if element.is_bigint() {
10937            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
10938            Ok(Value::BigInt(Gc::new(self.heap, big)))
10939        } else {
10940            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
10941            Ok(Value::Float(self.to_js_number(&primitive)?))
10942        }
10943    }
10944
10945    /// `ToPropertyKey`: what a computed member access uses as its key.
10946    ///
10947    /// A symbol is returned as itself, never stringified — that is what keeps
10948    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
10949    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
10950        match value {
10951            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
10952            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
10953            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
10954            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
10955            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10956                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
10957                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
10958                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
10959                    other.to_js_string(),
10960                ))),
10961            },
10962            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
10963        }
10964    }
10965
10966    /// `ToPropertyKey` for the callers that can only use a string key.
10967    ///
10968    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
10969    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
10970    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
10971    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
10972    /// program continues with a value nobody asked for.
10973    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10974        use crate::value::Wtf8;
10975        Ok(match value {
10976            // A string key keeps its code units. Going through a lossy `String` would make
10977            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
10978            Value::String(text) => text.wtf8().clone(),
10979            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
10980            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
10981            // falling back to its `ToString` would print `[object Object]`.
10982            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10983                Value::String(text) => text.wtf8().clone(),
10984                other => Wtf8::new(other.to_js_string()),
10985            },
10986            other => Wtf8::new(other.to_js_string()),
10987        })
10988    }
10989
10990    // -- object operations used by instructions -----------------------------
10991
10992    /// Read `object[key]`, returning `undefined` when the property is missing.
10993    ///
10994    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
10995    /// primitive (looking through its prototype) as well as an object — which is what
10996    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
10997    /// argument needs too.
10998    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
10999        self.read_field_key(object, &PropertyKey::from(key))
11000    }
11001
11002    /// [`Interp::read_field`] with a key that may be a symbol.
11003    ///
11004    /// A symbol key never reaches the string shortcuts: a string's `length` and its
11005    /// indices are string properties, and a symbol named `length` is a different
11006    /// property that a string primitive cannot have.
11007    /// [`Interp::read_field_key`], with an inline cache in front of it.
11008    ///
11009    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11010    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11011    /// without this the engine walked the chain and compared ~40 property names on each
11012    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11013    ///
11014    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11015    /// missing property. Those answers depend on running code or on state the guard below
11016    /// does not cover, and a wrong answer here is far more expensive than a lookup.
11017    ///
11018    /// A hit is re-validated against the *whole* walked chain, not just the level that
11019    /// answered: the receiver and every prototype down to that level must still be the same
11020    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11021    /// property-table *lengths* — which is what catches a property appearing on an
11022    /// intermediate prototype and shadowing the cached one.
11023    pub fn read_field_cached(
11024        &mut self,
11025        object: &Value,
11026        key: &PropertyKey,
11027        slot: usize,
11028    ) -> JsResult<Value> {
11029        let index = Self::field_cache_slot(object, key, slot);
11030        let Value::Object(target) = object else {
11031            return self.read_field_key(object, key);
11032        };
11033        if target.proxy_state().is_some() {
11034            return self.read_field_key(object, key);
11035        }
11036        if let Some(cached) = &self.field_cache[index]
11037            && cached.key == *key
11038            && let Some(value) = Self::cached_hit(target, cached)
11039        {
11040            return Ok(value);
11041        }
11042        let value = self.read_field_key(object, key)?;
11043        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11044        Ok(value)
11045    }
11046
11047    /// Whether a cache entry still describes this lookup, and if so the value.
11048    ///
11049    /// The guard is the whole point of the entry: identity plus property-table length for
11050    /// every level walked. Re-checked per level rather than once at the receiving end,
11051    /// because a shadowing property can appear anywhere along the chain.
11052    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11053        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11054        // starts with: a clone is a reference-count bump and a drop, and for
11055        // `property:monomorphic` every single hit takes only this arm.
11056        let (weak, len) = cached.chain[0].as_ref()?;
11057        if !target.upgrades_to(weak) {
11058            return None;
11059        }
11060        if cached.level == 0 {
11061            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11062            return target.cached_property_at(cached.index, &cached.key, *len);
11063        }
11064        if target.props_len() != *len {
11065            return None;
11066        }
11067        let mut level = 1;
11068        let mut current = target.proto()?;
11069        loop {
11070            let (weak, len) = cached.chain[level].as_ref()?;
11071            if !current.upgrades_to(weak) || current.props_len() != *len {
11072                return None;
11073            }
11074            if level == cached.level as usize {
11075                // The level that answered: the value is only reusable while the key is
11076                // still there and still a plain data property.
11077                return current.cached_data_property(cached.index, &cached.key);
11078            }
11079            current = current.proto()?;
11080            level += 1;
11081        }
11082    }
11083
11084    /// Build a cache entry for a lookup that just went through the slow path.
11085    ///
11086    /// Records the chain only when the answer came from a plain data property at a level
11087    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11088    /// costs the next lookup the walk it would have cost anyway.
11089    fn record_field_lookup(
11090        target: &Gc<JsObject>,
11091        key: &PropertyKey,
11092        _value: Value,
11093    ) -> Option<FieldCache> {
11094        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11095            [None, None, None];
11096        let mut current = target.clone();
11097        for level in 0..MAX_CACHED_CHAIN {
11098            chain[level] = Some((current.downgrade(), current.props_len()));
11099            if let Some((found, _)) = current.own_property_index(key) {
11100                // `own_property_index` declines an accessor and a hole, which is exactly
11101                // the set that must not be cached.
11102                return Some(FieldCache {
11103                    key: key.clone(),
11104                    index: found,
11105                    level: level as u8,
11106                    chain,
11107                });
11108            }
11109            current = current.proto()?;
11110        }
11111        None
11112    }
11113
11114    /// Which cache slot a lookup uses.
11115    ///
11116    /// Mixes the object's address, the name and the site, so that two properties of one
11117    /// object, and one property of two objects, land in different slots — which is what lets
11118    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11119    /// other iteration.
11120    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11121        let mut hash = match object {
11122            Value::Object(object) => object.address(),
11123            _ => 0,
11124        };
11125        hash = hash
11126            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11127            .rotate_left(17)
11128            .wrapping_add(key.hash_code());
11129        hash = hash.wrapping_add(site.wrapping_mul(31));
11130        // The table is a power of two, so the low bits are the slot.
11131        hash & (FIELD_CACHE_SLOTS - 1)
11132    }
11133
11134    /// Read `key` from `object`, without the inline cache.
11135    ///
11136    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11137    /// prototype chain, while the cached form answers an own data property from memory.
11138    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11139        let text = key.as_str().unwrap_or("");
11140        let Value::Object(object) = object else {
11141            // Reading a property of `undefined`/`null` is the classic TypeError.
11142            if object.is_nullish() {
11143                return Err(Signal::Throw(self.make_error(
11144                    "TypeError",
11145                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11146                )));
11147            }
11148            // A string has `length` and index access without being boxed.
11149            if let Value::String(value) = object {
11150                if text == "length" {
11151                    return Ok(Value::Int(value.utf16_len() as i32));
11152                }
11153                if let Some(index) = array_index(text) {
11154                    return Ok(match value.wtf8().unit_at(index as usize) {
11155                        Some(unit) => self.string_wtf8(unit),
11156                        None => Value::Undefined,
11157                    });
11158                }
11159            }
11160            // A property of a primitive is looked up on its prototype: this is what
11161            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11162            let prototype = match object {
11163                Value::String(_) => self.realm.string_proto.clone(),
11164                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11165                Value::Bool(_) => self.realm.boolean_proto.clone(),
11166                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11167                // `sym.description` reads through the prototype, not off the symbol.
11168                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11169                // …and a bigint's on `BigInt.prototype`, which is how
11170                // `(255n).toString(16)` reaches its method.
11171                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11172                _ => None,
11173            };
11174            if let Some(prototype) = prototype
11175                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11176            {
11177                return Ok(value);
11178            }
11179            return Ok(Value::Undefined);
11180        };
11181        Ok(self
11182            .get_property_key(object, key)?
11183            .unwrap_or(Value::Undefined))
11184    }
11185
11186    /// The `#name` a private symbol stands for, for error messages.
11187    ///
11188    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11189    /// was made from.
11190    fn private_name(symbol: &Value) -> Option<String> {
11191        match symbol {
11192            Value::Symbol(symbol) if symbol.is_private() => Some(
11193                symbol
11194                    .description()
11195                    .map(|text| text.to_string())
11196                    .unwrap_or_default(),
11197            ),
11198            _ => None,
11199        }
11200    }
11201
11202    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11203    ///
11204    /// Every private-field opcode takes the symbol the class stored in its own scope; a
11205    /// non-symbol here would be a compiler bug, and the reference guards it with
11206    /// `JS_ThrowTypeErrorNotASymbol`.
11207    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11208        match symbol {
11209            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11210            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11211        }
11212    }
11213
11214    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11215    ///
11216    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11217    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11218    /// would hit if the parser did not reject it first.
11219    fn define_private_field(
11220        &mut self,
11221        object: &Value,
11222        symbol: &Value,
11223        value: Value,
11224    ) -> JsResult<()> {
11225        let key = self.private_key(symbol)?;
11226        let Some(target) = object.as_object() else {
11227            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11228        };
11229        if !target.is_extensible() {
11230            return Err(Signal::Throw(
11231                self.make_error("TypeError", "object is not extensible"),
11232            ));
11233        }
11234        if target.own_property_key(&key).is_some() {
11235            let name = Self::private_name(symbol).unwrap_or_default();
11236            return Err(Signal::Throw(self.make_error(
11237                "TypeError",
11238                &format!("private class field '{name}' already exists"),
11239            )));
11240        }
11241        target.define_data_key(&key, value);
11242        Ok(())
11243    }
11244
11245    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11246    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11247        let key = self.private_key(symbol)?;
11248        let Some(target) = object.as_object() else {
11249            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11250        };
11251        match target.own_property_key(&key) {
11252            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11253            None => {
11254                let name = Self::private_name(symbol).unwrap_or_default();
11255                Err(Signal::Throw(self.make_error(
11256                    "TypeError",
11257                    &format!("private class field '{name}' does not exist"),
11258                )))
11259            }
11260        }
11261    }
11262
11263    /// `JS_SetPrivateField`: the store half of the same rule.
11264    fn write_private_field(
11265        &mut self,
11266        object: &Value,
11267        symbol: &Value,
11268        value: Value,
11269    ) -> JsResult<()> {
11270        let key = self.private_key(symbol)?;
11271        let Some(target) = object.as_object() else {
11272            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11273        };
11274        if target.write_value_key(&key, value) {
11275            return Ok(());
11276        }
11277        let name = Self::private_name(symbol).unwrap_or_default();
11278        Err(Signal::Throw(self.make_error(
11279            "TypeError",
11280            &format!("private class field '{name}' does not exist"),
11281        )))
11282    }
11283
11284    /// The `in` half: does `object` have this private field?
11285    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11286    ///
11287    /// The symbol is created once per class — the first `add_brand` on a given home object
11288    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11289    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11290    /// emit for the *instance* brand passes null because all it wants is the symbol.
11291    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11292        let Some(home_object) = home.as_object() else {
11293            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11294        };
11295        let symbol = match home_object.private_brand() {
11296            Some(symbol) => symbol,
11297            None => {
11298                let symbol = Gc::new(
11299                    self.heap,
11300                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11301                );
11302                home_object.set_private_brand(symbol.clone());
11303                symbol
11304            }
11305        };
11306        let Some(target) = object.as_object() else {
11307            // Not an object: nothing to brand. The reference does the same, and `undefined`
11308            // here would otherwise turn a field initialiser into a TypeError.
11309            return Ok(());
11310        };
11311        if !target.is_extensible() {
11312            return Err(Signal::Throw(
11313                self.make_error("TypeError", "object is not extensible"),
11314            ));
11315        }
11316        if target.carries_brand(&symbol) {
11317            return Err(Signal::Throw(
11318                self.make_error("TypeError", "private method is already present"),
11319            ));
11320        }
11321        target.add_brand(symbol);
11322        Ok(())
11323    }
11324
11325    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11326    ///
11327    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11328    /// decides whether to throw.
11329    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11330        let Some(function) = function.as_object() else {
11331            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11332        };
11333        let Some(home) = function.home_object() else {
11334            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11335        };
11336        let Some(brand) = home.private_brand() else {
11337            return Err(Signal::Throw(
11338                self.make_error("TypeError", "expecting <brand> private field"),
11339            ));
11340        };
11341        Ok(object.carries_brand(&brand))
11342    }
11343
11344    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11345        let Value::Object(object) = object else {
11346            return Err(Signal::Throw(self.make_error(
11347                "TypeError",
11348                &format!("cannot set property '{key}' of {}", object.to_js_string()),
11349            )));
11350        };
11351        // The write half of the property inline cache, in effect: an own, writable,
11352        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11353        // decide — no prototype walk (an own property shadows the chain before a setter
11354        // there could matter), no extensibility check (the object already has the key),
11355        // and no `[[DefineOwnProperty]]`.
11356        //
11357        // `this.value = …` inside a method is the whole write side of
11358        // `property:method-call`, and it was reaching `set_property_with_key` with its
11359        // proxy test, its typed-array test, its array-index test and finally a linear
11360        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11361        //
11362        // Every disqualifier is checked here: a proxy traps the set, an array index and
11363        // `length` live outside the property table, and a typed array's element is stored
11364        // through its view's element type.
11365        if object.proxy_state().is_none()
11366            && !object.is_array()
11367            && object.typed_array_element_type().is_none()
11368            && object.write_value_key(key, value.clone())
11369        {
11370            return Ok(());
11371        }
11372        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11373        let on_failure = if self.frame().code.code.strict {
11374            DeleteFailure::Throw
11375        } else {
11376            DeleteFailure::Ignore
11377        };
11378        self.set_property_with_key(object, key, value, on_failure)
11379    }
11380
11381    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11382    ///
11383    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11384    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11385    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11386    /// `Number.parseInt(sym)` — so those callers use this instead.
11387    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11388        if matches!(value, Value::Symbol(_)) {
11389            return Err(Signal::Throw(
11390                self.make_error("TypeError", "cannot convert symbol to string"),
11391            ));
11392        }
11393        // An object runs `ToPrimitive` first, which may itself produce a symbol —
11394        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11395        let value = self.to_primitive(value.clone(), Hint::String)?;
11396        if matches!(value, Value::Symbol(_)) {
11397            return Err(Signal::Throw(
11398                self.make_error("TypeError", "cannot convert symbol to string"),
11399            ));
11400        }
11401        Ok(value.to_js_string())
11402    }
11403
11404    /// `ToPropertyKey` for a builtin that takes a key argument.
11405    ///
11406    /// Fallible: a key whose `toString` throws has to propagate that error, both for
11407    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11408    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11409    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11410    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11411        self.propkey(value)
11412    }
11413
11414    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11415    ///
11416    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11417    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11418    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11419    /// `RangeError` — and why this cannot be a plain `ToNumber`.
11420    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11421        let number = match value {
11422            Value::Int(number) => *number as f64,
11423            Value::Float(number) => *number,
11424            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11425            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11426            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11427            // reference answers 0.
11428            Value::Null | Value::Bool(_) => value.to_number(),
11429            _ => {
11430                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11431                match primitive {
11432                    Value::Int(number) => number as f64,
11433                    Value::Float(number) => number,
11434                    other => {
11435                        // `ToString` then `ToNumber`, so a string length goes through the
11436                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
11437                        // `Value::to_number` on the string already implements exactly that.
11438                        let text = self.to_js_string(&other)?;
11439                        crate::value::string_to_number(&text)
11440                    }
11441                }
11442            }
11443        };
11444        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11445        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11446        // is a `RangeError`, not `0`.
11447        if !number.is_finite()
11448            || number.fract() != 0.0
11449            || !(0.0..=u32::MAX as f64).contains(&number)
11450        {
11451            return Err(self.range_error("invalid array length"));
11452        }
11453        Ok(number as u32)
11454    }
11455
11456    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11457    /// `Object.getOwnPropertySymbols` put in their result array.
11458    pub fn key_value(&self, key: &PropertyKey) -> Value {
11459        match key {
11460            PropertyKey::String(text) => self.string_wtf8(text.clone()),
11461            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11462        }
11463    }
11464
11465    /// Fill in a String exotic object: `_value`, `length` and the index properties.
11466    ///
11467    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11468    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11469    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11470    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11471    /// the two paths had drifted; this is the one both now use.
11472    ///
11473    /// The indices are *code units*, so an astral character occupies two of them — the
11474    /// same rule `s.length` and `s[i]` follow.
11475    /// Give an already-created object the internal slot that makes it a wrapper of
11476    /// `value`, so the primitive's prototype methods work on it.
11477    ///
11478    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11479    /// which are wrappers of their own type holding the empty value.
11480    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11481        self.internal_set(object, "_value", value);
11482    }
11483
11484    pub(crate) fn init_string_wrapper(
11485        &mut self,
11486        object: &Gc<JsObject>,
11487        text: &Gc<crate::value::JsString>,
11488    ) {
11489        object.define(
11490            "length",
11491            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11492        );
11493        for index in 0..text.utf16_len() {
11494            if let Some(unit) = text.wtf8().unit_at(index) {
11495                object.define(
11496                    &index.to_string(),
11497                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11498                    Property::with_attributes(self.string_wtf8(unit), false, true),
11499                );
11500            }
11501        }
11502        object.define_key(
11503            &self.internal_slot("_value"),
11504            Property::with_attributes(Value::String(text.clone()), false, false),
11505        );
11506    }
11507
11508    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11509    ///
11510    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11511    /// throws. The wrapper carries its primitive in `_value` — the same slot
11512    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11513    /// on a boxed value no constructor ever built.
11514    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11515        let (prototype, primitive) = match value {
11516            Value::Object(object) => return Ok(object.clone()),
11517            Value::String(text) => {
11518                let object = self.new_object(self.realm.string_proto.clone());
11519                self.init_string_wrapper(&object, text);
11520                return Ok(object);
11521            }
11522            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11523            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11524            // A symbol and a bigint box into wrappers whose methods live on
11525            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11526            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11527            // branch below instead produced an object with *no* prototype, so those
11528            // methods were unreachable on a box.
11529            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11530            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11531            Value::Undefined | Value::Null => {
11532                return Err(Signal::Throw(self.make_error(
11533                    "TypeError",
11534                    &format!("cannot convert {} to object", value.to_js_string()),
11535                )));
11536            }
11537            _ => (None, value.clone()),
11538        };
11539        let object = self.new_object(prototype);
11540        self.internal_set(&object, "_value", primitive);
11541        Ok(object)
11542    }
11543
11544    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11545    ///
11546    /// Split out for a reader that has to create the object *before* it knows what it wraps:
11547    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11548    /// written before its primitive, so the placeholder has to exist first and be filled in
11549    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11550    /// than a second in the deserialiser.
11551    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11552        let prototype = match value {
11553            Value::String(_) => self.realm.string_proto.clone(),
11554            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11555            Value::Bool(_) => self.realm.boolean_proto.clone(),
11556            Value::Symbol(_) => self.realm.symbol_proto.clone(),
11557            Value::BigInt(_) => self.realm.bigint_proto.clone(),
11558            _ => {
11559                return Err(Signal::Throw(self.make_error(
11560                    "TypeError",
11561                    &format!("cannot box {}", value.to_js_string()),
11562                )));
11563            }
11564        };
11565        object.set_proto(prototype);
11566        if let Value::String(text) = value {
11567            self.init_string_wrapper(object, text);
11568            return Ok(());
11569        }
11570        self.internal_set(object, "_value", value.clone());
11571        Ok(())
11572    }
11573
11574    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11575    ///
11576    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11577    /// through the `Symbol` function object, so the registry is reachable as a method rather
11578    /// than only from `builtins::symbol`.
11579    pub fn symbol_for(&mut self, key: &str) -> Value {
11580        if let Some(existing) = self.realm.symbol_registry.get(key) {
11581            return existing.clone();
11582        }
11583        let symbol = crate::builtins::symbol::symbol_value(
11584            self,
11585            crate::value::JsSymbol::registered(key.to_string()),
11586        );
11587        self.realm
11588            .symbol_registry
11589            .insert(key.to_string(), symbol.clone());
11590        symbol
11591    }
11592
11593    /// `a == b`, the coercing comparison.
11594    ///
11595    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11596    /// which is what makes `[] == ""` true: `[]` becomes `""` via
11597    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11598    /// because the conversion is allowed to call script code, so the two primitive
11599    /// operands are handed back to it.
11600    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11601        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11602            return Ok(left.loose_equals(&right));
11603        }
11604        // `null == undefined` holds even though neither is an object.
11605        if matches!(left, Value::Undefined | Value::Null)
11606            && matches!(right, Value::Undefined | Value::Null)
11607        {
11608            return Ok(true);
11609        }
11610        if matches!(left, Value::Undefined | Value::Null)
11611            || matches!(right, Value::Undefined | Value::Null)
11612        {
11613            return Ok(false);
11614        }
11615        // Two objects compare by identity. Only an object *against a primitive* is
11616        // converted, which is why `{} == {}` is false while `[] == ""` is true.
11617        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11618            return Ok(a.ptr_eq(b));
11619        }
11620        let left = self.to_primitive(left, Hint::Default)?;
11621        let right = self.to_primitive(right, Hint::Default)?;
11622        Ok(left.loose_equals(&right))
11623    }
11624
11625    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11626        let Value::Object(object) = object else {
11627            return Err(Signal::Throw(
11628                self.make_error("TypeError", "cannot use 'in' on a non-object"),
11629            ));
11630        };
11631        let key = self.propkey(key)?;
11632        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11633        // trap. One implementation, so an array's derived `length` and its inherited holes
11634        // cannot be right in one caller and wrong in another.
11635        self.has_own_or_inherited(object, &key)
11636    }
11637
11638    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11639    ///
11640    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11641    /// whole reason the operator is a hook rather than a prototype walk.
11642    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11643        if let Value::Object(function) = constructor {
11644            let key = self.realm.well_known_key(WellKnown::HasInstance);
11645            let method = self.get_property_key(function, &key)?;
11646            if let Some(method) = method
11647                && !matches!(method, Value::Undefined)
11648            {
11649                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11650                return Ok(answer.to_boolean());
11651            }
11652        }
11653        self.instance_of(object, constructor)
11654    }
11655
11656    /// `OrdinaryHasInstance`: the prototype walk on its own.
11657    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11658        self.instance_of(object, constructor)
11659    }
11660
11661    /// `IsArray`: an array, or a proxy whose target is one.
11662    ///
11663    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11664    /// makes `Array.isArray(new Proxy([], {}))` true.
11665    pub fn is_array_value(&self, value: &Value) -> bool {
11666        match value {
11667            Value::Object(object) => {
11668                if let Some(state) = object.proxy_state() {
11669                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11670                }
11671                object.is_array()
11672            }
11673            _ => false,
11674        }
11675    }
11676
11677    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11678    ///
11679    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11680    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11681    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11682    /// see [`Interp::enqueue_job_function`].
11683    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11684        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11685        // the handler is reported rather than lost — the same reason a `then` reaction needs a
11686        // promise to settle.
11687        let promise = self.new_promise();
11688        self.fulfill_promise(&promise, Value::Undefined);
11689        self.jobs.push_back(Job::Reaction {
11690            handler: Some(function),
11691            argument: Value::Undefined,
11692            rejected: false,
11693            promise,
11694        });
11695        Ok(())
11696    }
11697
11698    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11699        let Value::Object(target) = object else {
11700            return Ok(false);
11701        };
11702        let Value::Object(function) = constructor else {
11703            return Err(Signal::Throw(self.make_error(
11704                "TypeError",
11705                "right-hand side of 'instanceof' is not callable",
11706            )));
11707        };
11708        let prototype = self.get_property(function, "prototype")?;
11709        let Some(Value::Object(prototype)) = prototype else {
11710            return Ok(false);
11711        };
11712        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11713        // which is also what makes `proxyOfInstance instanceof C` work.
11714        let mut current = Some(target.clone());
11715        while let Some(object) = current {
11716            if object.ptr_eq(&prototype) {
11717                return Ok(true);
11718            }
11719            current = self.object_prototype_of(&object)?;
11720        }
11721        Ok(false)
11722    }
11723
11724    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11725    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11726        if let Some(proto) = self.proxy_get_prototype_of(object)? {
11727            return Ok(proto);
11728        }
11729        if let Some(exotic) = object.exotic()
11730            && let Some(proto) = exotic.get_prototype(self, object)?
11731        {
11732            return Ok(proto);
11733        }
11734        Ok(object.proto())
11735    }
11736
11737    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11738    pub fn object_set_prototype_of(
11739        &mut self,
11740        object: &Gc<JsObject>,
11741        proto: Option<Gc<JsObject>>,
11742    ) -> JsResult<bool> {
11743        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11744            return Ok(answer);
11745        }
11746        if let Some(exotic) = object.exotic()
11747            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11748        {
11749            return Ok(answer);
11750        }
11751        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11752        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11753        // inheriting from itself, which every later prototype walk then had to defend
11754        // against — and `Reflect.setPrototypeOf` reported success for an operation the
11755        // language says is impossible.
11756        if let Some(proto) = &proto {
11757            let mut current = Some(proto.clone());
11758            let mut guard = 0;
11759            while let Some(node) = current {
11760                if node.ptr_eq(object) {
11761                    return Err(Signal::Throw(
11762                        self.make_error("TypeError", "circular prototype chain"),
11763                    ));
11764                }
11765                guard += 1;
11766                if guard > 1000 {
11767                    break;
11768                }
11769                current = node.proto();
11770            }
11771        }
11772        object.set_proto(proto);
11773        Ok(true)
11774    }
11775
11776    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
11777    ///
11778    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
11779    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
11780    /// already one.
11781    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
11782        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
11783        // (§10.4.5.4 step 1.b.i) — the prototype chain is *not* consulted for a canonical
11784        // numeric index. That is observable: a view that has been resized out of bounds
11785        // has no indices, and `2 in view` must then be `false` even when
11786        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
11787        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
11788        // A proxy is excluded because it has no `[[ViewedArrayBuffer]]` slot of its own.
11789        if object.typed_array_parts().is_some()
11790            && object.proxy_state().is_none()
11791            && let Some(index) = key.as_str().and_then(array_index)
11792        {
11793            return Ok(object
11794                .typed_array_length()
11795                .is_some_and(|length| (index as usize) < length));
11796        }
11797        let mut current = Some(object.clone());
11798        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
11799        let mut guard = 0;
11800        while let Some(node) = current {
11801            guard += 1;
11802            if guard > 1000 {
11803                return Ok(false);
11804            }
11805            let own = self.object_get_own_property(&node, key)?;
11806            if own.is_some() {
11807                return Ok(true);
11808            }
11809            current = self.object_prototype_of(&node)?;
11810        }
11811        Ok(false)
11812    }
11813
11814    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
11815    ///
11816    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
11817    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
11818    /// boolean as well, and it needs the receiver to be the one the caller named.
11819    pub fn set_property_with_key_receiver(
11820        &mut self,
11821        object: &Gc<JsObject>,
11822        key: &PropertyKey,
11823        value: Value,
11824        receiver: Option<&Value>,
11825        on_failure: DeleteFailure,
11826    ) -> JsResult<bool> {
11827        let receiver = receiver
11828            .cloned()
11829            .unwrap_or_else(|| Value::Object(object.clone()));
11830        if object.proxy_state().is_some() {
11831            return match self.proxy_set(object, key, value, &receiver)? {
11832                Some(accepted) => Ok(accepted),
11833                None => Ok(true),
11834            };
11835        }
11836        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
11837        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
11838        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
11839        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
11840        if object.typed_array_element_type().is_some()
11841            && key.as_str().and_then(array_index).is_some()
11842        {
11843            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
11844            self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
11845            return Ok(true);
11846        }
11847        // An own accessor, or one found up the chain, receives the call with `receiver` as
11848        // `this` — which is the whole reason this variant exists.
11849        if let Some(setter) = self.lookup_setter(object, key)? {
11850            self.call_value(setter, receiver, vec![value])?;
11851            return Ok(true);
11852        }
11853        // Otherwise it is an ordinary create-or-write, which the plain path already does —
11854        // carrying the receiver comparison, which a typed array's element store can see.
11855        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
11856        self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
11857        Ok(true)
11858    }
11859
11860    /// The setter `key` resolves to, if it resolves to an accessor.
11861    fn lookup_setter(
11862        &mut self,
11863        object: &Gc<JsObject>,
11864        key: &PropertyKey,
11865    ) -> JsResult<Option<Value>> {
11866        let mut current = Some(object.clone());
11867        let mut guard = 0;
11868        while let Some(node) = current {
11869            guard += 1;
11870            if guard > 1000 {
11871                return Ok(None);
11872            }
11873            if let Some(property) = self.object_get_own_property(&node, key)? {
11874                if property.is_accessor() {
11875                    return Ok(property.setter);
11876                }
11877                // A data property stops the walk: the store writes here, not further up.
11878                return Ok(None);
11879            }
11880            current = self.object_prototype_of(&node)?;
11881        }
11882        Ok(None)
11883    }
11884
11885    /// `[[IsExtensible]]`, with the proxy trap when there is one.
11886    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11887        if let Some(answer) = self.proxy_is_extensible(object)? {
11888            return Ok(answer);
11889        }
11890        if let Some(exotic) = object.exotic()
11891            && let Some(answer) = exotic.is_extensible(self, object)?
11892        {
11893            return Ok(answer);
11894        }
11895        Ok(object.is_extensible())
11896    }
11897
11898    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
11899    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11900        if let Some(answer) = self.proxy_prevent_extensions(object)? {
11901            return Ok(answer);
11902        }
11903        if let Some(exotic) = object.exotic()
11904            && let Some(answer) = exotic.prevent_extensions(self, object)?
11905        {
11906            return Ok(answer);
11907        }
11908        object.set_extensible(false);
11909        Ok(true)
11910    }
11911
11912    fn copy_properties(
11913        &mut self,
11914        target: &Value,
11915        source: &Value,
11916        exclusion: &Value,
11917    ) -> JsResult<()> {
11918        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
11919        // does contribute: its index properties are own, enumerable and writable, which
11920        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
11921        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
11922        // is a no-op.
11923        let Some(target) = target.as_object() else {
11924            return Ok(());
11925        };
11926        let source_object = match source {
11927            Value::Object(object) => object.clone(),
11928            Value::String(text) => {
11929                // Untaken keys are the string's indices, which are code units.
11930                for index in 0..text.utf16_len() {
11931                    if let Some(unit) = text.wtf8().unit_at(index) {
11932                        target.define_data(&index.to_string(), self.string_wtf8(unit));
11933                    }
11934                }
11935                return Ok(());
11936            }
11937            _ => return Ok(()),
11938        };
11939        // An object *rest* element passes the keys already taken by the literal part as
11940        // an array of strings; a spread passes `null`, which excludes nothing. Only the
11941        // string keys of the exclusion array are meaningful, so an array is read by its
11942        // elements rather than by its own property names.
11943        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
11944        if let Value::Object(list) = exclusion
11945            && let Some(length) = list.array_length()
11946        {
11947            for index in 0..length {
11948                if let Some(value) = list.array_get(index) {
11949                    excluded.push(self.propkey_of(&value)?);
11950                }
11951            }
11952        }
11953        let source = &source_object;
11954        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
11955        // Reading the property table directly made every spread of a proxy empty.
11956        let keys = self.object_own_property_keys(source)?;
11957        for as_key in keys {
11958            if as_key.is_symbol() {
11959                // A spread copies string-keyed properties only.
11960                continue;
11961            }
11962            if excluded.contains(&crate::value::Wtf8::new(
11963                as_key.as_str().unwrap_or_default(),
11964            )) {
11965                continue;
11966            }
11967            let enumerable = self
11968                .object_get_own_property(source, &as_key)?
11969                .is_some_and(|property| property.enumerable);
11970            if !enumerable {
11971                continue;
11972            }
11973            let value = self
11974                .get_property_key(source, &as_key)?
11975                .unwrap_or(Value::Undefined);
11976            target.define_data_key(&as_key, value);
11977        }
11978        Ok(())
11979    }
11980
11981    // -- iteration ---------------------------------------------------------
11982
11983    /// One object's own keys in enumeration order: array indices ascending, then the
11984    /// rest in insertion order.
11985    ///
11986    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
11987    /// whether the key is enumerable, which the caller resolves per key because an
11988    /// array's elements are not in the same store as its named properties.
11989    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
11990        // An index can arrive twice, once from the array's element store and once from
11991        // its property map, so the numeric keys go through a map that keeps the
11992        // enumerable answer if either source gave one.
11993        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
11994        for (key, enumerable) in &own {
11995            if let Some(index) = key.as_str().and_then(array_index) {
11996                let entry = numeric.entry(index).or_insert(false);
11997                *entry = *entry || *enumerable;
11998            }
11999        }
12000        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12001            .into_iter()
12002            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12003            .collect();
12004        ordered.extend(
12005            own.into_iter()
12006                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12007        );
12008        ordered
12009    }
12010
12011    /// Build the key list a `for-in` loop walks.
12012    ///
12013    /// The order is the specification's: own properties before inherited ones, and
12014    /// within one object the integer-like keys in ascending numeric order ahead of the
12015    /// string keys in insertion order. A shadowed key only appears once, and a key that
12016    /// is a non-enumerable own property anywhere nearer is skipped entirely.
12017    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12018        let record = self.new_object(None);
12019        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12020        // A proxy supplies its own key list, and — the reason this is not just another
12021        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12022        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12023        // descriptor there.
12024        if let Value::Object(object) = value
12025            && object.proxy_state().is_some()
12026        {
12027            let own = self
12028                .proxy_own_keys(object)?
12029                .unwrap_or_else(|| object.own_property_keys());
12030            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12031            let mut numeric: Vec<u32> = Vec::new();
12032            let mut rest: Vec<PropertyKey> = Vec::new();
12033            for key in own {
12034                match key.as_str().and_then(array_index) {
12035                    Some(index) => numeric.push(index),
12036                    None => rest.push(key),
12037                }
12038            }
12039            numeric.sort_unstable();
12040            ordered.extend(
12041                numeric
12042                    .into_iter()
12043                    .map(|index| PropertyKey::from(index.to_string())),
12044            );
12045            ordered.extend(rest);
12046            for (index, key) in ordered.into_iter().enumerate() {
12047                record.define_data(&index.to_string(), self.key_value(&key));
12048            }
12049            record.define_data("__index", Value::Int(0));
12050            // The mark that makes `for_in_advance` re-ask the proxy per key.
12051            record.define_data("__proxy", Value::Object(object.clone()));
12052            return Ok(record);
12053        }
12054        if let Value::Object(object) = value {
12055            let mut chain = vec![object.clone()];
12056            chain.extend(object.chain());
12057            // Every own string key the walk has seen, enumerable or not. A
12058            // non-enumerable own property still hides a same-named enumerable one
12059            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12060            // keeps `x` out of the loop even when the prototype has one.
12061            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12062            for object in chain {
12063                let mut own: Vec<(crate::value::Wtf8, bool)> = object
12064                    .own_property_keys()
12065                    .iter()
12066                    .filter_map(|key| key.as_wtf8().cloned())
12067                    .map(|key| {
12068                        let enumerable = object
12069                            .own_property(&key.to_string_lossy())
12070                            .map(|property| property.enumerable)
12071                            .unwrap_or(false);
12072                        (key, enumerable)
12073                    })
12074                    .collect();
12075                if let Some(length) = object.array_length() {
12076                    own.retain(|(key, _)| key.as_str() != Some("length"));
12077                    for index in 0..length {
12078                        if object.array_get(index).is_some() {
12079                            own.push((crate::value::Wtf8::new(index.to_string()), true));
12080                        }
12081                    }
12082                }
12083                // Integer-like keys come first in ascending order, then the rest in
12084                // insertion order — and the ordering is *per object*, not for the chain
12085                // as a whole: one pass over every collected key lifted a prototype's
12086                // `"4"` above the target's own `x`/`y`, which is not the order
12087                // `for…in` reports.
12088                for (key, enumerable) in Self::order_own_keys(own) {
12089                    if visited.contains(&key) {
12090                        continue;
12091                    }
12092                    visited.push(key.clone());
12093                    if enumerable {
12094                        keys.push(key);
12095                    }
12096                }
12097            }
12098        }
12099        for (index, key) in keys.into_iter().enumerate() {
12100            record.define_data(&index.to_string(), self.string_wtf8(key));
12101        }
12102        record.define_data("__index", Value::Int(0));
12103        Ok(record)
12104    }
12105
12106    /// The next key of a `for…in` record, `None` when the loop is done.
12107    ///
12108    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12109    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12110    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12111    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12112    /// key the handler had already withdrawn.
12113    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12114        let Value::Object(record) = record else {
12115            return Ok(None);
12116        };
12117        let proxy = record
12118            .own_property("__proxy")
12119            .and_then(|property| property.value);
12120        loop {
12121            let index = record
12122                .own_property("__index")
12123                .and_then(|property| property.value)
12124                .map(|value| value.to_int32())
12125                .unwrap_or(0);
12126            let Some(candidate) = record
12127                .own_property(&index.to_string())
12128                .and_then(|property| property.value)
12129            else {
12130                return Ok(None);
12131            };
12132            record.define_data("__index", Value::Int(index + 1));
12133            let text = candidate.to_js_string();
12134            let Some(Value::Object(proxy)) = &proxy else {
12135                return Ok(Some(text));
12136            };
12137            // The candidate is already a key string here, so the lookup does not need a
12138            // second `ToPropertyKey` conversion.
12139            let key = PropertyKey::from(text.as_str());
12140            let live = match self.proxy_get_own_property(proxy, &key)? {
12141                Some(descriptor) => descriptor,
12142                // Not a proxy after all, or it lost its state: fall back to the target.
12143                None => proxy.own_property_key(&key),
12144            };
12145            if live.is_some_and(|property| property.enumerable) {
12146                return Ok(Some(text));
12147            }
12148            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12149            // next one.
12150        }
12151    }
12152
12153    /// The iterator for `for-of`: the object and its `next` method.
12154    ///
12155    /// An object that already carries a `next` method is used as it is — that is what
12156    /// `arr.values()` returns — and only arrays and strings get the built-in
12157    /// sequence iterator.
12158    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12159    ///
12160    /// Callers that must choose between the iterable and the array-like protocol — the
12161    /// typed-array constructor is the main one — need to ask *before* committing to one.
12162    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12163        let key = self.realm.well_known_key(WellKnown::Iterator);
12164        let method = self.read_field_key(value, &key)?;
12165        if matches!(method, Value::Undefined | Value::Null) {
12166            return Ok(false);
12167        }
12168        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12169            return Err(Signal::Throw(
12170                self.make_error("TypeError", "Symbol.iterator is not callable"),
12171            ));
12172        }
12173        Ok(true)
12174    }
12175
12176    /// Collect everything an iterable yields, closing it if the walk is abandoned.
12177    ///
12178    /// The cap is a guard against a generator that never ends: an unbounded collect would
12179    /// be an out-of-memory abort rather than a catchable error.
12180    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12181        const MAX_ITEMS: usize = 1 << 24;
12182        let iterator = self.get_iterator(value)?;
12183        let mut out = Vec::new();
12184        loop {
12185            let (element, done) = self.iterator_step(&iterator)?;
12186            if done {
12187                return Ok(out);
12188            }
12189            out.push(element);
12190            if out.len() > MAX_ITEMS {
12191                return Err(self.range_error("iterable is too long to collect"));
12192            }
12193        }
12194    }
12195
12196    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12197    ///
12198    /// A native constructor calls this once it has validated its arguments, which is the
12199    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12200    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12201    /// never reached. The prototype comes from `new.target` when it is an object, and from
12202    /// `default_proto` otherwise.
12203    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12204        let proto = self.ctor_prototype(default_proto)?;
12205        Ok(self.new_object(Some(proto)))
12206    }
12207
12208    /// An **array** whose prototype comes from `new.target`.
12209    ///
12210    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12211    /// instance from `new.target.prototype`, and building a plain array instead made every
12212    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12213    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12214        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12215        Ok(JsObject::array(self.heap, Some(proto), 0))
12216    }
12217
12218    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12219    ///
12220    /// The `Option` form is for the constructors that build their instance in a helper which
12221    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12222    /// from `await`'s internal promise, and only the first has a `new.target`.
12223    fn ctor_prototype_opt(
12224        &mut self,
12225        default_proto: Option<Gc<JsObject>>,
12226    ) -> JsResult<Option<Gc<JsObject>>> {
12227        let Some(target) = self.pending_new_target.clone() else {
12228            return Ok(default_proto);
12229        };
12230        let Some(target) = target.as_object().cloned() else {
12231            return Ok(default_proto);
12232        };
12233        match self.get_property(&target, "prototype")? {
12234            Some(Value::Object(proto)) => Ok(Some(proto)),
12235            _ => Ok(default_proto),
12236        }
12237    }
12238
12239    /// `new.target.prototype`, or `default_proto` when this is a plain call.
12240    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12241        let Some(target) = self.pending_new_target.clone() else {
12242            return Ok(default_proto);
12243        };
12244        let Some(target) = target.as_object().cloned() else {
12245            return Ok(default_proto);
12246        };
12247        match self.get_property(&target, "prototype")? {
12248            Some(Value::Object(proto)) => Ok(proto),
12249            _ => Ok(default_proto),
12250        }
12251    }
12252
12253    /// `CreateDataPropertyOrThrow(O, key, value)`.
12254    ///
12255    /// A *definition*, not an assignment. The difference is visible the moment the target
12256    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12257    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12258    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12259    /// refused (`configurable: false`).
12260    ///
12261    /// The fast path exists because this is called once per element by `map`, `filter`,
12262    /// `slice` and friends: a plain array with no custom element descriptors and a writable
12263    /// `length` can store straight into its element vector.
12264    pub fn create_data_property_or_throw(
12265        &mut self,
12266        object: &Gc<JsObject>,
12267        index: usize,
12268        value: Value,
12269    ) -> JsResult<()> {
12270        if object.is_array()
12271            && object.elements_writable()
12272            && !object.has_element_descriptors()
12273            && object.is_extensible()
12274            && object.array_set(self.heap, index, value.clone())
12275        {
12276            return Ok(());
12277        }
12278        let key = PropertyKey::from(index.to_string());
12279        let property = Property {
12280            value: Some(value),
12281            writable: true,
12282            enumerable: true,
12283            configurable: true,
12284            ..Property::default()
12285        };
12286        if self.object_define_own_property(object, &key, property)? {
12287            return Ok(());
12288        }
12289        Err(self.type_error("cannot create the property"))
12290    }
12291
12292    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12293    ///
12294    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12295    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12296    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12297    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12298    /// run user code and both can throw.
12299    pub fn species_constructor(
12300        &mut self,
12301        object: &Gc<JsObject>,
12302        default: Value,
12303    ) -> JsResult<Value> {
12304        let Some(constructor) = self.get_property(object, "constructor")? else {
12305            return Ok(default);
12306        };
12307        let constructor = match constructor {
12308            Value::Undefined => return Ok(default),
12309            Value::Object(constructor) => constructor,
12310            _ => return Err(self.type_error("constructor is not an object")),
12311        };
12312        let key = self.realm.well_known_key(WellKnown::Species);
12313        let species = self.get_property_key(&constructor, &key)?;
12314        match species {
12315            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12316            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12317            Some(_) => Err(self.type_error("species is not a constructor")),
12318        }
12319    }
12320
12321    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12322    ///
12323    /// The result is an array of `length` holes whose prototype comes from
12324    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12325    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12326    /// is why the `IsArray` check is the first step and not an optimisation.
12327    pub fn array_species_create(
12328        &mut self,
12329        original: &Value,
12330        length: usize,
12331    ) -> JsResult<Gc<JsObject>> {
12332        let Some(object) = original.as_object().cloned() else {
12333            return Ok(self.new_array_of_length(length));
12334        };
12335        if !object.is_array() {
12336            return Ok(self.new_array_of_length(length));
12337        }
12338        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12339        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12340        let Some(constructor) = self.get_property(&object, "constructor")? else {
12341            return Ok(self.new_array_of_length(length));
12342        };
12343        let species = match constructor {
12344            Value::Undefined => return Ok(self.new_array_of_length(length)),
12345            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12346                return Ok(self.new_array_of_length(length));
12347            }
12348            Value::Object(constructor) => {
12349                let key = self.realm.well_known_key(WellKnown::Species);
12350                match self.get_property_key(&constructor, &key)? {
12351                    None | Some(Value::Undefined) | Some(Value::Null) => {
12352                        return Ok(self.new_array_of_length(length));
12353                    }
12354                    Some(species) => species,
12355                }
12356            }
12357            _ => return Ok(self.new_array_of_length(length)),
12358        };
12359        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12360        // that is merely callable is the `create-species-non-ctor` case.
12361        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12362            return Err(self.type_error("species is not a constructor"));
12363        }
12364        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12365        let Some(created) = created.as_object().cloned() else {
12366            return Err(self.type_error("species constructor did not answer an object"));
12367        };
12368        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12369        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12370        // object, and `create-species-with-non-writable-property` asserts exactly that.
12371        // The length is set for the array case; the generic case is the caller's
12372        // `Set(A, "length", …)`.
12373        if created.is_array() {
12374            created.array_set_length(self.heap, length);
12375        }
12376        Ok(created)
12377    }
12378
12379    /// Whether `object` is this realm's `%Array%`.
12380    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12381        self.realm
12382            .array_constructor
12383            .as_ref()
12384            .is_some_and(|array| array.ptr_eq(object))
12385    }
12386
12387    /// A fresh `length`-hole array with the intrinsic prototype.
12388    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12389        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12390        array.array_set_length(self.heap, length);
12391        array
12392    }
12393
12394    /// Whether this call is a construction, i.e. `new.target` is defined.
12395    ///
12396    /// A native constructor receives `this = undefined` (it builds its own instance), so it
12397    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12398    /// The native function currently executing, if any.
12399    pub fn current_native(&self) -> Option<Gc<JsObject>> {
12400        self.current_native.clone()
12401    }
12402
12403    /// Whether this call is a construction, i.e. `new.target` is defined.
12404    pub fn is_constructing(&self) -> bool {
12405        self.pending_new_target.is_some()
12406    }
12407
12408    /// The `TypeError` a constructor too primitive to have a wrapper raises.
12409    ///
12410    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12411    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12412    /// happens inside the native function, which is why the trace carries an
12413    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12414    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12415    /// constructor`, and an unnamed one reports the leading space of `" is not a
12416    /// constructor"` because the reference formats the empty name as it is.
12417    ///
12418    /// It is also the answer for a `new.target` that cannot be named at all — not a
12419    /// function, or a throwing `name` getter — where the reference falls back to the bare
12420    /// `not a constructor`.
12421    pub fn not_a_constructor_error(&mut self) -> Signal {
12422        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12423        self.not_a_constructor_error_for(target)
12424    }
12425
12426    /// The same `TypeError` for an explicit target, for the callers that check
12427    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12428    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12429        let target = match target {
12430            Value::Object(target) if target.is_callable() => target,
12431            _ => return self.type_error("not a constructor"),
12432        };
12433        let name = match self.get_property(&target, "name") {
12434            Ok(Some(value)) => value.to_js_string(),
12435            _ => return self.type_error("not a constructor"),
12436        };
12437        self.type_error(format!("{name} is not a constructor"))
12438    }
12439
12440    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12441    ///
12442    /// True whenever `new.target` is not the callee itself, or when it has no usable
12443    /// `prototype` — the cases where reading the property is observable at all.
12444    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12445        match &self.pending_new_target {
12446            Some(Value::Object(target)) => !target.ptr_eq(callee),
12447            Some(_) => true,
12448            None => false,
12449        }
12450    }
12451
12452    /// The symbol key for one of the engine's own hidden slots.
12453    ///
12454    /// Cached on the realm, so every object of a kind shares one key and a slot can be
12455    /// read back by name.
12456    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12457        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12458            return PropertyKey::Symbol(symbol.clone());
12459        }
12460        let symbol = Gc::new(
12461            self.heap,
12462            crate::value::JsSymbol::new(Some(name.to_string())),
12463        );
12464        self.realm
12465            .internal_slots
12466            .borrow_mut()
12467            .insert(name, Value::Symbol(symbol.clone()));
12468        PropertyKey::Symbol(symbol)
12469    }
12470
12471    /// Read a hidden slot, or `None` when the object has none of that name.
12472    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12473        let slots = self.realm.internal_slots.borrow();
12474        let Value::Symbol(symbol) = slots.get(name)? else {
12475            return None;
12476        };
12477        object
12478            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12479            .and_then(|property| property.value)
12480    }
12481
12482    /// Define a hidden slot.
12483    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12484        let key = self.internal_slot(name);
12485        object.define_key(&key, Property::with_attributes(value, false, false));
12486    }
12487
12488    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12489    ///
12490    /// The method is looked up on the value (through its prototype), called with no
12491    /// arguments, and its result becomes the iterator. A generator gets here through
12492    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12493    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12494    ///
12495    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12496    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12497    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12498    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12499    /// does, and a user-defined iterable works without a special case.
12500    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12501    /// `Symbol.iterator`.
12502    ///
12503    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12504    /// iterable is legal there, and each value it produces is simply already settled by
12505    /// the time the `await` around it runs.
12506    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12507        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12508        let method = self.read_field_key(value, &async_key)?;
12509        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12510        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12511        // is *present but not callable* is a TypeError — it does not mean "try the other
12512        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12513        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12514        // guard is there to catch.
12515        let absent = matches!(method, Value::Undefined | Value::Null);
12516        if !absent {
12517            let Value::Object(object) = &method else {
12518                return Err(Signal::Throw(
12519                    self.make_error("TypeError", "value is not iterable"),
12520                ));
12521            };
12522            if !object.is_callable() {
12523                return Err(Signal::Throw(
12524                    self.make_error("TypeError", "value is not iterable"),
12525                ));
12526            }
12527        }
12528        if absent {
12529            return self.get_iterator(value);
12530        }
12531        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12532        if !matches!(iterator, Value::Object(_)) {
12533            return Err(Signal::Throw(
12534                self.make_error("TypeError", "iterator is not an object"),
12535            ));
12536        }
12537        let next = self.read_field(&iterator, "next")?;
12538        Ok(Iterator {
12539            object: iterator,
12540            next,
12541        })
12542    }
12543
12544    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12545        let key = self.realm.well_known_key(WellKnown::Iterator);
12546        let method = self.read_field_key(value, &key)?;
12547        let Value::Object(function) = &method else {
12548            return Err(Signal::Throw(self.make_error(
12549                "TypeError",
12550                &format!("{} is not iterable", value.to_js_string()),
12551            )));
12552        };
12553        if !function.is_callable() {
12554            return Err(Signal::Throw(self.make_error(
12555                "TypeError",
12556                &format!("{} is not iterable", value.to_js_string()),
12557            )));
12558        }
12559        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12560        // The spec requires an object here; a primitive iterator has no `next` to call
12561        // and would fail one step later with a confusing message.
12562        if !matches!(iterator, Value::Object(_)) {
12563            return Err(Signal::Throw(
12564                self.make_error("TypeError", "iterator is not an object"),
12565            ));
12566        }
12567        let next = self.read_field(&iterator, "next")?;
12568        Ok(Iterator {
12569            object: iterator,
12570            next,
12571        })
12572    }
12573
12574    /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
12575    /// not iterable.
12576    ///
12577    /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
12578    /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
12579    /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
12580    /// was `[]`.
12581    pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
12582        let key = self.realm.well_known_key(WellKnown::Iterator);
12583        let method = self.read_field_key(value, &key)?;
12584        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12585            return Ok(None);
12586        }
12587        let iterator = self.get_iterator(value)?;
12588        let mut out = Vec::new();
12589        loop {
12590            let (element, done) = self.iterator_step(&iterator)?;
12591            if done {
12592                return Ok(Some(out));
12593            }
12594            out.push(element);
12595        }
12596    }
12597
12598    /// One step of an internal iterator: the value and whether it is exhausted.
12599    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12600        // A real iterator (`next` is a function) answers with a result object.
12601        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12602            let result =
12603                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12604            let Some(result) = result.as_object().cloned() else {
12605                return Err(self.type_error("iterator result is not an object"));
12606            };
12607            let done = self
12608                .get_property(&result, "done")?
12609                .is_some_and(|value| value.to_boolean());
12610            let value = self
12611                .get_property(&result, "value")?
12612                .unwrap_or(Value::Undefined);
12613            return Ok((value, done));
12614        }
12615        // An iterator whose `next` is not callable is treated as exhausted, which is
12616        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12617        // that are not iterable at all.
12618        Ok((Value::Undefined, true))
12619    }
12620
12621    /// `[...iterable]`: append everything the iterator yields, and answer the next
12622    /// index.
12623    ///
12624    /// This goes through the same iterator machinery `for-of` uses rather than copying
12625    /// an array's elements, because a spread source is any iterable: a string spreads
12626    /// into its characters and an array iterator spreads into its results. Handling
12627    /// only arrays made `[..."ab"]` come out empty with no error at all.
12628    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12629        let Some(target) = array.as_object().cloned() else {
12630            return Ok(0);
12631        };
12632        let start = target.array_length().unwrap_or(0);
12633        let mut added = 0;
12634        let iterator = self.get_iterator(iterable)?;
12635        loop {
12636            let (value, done) = self.iterator_step(&iterator)?;
12637            if done {
12638                break;
12639            }
12640            target.array_set(self.heap, start + added, value);
12641            added += 1;
12642        }
12643        Ok((start + added) as i32)
12644    }
12645
12646    /// How an uncaught exception is reported.
12647    ///
12648    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12649    /// with `ToString` — `js_std_dump_error` is three lines that end in
12650    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12651    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12652    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12653    ///
12654    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12655    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12656    /// `toString`"; it does call it, but only for objects of a class it does not know how
12657    /// to walk, and never for errors, arrays or plain objects.
12658    ///
12659    /// A printer that fails must not take the reporter down with it, so that case falls
12660    /// back to the `ToString` rendering.
12661    pub fn describe_exception(&mut self, value: &Value) -> String {
12662        match crate::print::sprint(self, value) {
12663            Ok(text) => text,
12664            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12665        }
12666    }
12667
12668    /// The file name of whatever is running, innermost frame first.
12669    ///
12670    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12671    /// innermost frame's file name, without distinguishing a module body from a plain
12672    /// script. `import()` uses it as the base for a relative specifier, which is why
12673    /// `import('./x.js')` inside a script resolves next to the script and not next to the
12674    /// process's working directory.
12675    pub fn script_or_module_name(&self) -> Option<String> {
12676        self.script_or_module_name_at(0)
12677    }
12678
12679    /// [`Interp::script_or_module_name`] `level` frames further out.
12680    ///
12681    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12682    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12683    /// frame without a file name is skipped rather than counted, because a native call
12684    /// pushes no frame of its own and so cannot be a level.
12685    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12686        self.frames
12687            .iter()
12688            .rev()
12689            .filter_map(|frame| frame.code.code.filename.clone())
12690            .nth(level)
12691    }
12692
12693    /// The current call stack, formatted the way `qjs` prints `error.stack`.
12694    ///
12695    /// One `    at name (file:line:col)` line per active frame, innermost first. The
12696    /// position is the one recorded for the instruction each frame is stopped on, which
12697    /// is why the compiler builds a pc-to-position table per function: without it a
12698    /// trace could only name the function, not the line inside it.
12699    ///
12700    /// A frame whose code has no positions prints just `(file)`, matching the
12701    /// reference's output for stripped bytecode.
12702    pub fn stack_trace(&self) -> String {
12703        self.stack_trace_skipping(0)
12704    }
12705
12706    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12707    fn stack_trace_skipping(&self, skip: usize) -> String {
12708        // One ordered list, innermost first, so `skip` counts the same thing whether the
12709        // frames it leaves out are native or bytecode. Indices rather than references: a
12710        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12711        let depth = self.frames.len();
12712        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12713        // A native entered while `at` bytecode frames were live was called *from* the
12714        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12715        // entered at the current depth are therefore innermost of all.
12716        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12717            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12718                if *at == wanted {
12719                    order.push((true, index));
12720                }
12721            }
12722        };
12723        push_natives(&mut order, depth);
12724        for index in (0..depth).rev() {
12725            order.push((false, index));
12726            push_natives(&mut order, index);
12727        }
12728        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12729        // barrier. Natives entered at exactly the barrier depth are the eval entry point
12730        // itself (`evalScript (native)`), and the reference leaves those out too.
12731        if let Some(barrier) = self.trace_barriers.last().copied() {
12732            order.retain(|(is_native, index)| match is_native {
12733                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12734                false => *index >= barrier,
12735            });
12736        }
12737
12738        let mut out = String::new();
12739        for (is_native, index) in order.into_iter().skip(skip) {
12740            match is_native {
12741                true => {
12742                    out.push_str("    at ");
12743                    let (native, _) = &self.native_frames[index];
12744                    let name = native
12745                        .own_property("name")
12746                        .and_then(|property| property.value)
12747                        .map(|value| value.to_js_string())
12748                        .unwrap_or_default();
12749                    out.push_str(&name);
12750                    out.push_str(" (native)\n");
12751                }
12752                false => {
12753                    let frame = &self.frames[index];
12754                    let code = &frame.code.code;
12755                    let file = code.filename.as_deref().unwrap_or("<input>");
12756                    // The name comes from the function *object*, not from the compiled code:
12757                    // an anonymous function expression is named by the property it is stored
12758                    // in (`{valueOf: function(){}}`), which only the object knows.
12759                    let bound_name = match &frame.callee {
12760                        Value::Object(object) => {
12761                            object
12762                                .own_property("name")
12763                                .and_then(|property| match property.value {
12764                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
12765                                        Some(text.to_string_lossy().into_owned())
12766                                    }
12767                                    _ => None,
12768                                })
12769                        }
12770                        _ => None,
12771                    };
12772                    // No callee object means the body was entered by the host, so the
12773                    // name has to come from the compiled code. Two cases differ:
12774                    //
12775                    // * an *unnamed* function of any kind — the reference reads the
12776                    //   `name` property, finds it empty, and prints `<anonymous>`;
12777                    // * a *module* body, which has no `name` property at all: the
12778                    //   reference builds that function object with `js_closure2` and
12779                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
12780                    //   so a trace reaching it also prints `<anonymous>` — while a
12781                    //   *script* body prints `<eval>`, its `name`.
12782                    let unnamed = code.name.is_empty() || code.module.is_some();
12783                    out.push_str("    at ");
12784                    match bound_name.as_deref() {
12785                        Some(name) => out.push_str(name),
12786                        None if unnamed => out.push_str("<anonymous>"),
12787                        None => out.push_str(&code.name),
12788                    }
12789                    match code.position_at(frame.at as u32) {
12790                        Some((line, column)) => {
12791                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
12792                        }
12793                        None => out.push_str(&format!(" ({file})\n")),
12794                    }
12795                }
12796            }
12797        }
12798        out
12799    }
12800
12801    /// Give an anonymous function the name of the property it is stored in.
12802    ///
12803    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
12804    /// enumerable and not configurable, and a function that already has a real name
12805    /// keeps it.
12806    ///
12807    /// "Already named" means a *non-empty* name: every function object is created with
12808    /// a `name` of `""` so the property exists on all of them, and treating that empty
12809    /// string as a name left every anonymous function nameless — which is how a stack
12810    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
12811    /// `SetFunctionName`, for a name that came from source text.
12812    fn set_function_name(&mut self, function: &Value, name: &str) {
12813        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
12814    }
12815
12816    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
12817    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
12818    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
12819        let Value::Object(object) = function else {
12820            return;
12821        };
12822        // `SetFunctionName` applies to *functions* and classes only, and only when they are
12823        // anonymous. Without the callability guard, `{value: someObject}` renamed
12824        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
12825        // on the right-hand side of a property. That is how a `zipKeyed` result object
12826        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
12827        // has no `NamedEvaluation` at all.
12828        if !object.is_callable() {
12829            return;
12830        }
12831        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
12832            && !existing.wtf8().is_empty()
12833        {
12834            return;
12835        }
12836        let text = self.string_wtf8(name.clone());
12837        object.define("name", Property::name_or_length(text));
12838    }
12839
12840    // -- global declarations -----------------------------------------------
12841
12842    /// Declare a global binding, creating its reference cell.
12843    /// Declare a `var` or function global, whose home is the global object.
12844    ///
12845    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
12846    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
12847    /// such as `print`, or a redeclaration — is left alone.
12848    pub fn declare_var_global(&mut self, name: &str) {
12849        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
12850        // global object is exactly the leak `typeof my_var === "undefined"` after
12851        // `eval("var my_var=2")` rules out.
12852        if let Some(scope) = self.eval_scope.as_mut() {
12853            scope.entry(name.to_string()).or_insert(Value::Undefined);
12854            return;
12855        }
12856        // A sloppy direct eval declares into its *caller's* variable environment. Doing
12857        // this on the global object instead made `eval("var c = 1")` inside a parameter
12858        // list overwrite a global `c`, and made two calls to the same function share one
12859        // binding.
12860        if let Some(cell) = self.declare_eval_local(name) {
12861            cell.set(Value::Undefined);
12862            return;
12863        }
12864        let global = self.realm.global.clone();
12865        if global.own_property(name).is_some() {
12866            return;
12867        }
12868        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
12869        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
12870        // whole point of that trick and what lets `Object.defineProperty` reshape it
12871        // afterwards. `eval_scope` is `Some` while an eval is running.
12872        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
12873        global.define(
12874            name,
12875            Property {
12876                value: Some(Value::Undefined),
12877                writable: true,
12878                enumerable: true,
12879                configurable: from_eval,
12880                ..Property::default()
12881            },
12882        );
12883    }
12884
12885    /// Declare a *lexical* global binding, which starts in its dead zone.
12886    ///
12887    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
12888    /// global object and is created when its initialiser runs.
12889    pub fn declare_global(&mut self, name: &str, is_const: bool) {
12890        if is_const {
12891            self.realm.lexical_consts.insert(name.to_string());
12892        }
12893        if !self.realm.globals.contains_key(name) {
12894            // `Uninitialized` rather than `Undefined`: the binding exists but is not
12895            // readable until its initialiser runs, and that is what `let x` before
12896            // `x = 1` has to observe.
12897            let cell = self.new_cell(Value::Uninitialized);
12898            self.realm.globals.insert(name.to_string(), cell);
12899            self.realm.declared.push(name.to_string());
12900        }
12901    }
12902}
12903
12904/// The bytecode and environment of a function object, if it is a bytecode function.
12905///
12906/// Extracted before a call so no borrow of the object is held across it.
12907fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
12908    function.with(|data| match &data.kind {
12909        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
12910        _ => None,
12911    })
12912}
12913
12914/// A native call target, extracted before the call so no borrow is held.
12915enum NativeCall {
12916    Native(NativeFn),
12917    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
12918    /// not hold that object's `RefCell` borrow.
12919    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
12920    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
12921    Bound {
12922        target: Value,
12923        this: Value,
12924        leading: Vec<Value>,
12925    },
12926    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
12927    Revoker(crate::object::ProxyRef),
12928    /// A promise's `resolve`.
12929    PromiseResolve(Gc<JsObject>),
12930    /// A promise's `reject`.
12931    PromiseReject(Gc<JsObject>),
12932    /// The executor `NewPromiseCapability(C)` hands a user constructor.
12933    CapabilityExecutor {
12934        state: Gc<JsObject>,
12935    },
12936    /// One leg of a `then` that settles through a user capability.
12937    ThenShim {
12938        handler: Option<Value>,
12939        resolve: Value,
12940        reject: Value,
12941        fulfilled: bool,
12942    },
12943    /// One continuation of an `await`.
12944    AwaitResume {
12945        coroutine: Gc<JsObject>,
12946        promise: Gc<JsObject>,
12947        kind: ResumeKind,
12948    },
12949    /// One element of a `Promise` combinator settling.
12950    CombinatorSettle {
12951        state: Gc<JsObject>,
12952        index: usize,
12953        fulfilled: bool,
12954    },
12955    /// One of `Promise.prototype.finally`'s two shims.
12956    FinallyShim {
12957        callback: Option<Value>,
12958        fulfilled: bool,
12959        constructor: Value,
12960    },
12961    /// Settle a promise with a fixed outcome.
12962    SettlePromise {
12963        promise: Gc<JsObject>,
12964        value: Value,
12965        rejected: bool,
12966    },
12967    /// Continue an async generator after its `await` settled.
12968    GeneratorResume {
12969        generator: Gc<JsObject>,
12970        promise: Gc<JsObject>,
12971        kind: ResumeKind,
12972    },
12973    /// Read a module namespace's binding out of its cell.
12974    ModuleBinding(Gc<Cell>),
12975    /// Finish a completed async generator's `return(v)` once `v` has settled.
12976    CompletedReturn {
12977        generator: Gc<JsObject>,
12978        promise: Gc<JsObject>,
12979        rejected: bool,
12980    },
12981    /// Answer a pending async-generator method with `{value, done}`.
12982    YieldResult {
12983        generator: Gc<JsObject>,
12984        promise: Gc<JsObject>,
12985        done: bool,
12986    },
12987    /// One step of `AsyncDisposableStack.disposeAsync`.
12988    DisposeStep {
12989        remaining: Gc<JsObject>,
12990        promise: Gc<JsObject>,
12991        error: Value,
12992        rejected: bool,
12993    },
12994}
12995
12996/// What a store does when the object refuses the write.
12997#[derive(Clone, Copy, PartialEq, Eq)]
12998pub enum DeleteFailure {
12999    /// Raise a `TypeError`, which is what strict mode and every built-in does.
13000    Throw,
13001    /// Ignore the write, which is what a sloppy-mode assignment does.
13002    Ignore,
13003}
13004
13005/// Whether `object` is a `Date` instance, by the class tag it carries.
13006///
13007/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13008/// builtins module depending on the interpreter's conversion order.
13009fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13010    interp
13011        .internal_get(object, "_class")
13012        .is_some_and(|value| value.to_js_string() == "Date")
13013}
13014
13015/// Which type `ToPrimitive` prefers when it converts an object.
13016#[derive(Clone, Copy, PartialEq, Eq)]
13017pub enum Hint {
13018    /// The default hint, which behaves like [`Hint::Number`].
13019    Default,
13020    /// `Number(obj)` and the arithmetic operators.
13021    Number,
13022    /// `String(obj)` and `ToPropertyKey`.
13023    String,
13024}
13025
13026/// Which table a binding slot indexes, for the messages that name it.
13027#[derive(Clone, Copy)]
13028enum VarSlot {
13029    Loc,
13030    Closure,
13031}
13032
13033/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13034fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13035    Ok(this)
13036}
13037
13038/// An internal iterator: the sequence plus a cursor.
13039pub(crate) struct Iterator {
13040    pub(crate) object: Value,
13041    pub(crate) next: Value,
13042}
13043
13044/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13045/// and plain `a` for a method.
13046///
13047/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13048/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13049/// reads `at get a (file:1:2)`.
13050/// The same prefixing, for a name that may hold an unpaired surrogate.
13051fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13052    let prefix = match flags & 3 {
13053        1 => "get ",
13054        2 => "set ",
13055        _ => return key.clone(),
13056    };
13057    let mut units: Vec<u16> = prefix.encode_utf16().collect();
13058    units.extend_from_slice(&key.to_units());
13059    crate::value::Wtf8::from_units(&units)
13060}
13061
13062fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13063    match flags & 3 {
13064        1 => format!("get {key}"),
13065        2 => format!("set {key}"),
13066        _ => key.to_string(),
13067    }
13068}
13069
13070/// Define a method or accessor property, per the `define_method` flag byte.
13071///
13072/// The low two bits pick value/getter/setter and bit 2 marks the property
13073/// enumerable.
13074///
13075/// A getter and a setter arrive as two separate `define_method` instructions, and the
13076/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13077/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13078/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13079/// `JS_DefineProperty`, which leaves the other half alone.
13080fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13081    let enumerable = flags & 4 != 0;
13082    let kind = flags & 3;
13083    let existing = object.own_property_key(key);
13084    let property = match kind {
13085        1 => Property {
13086            getter: Some(function),
13087            // The setter half, if this literal already defined one.
13088            setter: existing
13089                .filter(Property::is_accessor)
13090                .and_then(|p| p.setter),
13091            enumerable,
13092            configurable: true,
13093            ..Property::default()
13094        },
13095        2 => Property {
13096            getter: existing
13097                .filter(Property::is_accessor)
13098                .and_then(|p| p.getter),
13099            setter: Some(function),
13100            enumerable,
13101            configurable: true,
13102            ..Property::default()
13103        },
13104        _ => Property {
13105            value: Some(function),
13106            writable: true,
13107            enumerable,
13108            configurable: true,
13109            ..Property::default()
13110        },
13111    };
13112    object.define_key(key, property);
13113}
13114
13115// ---------------------------------------------------------------------------
13116// Operand decoding
13117// ---------------------------------------------------------------------------
13118
13119/// How `print` renders a value: the reference's `JS_PrintValue`.
13120///
13121/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13122/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13123/// The format is reproduced closely because the test suite compares output text:
13124///
13125/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13126/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13127/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13128/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13129///   end print as `<N empty item(s)>`;
13130/// * a string is quoted inside a container but raw at the top level, which is why
13131///   `print("x")` and `print(["x"])` differ.
13132pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13133    // A string argument is printed raw: `js_print` converts it with `ToString`
13134    // instead of dumping it, and the quoting only appears inside a container.
13135    if let Value::String(text) = value {
13136        return text.to_string_lossy().into_owned();
13137    }
13138    let mut printer = Printer {
13139        interp,
13140        out: String::new(),
13141        stack: Vec::new(),
13142    };
13143    printer.value(value, 0);
13144    printer.out
13145}
13146
13147/// The internal class name an object carries, when it has one.
13148fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13149    interp
13150        .internal_get(object, "_class")
13151        .map(|value| value.to_js_string())
13152}
13153
13154/// A string property, looked up the way `GetProperty` does: own first, then the
13155/// prototype chain. Needed because the print formatter holds the interpreter
13156/// immutably and so cannot run getters.
13157fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13158    let mut current = Some(object.clone());
13159    // Bounded, because a prototype cycle would otherwise loop forever.
13160    for _ in 0..100 {
13161        let node = current?;
13162        if let Some(property) = node.own_property(name)
13163            && let Some(value) = property.value
13164        {
13165            return Some(value.to_js_string());
13166        }
13167        current = node.with(|data| data.proto.clone());
13168    }
13169    None
13170}
13171
13172/// The `JS_PrintValue` state: output, and the objects currently being printed.
13173struct Printer<'a, 'rt> {
13174    /// Kept for the class-name lookups that typed arrays and `Date` will need.
13175    #[allow(dead_code)]
13176    interp: &'a Interp<'rt>,
13177    out: String,
13178    stack: Vec<Gc<JsObject>>,
13179}
13180
13181impl Printer<'_, '_> {
13182    /// Depth past which a container is summarised by its class name.
13183    const MAX_DEPTH: usize = 2;
13184
13185    fn value(&mut self, value: &Value, level: usize) {
13186        match value {
13187            Value::Undefined
13188            | Value::Uninitialized
13189            | Value::Hole
13190            | Value::CatchOffset(_)
13191            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13192            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13193            // The printer writes a bigint the way the language spells one, so a dump is
13194            // unambiguous about which kind of number it is showing.
13195            Value::BigInt(big) => {
13196                self.out.push_str(&big.to_decimal_string());
13197                self.out.push('n');
13198            }
13199            Value::Null => self.out.push_str("null"),
13200            Value::Bool(true) => self.out.push_str("true"),
13201            Value::Bool(false) => self.out.push_str("false"),
13202            Value::Int(number) => self.out.push_str(&number.to_string()),
13203            Value::Float(number) => {
13204                self.out
13205                    .push_str(&crate::value::number_to_string_for_print(*number));
13206            }
13207            Value::String(text) => self.print_string(&text.to_string_lossy()),
13208            Value::Object(object) => self.object(object, level),
13209        }
13210    }
13211
13212    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13213        // A cycle is reported rather than followed; the index is where the object
13214        // already sits in the print stack, which is what the reference shows.
13215        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13216            self.out.push_str(&format!("[circular {index}]"));
13217            return;
13218        }
13219        if object.is_callable() {
13220            let name = object
13221                .own_property("name")
13222                .and_then(|property| property.value)
13223                .map(|value| value.to_js_string())
13224                .unwrap_or_default();
13225            if name.is_empty() {
13226                self.out.push_str("[Function (anonymous)]");
13227            } else {
13228                self.out.push_str(&format!("[Function {name}]"));
13229            }
13230            return;
13231        }
13232        if level >= Self::MAX_DEPTH {
13233            let class = if object.is_array() { "Array" } else { "Object" };
13234            self.out.push_str(&format!("[{class}]"));
13235            return;
13236        }
13237        // `Date` and `Error` print as themselves rather than as bags of properties:
13238        // the ISO string, and `Name: message` followed by the trace.
13239        if let Some(class) = class_of(self.interp, object) {
13240            if class == "Date" {
13241                self.date(object);
13242                return;
13243            }
13244            if class == "Error" {
13245                self.error(object);
13246                return;
13247            }
13248        }
13249        self.stack.push(object.clone());
13250        if object.is_array() {
13251            self.array(object, level);
13252        } else {
13253            self.plain_object(object, level);
13254        }
13255        self.stack.pop();
13256    }
13257
13258    /// A Date prints as its ISO string; an invalid one falls through to the plain
13259    /// object form, the way the reference falls back when `toISOString` throws.
13260    fn date(&mut self, object: &Gc<JsObject>) {
13261        let value = self
13262            .interp
13263            .internal_get(object, "_date_value")
13264            .map(|value| value.to_number());
13265        match value.and_then(crate::builtins::date::iso_string) {
13266            Some(text) => self.out.push_str(&text),
13267            None => self.plain_object(object, 0),
13268        }
13269    }
13270
13271    /// `Name: message`, then the trace with its trailing newline removed.
13272    fn error(&mut self, object: &Gc<JsObject>) {
13273        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13274        self.out.push_str(&name);
13275        if let Some(message) = inherited(object, "message")
13276            && !message.is_empty()
13277        {
13278            self.out.push_str(": ");
13279            self.out.push_str(&message);
13280        }
13281        if let Some(stack) = inherited(object, "stack") {
13282            self.out.push('\n');
13283            self.out.push_str(stack.trim_end_matches('\n'));
13284        }
13285    }
13286
13287    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13288        let elements = object.array_elements().unwrap_or_default();
13289        self.out.push_str("[ ");
13290        // An interior hole means the array is "sparse": the reference prints those
13291        // as `index: value` pairs and says nothing about the holes themselves, while
13292        // a hole run at the end becomes a single `<N empty items>` note.
13293        let last_present = elements
13294            .iter()
13295            .rposition(|value| !matches!(value, Value::Hole));
13296        let has_interior_hole = match last_present {
13297            Some(last) => elements[..last]
13298                .iter()
13299                .any(|value| matches!(value, Value::Hole)),
13300            None => false,
13301        };
13302        let mut first = true;
13303        if has_interior_hole {
13304            let mut index = 0;
13305            while index < elements.len() {
13306                let value = &elements[index];
13307                if matches!(value, Value::Hole) {
13308                    index += 1;
13309                    continue;
13310                }
13311                if !first {
13312                    self.out.push_str(", ");
13313                }
13314                first = false;
13315                self.out.push_str(&format!("{index}: "));
13316                self.value(value, level + 1);
13317                index += 1;
13318            }
13319        } else {
13320            for (index, value) in elements.iter().enumerate() {
13321                if matches!(value, Value::Hole) {
13322                    continue;
13323                }
13324                if !first {
13325                    self.out.push_str(", ");
13326                }
13327                first = false;
13328                let _ = index;
13329                self.value(value, level + 1);
13330            }
13331            if let Some(last) = last_present {
13332                let trailing = elements.len() - last - 1;
13333                if trailing > 0 {
13334                    if !first {
13335                        self.out.push_str(", ");
13336                    }
13337                    self.out.push_str(&format!(
13338                        "<{trailing} empty item{}>",
13339                        if trailing > 1 { "s" } else { "" }
13340                    ));
13341                }
13342            } else if !elements.is_empty() {
13343                let count = elements.len();
13344                self.out.push_str(&format!(
13345                    "<{count} empty item{}>",
13346                    if count > 1 { "s" } else { "" }
13347                ));
13348            }
13349        }
13350        self.out.push_str(" ]");
13351    }
13352
13353    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13354        self.out.push_str("{ ");
13355        let mut first = true;
13356        for key in object.own_keys() {
13357            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13358                continue;
13359            };
13360            if !property.enumerable {
13361                continue;
13362            }
13363            if !first {
13364                self.out.push_str(", ");
13365            }
13366            first = false;
13367            self.out
13368                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13369                    &key.to_string_lossy(),
13370                )));
13371            self.out.push_str(": ");
13372            // An accessor has no value to dump; the reference names the half that
13373            // exists instead of calling it.
13374            if property.is_accessor() {
13375                let text = match (property.getter.is_some(), property.setter.is_some()) {
13376                    (true, true) => "[Getter/Setter]",
13377                    (false, true) => "[Setter]",
13378                    _ => "[Getter]",
13379                };
13380                self.out.push_str(text);
13381            } else {
13382                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13383            }
13384        }
13385        self.out.push_str(" }");
13386    }
13387
13388    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13389    fn print_string(&mut self, text: &str) {
13390        self.out.push('"');
13391        for character in text.chars() {
13392            match character {
13393                '"' => self.out.push_str("\\\""),
13394                '\\' => self.out.push_str("\\\\"),
13395                '\n' => self.out.push_str("\\n"),
13396                '\r' => self.out.push_str("\\r"),
13397                '\t' => self.out.push_str("\\t"),
13398                c if (c as u32) < 0x20 => {
13399                    self.out.push_str(&format!("\\u{:04x}", c as u32));
13400                }
13401                c => self.out.push(c),
13402            }
13403        }
13404        self.out.push('"');
13405    }
13406}
13407
13408/// How `print` renders a value.
13409///
13410/// `ToString`, except that negative zero keeps its sign — the reference's host
13411/// printer does that while `String(-0)` is `"0"`.
13412pub fn display(value: &Value) -> String {
13413    match value {
13414        Value::Float(number) => crate::value::number_to_string_for_print(*number),
13415        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13416            "undefined".to_string()
13417        }
13418        other => other.to_js_string(),
13419    }
13420}
13421
13422// ---------------------------------------------------------------------------
13423// Numeric operators
13424// ---------------------------------------------------------------------------
13425
13426/// `a + b` keeping the `Int` representation when it fits.
13427fn add_numbers(left: Value, right: Value) -> Value {
13428    match (&left, &right) {
13429        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13430            Some(sum) => Value::Int(sum),
13431            None => Value::Float(*a as f64 + *b as f64),
13432        },
13433        _ => Value::Float(left.to_number() + right.to_number()),
13434    }
13435}
13436
13437/// The arithmetic operators other than `+`, which needs string concatenation.
13438fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13439    use Opcode::*;
13440    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13441    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13442    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13443    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13444        return Ok(match op {
13445            And => Value::Int(x & y),
13446            Or => Value::Int(x | y),
13447            Xor => Value::Int(x ^ y),
13448            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13449            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13450            Shr => match (*x as u32) >> ((*y as u32) & 31) {
13451                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13452                shifted => Value::Float(shifted as f64),
13453            },
13454            Sub => match x.checked_sub(*y) {
13455                Some(value) => Value::Int(value),
13456                None => Value::Float(*x as f64 - *y as f64),
13457            },
13458            _ => return arithmetic_slow(op, left, right),
13459        });
13460    }
13461    arithmetic_slow(op, left, right)
13462}
13463
13464/// [`arithmetic`] for everything the integer fast path above does not take.
13465fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13466    use Opcode::*;
13467    let (a, b) = (left.to_number(), right.to_number());
13468    Ok(match op {
13469        Sub => match (&left, &right) {
13470            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13471                Some(value) => Value::Int(value),
13472                None => Value::Float(a - b),
13473            },
13474            _ => Value::Float(a - b),
13475        },
13476        Mul => Value::Float(a * b),
13477        Div => Value::Float(a / b),
13478        Mod => Value::Float(js_mod(a, b)),
13479        Pow => Value::Float(a.powf(b)),
13480        And => Value::Int(left.to_int32() & right.to_int32()),
13481        Or => Value::Int(left.to_int32() | right.to_int32()),
13482        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13483        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13484        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13485        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13486        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13487        // fits the small-integer representation stays an `Int`; the rest become a
13488        // float, which is how the reference keeps `n >>> 0` non-negative.
13489        Shr => {
13490            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13491            match i32::try_from(shifted) {
13492                Ok(value) => Value::Int(value),
13493                Err(_) => Value::Float(shifted as f64),
13494            }
13495        }
13496        _ => Value::Float(a),
13497    })
13498}
13499
13500/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13501///
13502/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13503/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13504/// slow path where the rules live.
13505fn is_number(value: &Value) -> bool {
13506    matches!(value, Value::Int(_) | Value::Float(_))
13507}
13508
13509/// The `Value::Bool` a comparison operator answers for `ordering`.
13510///
13511/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13512/// false for it, including `<=` and `>=`.
13513fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13514    use Opcode::*;
13515    let answer = match (op, ordering) {
13516        (_, None) => false,
13517        (Lt, Some(ordering)) => ordering.is_lt(),
13518        (Lte, Some(ordering)) => ordering.is_le(),
13519        (Gt, Some(ordering)) => ordering.is_gt(),
13520        (Gte, Some(ordering)) => ordering.is_ge(),
13521        _ => false,
13522    };
13523    Value::Bool(answer)
13524}
13525
13526/// `%`, which follows the sign of the dividend rather than Rust's.
13527fn js_mod(left: f64, right: f64) -> f64 {
13528    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13529        return f64::NAN;
13530    }
13531    if right.is_infinite() {
13532        return left;
13533    }
13534    let remainder = left % right;
13535    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13536    // the spec makes the sign match the dividend.
13537    if remainder == 0.0 {
13538        0.0f64.copysign(left)
13539    } else {
13540        remainder
13541    }
13542}
13543
13544fn negate(value: Value) -> Value {
13545    match value {
13546        Value::Int(0) => Value::Float(-0.0),
13547        Value::Int(i) => Value::Int(-i),
13548        other => Value::Float(-other.to_number()),
13549    }
13550}
13551
13552fn increment(value: Value) -> Value {
13553    match value {
13554        Value::Int(i) => match i.checked_add(1) {
13555            Some(next) => Value::Int(next),
13556            None => Value::Float(i as f64 + 1.0),
13557        },
13558        other => Value::Float(other.to_number() + 1.0),
13559    }
13560}
13561
13562fn decrement(value: Value) -> Value {
13563    match value {
13564        Value::Int(i) => match i.checked_sub(1) {
13565            Some(next) => Value::Int(next),
13566            None => Value::Float(i as f64 - 1.0),
13567        },
13568        other => Value::Float(other.to_number() - 1.0),
13569    }
13570}
13571
13572/// Compare a `BigInt` with an `f64` on their mathematical values.
13573///
13574/// Neither side is rounded to the other's precision: the number is split into its integer
13575/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13576/// when the integer parts are equal. An infinite value is larger than every bigint.
13577fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13578    use std::cmp::Ordering;
13579    if number.is_nan() {
13580        return None;
13581    }
13582    if number.is_infinite() {
13583        return Some(if number > 0.0 {
13584            Ordering::Less
13585        } else {
13586            Ordering::Greater
13587        });
13588    }
13589    let truncated = number.trunc();
13590    // A number wider than `i128` still has an exact integer part, but no bigint form we can
13591    // build cheaply; the sign of the difference is all that is needed, so compare against
13592    // the bigint's own magnitude instead.
13593    if truncated.abs() >= 1.7e38 {
13594        let big_as_f64 = big.to_f64();
13595        return big_as_f64.partial_cmp(&number);
13596    }
13597    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13598    match big.cmp(&integer) {
13599        Ordering::Equal => {
13600            // Same integer part: the fraction decides, and a negative number's fraction is
13601            // below the integer (`-1.5` truncates to `-1`).
13602            if number > truncated {
13603                Some(Ordering::Less)
13604            } else if number < truncated {
13605                Some(Ordering::Greater)
13606            } else {
13607                Some(Ordering::Equal)
13608            }
13609        }
13610        other => Some(other),
13611    }
13612}