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        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
4661        // remembered a global's slot index since M12b, but the *store* side never did: it
4662        // converted the name to a `PropertyKey` (two allocations) and then scanned the
4663        // global object's whole table — which holds every builtin — on every assignment to
4664        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
4665        // full global lookup per iteration; measured with a counter, `s` as a global made
4666        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
4667        //
4668        // Re-validated exactly like the read: same object, same index, still the name, and
4669        // — the one extra check a store needs — still writable. A global that is an
4670        // accessor, non-writable, or inherited fails here and falls through to the full
4671        // path below, which reports the failure the way it always did.
4672        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4673        let global = self.realm.global.clone();
4674        if let Some(cached) = &self.global_cache[site]
4675            && global.upgrades_to(&cached.object)
4676            && global.write_data_at(cached.index, &name, value.clone())
4677        {
4678            return Ok(());
4679        }
4680        match global.own_property(&name) {
4681            // A `var` global is writable, so the store goes straight through — but
4682            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4683            // store (a non-writable or accessor-without-setter global) is a silent
4684            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4685            // split every other assignment has.
4686            Some(_) => {
4687                let on_failure = if self.current_strict() {
4688                    DeleteFailure::Throw
4689                } else {
4690                    DeleteFailure::Ignore
4691                };
4692                let result = self.set_property_with(&global, &name, value, on_failure);
4693                // Teach the cache the slot for a plain writable own data property, which is
4694                // what a declared `var` is. Without this the fast path above could never
4695                // fire for a global that is only ever *written* — its entry would have to
4696                // be put there by a read of the same slot, and a write-only loop has none.
4697                if result.is_ok()
4698                    && let Some(index) = global.own_data_index(&name)
4699                {
4700                    self.global_cache[site] = Some(GlobalCache {
4701                        object: global.downgrade(),
4702                        index,
4703                    });
4704                }
4705                result
4706            }
4707            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4708            // declaration creates a *configurable* property, which is what makes it
4709            // deletable and is the one way a global differs from a declared `var`.
4710            // In strict mode the same store is a `ReferenceError` instead: that is the
4711            // whole point of strict mode, and creating the global silently meant
4712            // `"use strict"; x = 1` looked like it worked.
4713            None => {
4714                if self.current_strict() {
4715                    return Err(self.throw_reference(&name));
4716                }
4717                // A direct eval declares here rather than on the global object: its
4718                // `var`s belong to the caller's variable environment. `declare_eval_local`
4719                // also covers a plain assignment to a variable an earlier eval made.
4720                if let Some(cell) = self.declare_eval_local(&name) {
4721                    cell.set(value);
4722                    return Ok(());
4723                }
4724                global.define_data(&name, value);
4725                Ok(())
4726            }
4727        }
4728    }
4729
4730    /// The value of a binding of the frame that called `eval`, if there is one.
4731    fn eval_binding_value(&self, name: &str) -> Option<Value> {
4732        let binding = self
4733            .eval_bindings
4734            .iter()
4735            .find(|binding| binding.name == name)?;
4736        let owner = self.frames.get(binding.frame)?;
4737        let (slot, index) = (binding.slot, binding.index);
4738        Some(match slot {
4739            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4740                cell if cell >= 0 => owner
4741                    .cells
4742                    .get(cell as usize)
4743                    .map(|cell| cell.get())
4744                    .unwrap_or(Value::Undefined),
4745                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4746            },
4747            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4748                cell if cell >= 0 => owner
4749                    .cells
4750                    .get(cell as usize)
4751                    .map(|cell| cell.get())
4752                    .unwrap_or(Value::Undefined),
4753                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4754            },
4755        })
4756    }
4757
4758    /// Write to a binding of the frame that called `eval`.
4759    ///
4760    /// `Ok(false)` means no binding matched and the caller should keep looking. A
4761    /// matched binding can still refuse the store, which is why this is fallible: a
4762    /// `const` is read-only everywhere, and a named function expression's own name is
4763    /// read-only in strict mode.
4764    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4765        let Some(binding) = self
4766            .eval_bindings
4767            .iter()
4768            .find(|binding| binding.name == name)
4769        else {
4770            return Ok(false);
4771        };
4772        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4773        let strict = self.current_strict();
4774        let Some(owner) = self.frames.get_mut(frame) else {
4775            return Ok(false);
4776        };
4777        match slot {
4778            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4779                cell if cell >= 0 => {
4780                    if let Some(cell) = owner.cells.get(cell as usize) {
4781                        cell.set(value.clone());
4782                    }
4783                }
4784                _ => {
4785                    if let Some(slot) = owner.args.get_mut(index) {
4786                        *slot = value.clone();
4787                    }
4788                }
4789            },
4790            EvalSlot::Local => {
4791                let declared = owner.code.code.vars.get(index);
4792                // A `const` is read-only even through `eval`. The realm records this for
4793                // globals (see `lexical_consts`), but a local's `const`-ness is only in
4794                // the bytecode, so this is where it has to be enforced.
4795                if declared.is_some_and(|var| var.is_const) {
4796                    return Err(self.read_only_local(name));
4797                }
4798                // The name of a named function expression is read-only too, but only
4799                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4800                // such a name is ignored, the same as a direct store would be.
4801                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4802                    return if strict {
4803                        Err(self.read_only_local(name))
4804                    } else {
4805                        Ok(true)
4806                    };
4807                }
4808                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4809                    cell if cell >= 0 => {
4810                        if let Some(cell) = owner.cells.get(cell as usize) {
4811                            cell.set(value.clone());
4812                        }
4813                    }
4814                    _ => {
4815                        if let Some(slot) = owner.locals.get_mut(index) {
4816                            *slot = value.clone();
4817                        }
4818                    }
4819                }
4820            }
4821        }
4822        Ok(true)
4823    }
4824
4825    /// The `TypeError` an assignment to a read-only binding raises.
4826    fn read_only_local(&self, name: &str) -> Signal {
4827        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4828    }
4829
4830    /// Declare `name` as a variable of the frame that called the running `eval`.
4831    ///
4832    /// `None` when there is no direct eval in progress, or it was called from the top
4833    /// level — then the caller's variable environment *is* the global one and the
4834    /// existing path is right.
4835    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4836        let caller = self.eval_caller.flatten()?;
4837        // The bottom frame is the top-level script, whose variable environment *is* the
4838        // global one — so `eval("var x = 1")` at the top level still creates a global.
4839        if caller == 0 {
4840            return None;
4841        }
4842        // A name the eval's *own* variable environment already binds is not a new
4843        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4844        // `arguments`, and creating a second binding would leave the first — the one
4845        // closures read — untouched. A binding of an *outer* frame does not count: a
4846        // declaration shadows it rather than writing through.
4847        if self
4848            .eval_bindings
4849            .iter()
4850            .any(|binding| binding.name == name && binding.frame == caller)
4851        {
4852            return None;
4853        }
4854        let phase = if self.in_parameter_list_at(caller) {
4855            0
4856        } else {
4857            1
4858        };
4859        self.frame_local_vars(caller)?;
4860        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4861        if let Some(cell) = local_vars.get(name, 1) {
4862            return Some(cell);
4863        }
4864        let cell = self.new_cell(Value::Undefined);
4865        Some(local_vars.declare(name, phase, cell))
4866    }
4867
4868    /// Make sure `frame` has a `LocalVars`, creating it on demand.
4869    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4870        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4871            return Some(local_vars.clone());
4872        }
4873        let local_vars = Gc::new(self.heap, LocalVars::new());
4874        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4875        Some(local_vars)
4876    }
4877
4878    /// Whether the realm already has a binding for `name`, lexically or as an *own*
4879    /// property of the global object. Used to decide whether a store inside an
4880    /// `eval` writes through to the realm or declares a binding of its own.
4881    ///
4882    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4883    /// write to `Object.prototype.toString`, and must not shadow it either.
4884    fn global_knows(&mut self, name: &str) -> bool {
4885        if self.realm.globals.contains_key(name) {
4886            return true;
4887        }
4888        self.realm.global.own_property(name).is_some()
4889    }
4890
4891    /// Whether the code currently running is strict.
4892    ///
4893    /// Read off the frame's function, which is where the parser's answer ended up; a
4894    /// native function never runs strict-only checks, and there is no frame at all
4895    /// before the first script.
4896    pub fn current_strict(&self) -> bool {
4897        self.frames
4898            .last()
4899            .is_some_and(|frame| frame.code.code.strict)
4900    }
4901
4902    /// Initialise a declared global, which is what ends its dead zone.
4903    ///
4904    /// A `var` global becomes a property of the global object: writable, so a later
4905    /// assignment goes through, and non-configurable, so `delete` refuses.
4906    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4907        let (name, lexical, _) = self.global_binding(slot);
4908        // A `var` declared by the strict `eval` currently running belongs to the
4909        // eval's scope, not to the global object: `eval("var v = 1")` must not make
4910        // `typeof v` answer `"number"` afterwards. A name the realm already has is
4911        // initialised in place, which is what a re-declaration inside eval does.
4912        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4913            self.eval_scope
4914                .as_mut()
4915                .expect("checked above")
4916                .insert(name, value);
4917            return Ok(());
4918        }
4919        if let Some(scope) = self.eval_scope.as_mut()
4920            && scope.contains_key(&name)
4921        {
4922            scope.insert(name, value);
4923            return Ok(());
4924        }
4925        if lexical {
4926            // The cell exists (created at declaration time) holding the dead-zone
4927            // marker; storing the value is what makes the binding readable.
4928            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4929                cell.set(value);
4930                return Ok(());
4931            }
4932            let cell = self.new_cell(value);
4933            self.realm.globals.insert(name, cell);
4934            return Ok(());
4935        }
4936        let global = self.realm.global.clone();
4937        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4938        // to answer `false` and leave the binding in place. `with_attributes` ties
4939        // `configurable` to `writable`, so the property is built field by field.
4940        global.define(
4941            &name,
4942            Property {
4943                value: Some(value),
4944                writable: true,
4945                enumerable: true,
4946                configurable: false,
4947                ..Property::default()
4948            },
4949        );
4950        Ok(())
4951    }
4952
4953    /// The `TypeError` a store to a `const` global raises.
4954    fn read_only_global(&self, name: &str) -> Signal {
4955        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4956    }
4957
4958    // -- properties ---------------------------------------------------------
4959
4960    /// Read `object[key]`, following the prototype chain.
4961    ///
4962    /// An inherited accessor runs with the *receiver* as `this`, which is why the
4963    /// lookup returns the owner rather than just the value.
4964    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4965        self.get_property_key(object, &PropertyKey::from(key))
4966    }
4967
4968    /// [`Interp::get_property`] with a key that may be a symbol.
4969    pub fn get_property_key(
4970        &mut self,
4971        object: &Gc<JsObject>,
4972        key: &PropertyKey,
4973    ) -> JsResult<Option<Value>> {
4974        self.get_property_key_for(object, None, key)
4975    }
4976
4977    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
4978    ///
4979    /// The receiver matters when the property is found on a *prototype*: a getter has to
4980    /// see the object the read started from. For a primitive that is the primitive
4981    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
4982    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4983    /// the owner.
4984    pub fn get_property_key_for(
4985        &mut self,
4986        object: &Gc<JsObject>,
4987        receiver: Option<&Value>,
4988        key: &PropertyKey,
4989    ) -> JsResult<Option<Value>> {
4990        // A proxy answers for itself, before any of the shortcuts below: `new
4991        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4992        // have.
4993        if object.proxy_state().is_some() {
4994            let receiver = receiver
4995                .cloned()
4996                .unwrap_or_else(|| Value::Object(object.clone()));
4997            return self.proxy_get(object, &receiver, key);
4998        }
4999        // A host class's `get_property` trap replaces the whole read, prototype walk
5000        // included — that is what makes a native accessor free rather than a JavaScript
5001        // getter call.
5002        if let Some(exotic) = object.exotic() {
5003            let receiver_value = receiver
5004                .cloned()
5005                .unwrap_or_else(|| Value::Object(object.clone()));
5006            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5007                return Ok(Some(value));
5008            }
5009            // With no `get_property` trap, a `get_own_property` trap still answers for the
5010            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5011            // and the hook lives exactly there. A key the trap reports as absent is still
5012            // looked for on the prototype, which is why the search resumes *above*.
5013            if let Some(property) = exotic.get_own_property(self, object, key)? {
5014                return match property {
5015                    Some(property) => self.read_property(property, object, receiver),
5016                    None => match lookup_key_above(object, key) {
5017                        Some((_, property)) => self.read_property(property, object, receiver),
5018                        None => Ok(None),
5019                    },
5020                };
5021            }
5022        }
5023        // The element-vector and `length` shortcuts are string-only: an array index
5024        // has no symbol spelling.
5025        if let Some(text) = key.as_str() {
5026            if let Some(value) = self.own_element(object, text) {
5027                return Ok(Some(value));
5028            }
5029            // `length` is not stored as a property: an array's length is its element
5030            // count, and keeping one copy of it is what makes `push`/`pop` and
5031            // `a.length = n` agree.
5032            if let Some(length) = object.array_length()
5033                && text == "length"
5034            {
5035                // Not `Value::Int(length as i32)`: see [`length_value`].
5036                return Ok(Some(crate::object::length_value(length)));
5037            }
5038        }
5039        match lookup_key(object, key) {
5040            Some((_, property)) => self.read_property(property, object, receiver),
5041            None => Ok(None),
5042        }
5043    }
5044
5045    /// The value a property read answers.
5046    ///
5047    /// One place rather than three, because an accessor has to run with the *receiver* as
5048    /// `this` whether the descriptor came from the property table, an exotic
5049    /// `get_own_property` trap, or a prototype above one.
5050    fn read_property(
5051        &mut self,
5052        property: Property,
5053        object: &Gc<JsObject>,
5054        receiver: Option<&Value>,
5055    ) -> JsResult<Option<Value>> {
5056        if property.is_accessor() {
5057            match &property.getter {
5058                Some(getter) if !matches!(getter, Value::Undefined) => {
5059                    let receiver = receiver
5060                        .cloned()
5061                        .unwrap_or_else(|| Value::Object(object.clone()));
5062                    self.call_value(getter.clone(), receiver, Vec::new())
5063                        .map(Some)
5064                }
5065                // An accessor with no getter reads as `undefined`.
5066                _ => Ok(Some(Value::Undefined)),
5067            }
5068        } else {
5069            Ok(property.value)
5070        }
5071    }
5072
5073    /// `super.key` — start the search at `proto`, but report to `receiver`.
5074    ///
5075    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5076    /// found on the prototype of a class has to see the *instance* as `this`, and a
5077    /// plain property read off `proto` would lose that.
5078    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5079        let start = self.require_object(proto)?;
5080        let key = self.propkey(key)?;
5081        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5082        if matches!(proto, Value::Null) {
5083            return Ok(Value::Undefined);
5084        }
5085        match lookup_key(&start, &key) {
5086            Some((_, property)) if property.is_accessor() => match &property.getter {
5087                Some(getter) if !matches!(getter, Value::Undefined) => {
5088                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5089                }
5090                _ => Ok(Value::Undefined),
5091            },
5092            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5093            None => Ok(Value::Undefined),
5094        }
5095    }
5096
5097    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5098    ///
5099    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5100    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5101    /// assignment follows.
5102    fn super_write(
5103        &mut self,
5104        receiver: &Value,
5105        proto: &Value,
5106        key: &Value,
5107        value: Value,
5108    ) -> JsResult<()> {
5109        let target = self.require_object(receiver)?;
5110        let key = self.propkey(key)?;
5111        if !matches!(proto, Value::Null)
5112            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5113        {
5114            if property.is_accessor() {
5115                if let Some(setter) = &property.setter
5116                    && !matches!(setter, Value::Undefined)
5117                {
5118                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5119                }
5120                return Ok(());
5121            }
5122            // A data property on the prototype is writable or not; reading `owner` at
5123            // all is only for the attribute check.
5124            if !property.writable {
5125                return Err(self.type_error(format!("'{key}' is read-only")));
5126            }
5127            let _ = owner;
5128        }
5129        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5130    }
5131
5132    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5133    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5134        match value.as_object() {
5135            Some(object) => Ok(object.clone()),
5136            None => Err(Signal::Throw(
5137                self.make_error("TypeError", "value is not an object"),
5138            )),
5139        }
5140    }
5141
5142    /// Build the class object `define_class` produces.
5143    ///
5144    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5145    /// whose prototype property is a fresh object inheriting from the parent's
5146    /// prototype, and whose own prototype is the parent constructor — which is what makes
5147    /// a static method inherited too.
5148    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5149        let ctor = self.pop();
5150        let parent = self.pop();
5151        let Value::Object(function) = &ctor else {
5152            return Err(Signal::Throw(
5153                self.make_error("TypeError", "class constructor must be a function"),
5154            ));
5155        };
5156        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5157        // but gives the instances no prototype at all.
5158        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5159            match &parent {
5160                Value::Null => (Some(self.realm.function_proto.clone()), None),
5161                Value::Object(parent_class) => {
5162                    if !parent_class.is_callable() {
5163                        return Err(Signal::Throw(
5164                            self.make_error("TypeError", "parent class must be constructor"),
5165                        ));
5166                    }
5167                    let proto = self.get_property(parent_class, "prototype")?;
5168                    match proto {
5169                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5170                        Some(Value::Null) => (Some(parent_class.clone()), None),
5171                        _ => {
5172                            return Err(Signal::Throw(self.make_error(
5173                                "TypeError",
5174                                "parent prototype must be an object or null",
5175                            )));
5176                        }
5177                    }
5178                }
5179                _ => {
5180                    return Err(Signal::Throw(
5181                        self.make_error("TypeError", "parent class must be constructor"),
5182                    ));
5183                }
5184            }
5185        } else {
5186            (
5187                Some(self.realm.function_proto.clone()),
5188                Some(self.realm.object_proto.clone()),
5189            )
5190        };
5191        let proto = self.new_object(parent_proto);
5192        function.set_proto(parent_ctor);
5193        // A class is not callable without `new`, and its `prototype` is not writable —
5194        // both follow from being a class and are what `class A {}; A()` throws on.
5195        function.set_class_constructor(true);
5196        function.set_home_object(None);
5197        self.set_function_name(&ctor, name);
5198        self.define_class_properties(function, &ctor, &proto)?;
5199        Ok((ctor, proto))
5200    }
5201
5202    /// Give the constructor its `prototype` and `length`, and the prototype its
5203    /// `constructor` back-pointer.
5204    fn define_class_properties(
5205        &mut self,
5206        function: &Gc<JsObject>,
5207        ctor: &Value,
5208        proto: &Gc<JsObject>,
5209    ) -> JsResult<()> {
5210        proto.define(
5211            "constructor",
5212            Property::with_attributes(ctor.clone(), true, false),
5213        );
5214        function.define(
5215            "prototype",
5216            Property::prototype_of(Value::Object(proto.clone()), false),
5217        );
5218        if let Some((code, _)) = bytecode_of(function) {
5219            let length = code.code.defined_args;
5220            function.define(
5221                "length",
5222                Property::name_or_length(Value::Int(length as i32)),
5223            );
5224        }
5225        Ok(())
5226    }
5227
5228    /// The own array element `key` names, if this object has one.
5229    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5230        let index = array_index(key)?;
5231        // A typed array's elements live in its buffer, not in a property list: reading one
5232        // goes through the view's element type so a bounds check and a detached buffer are
5233        // both handled there.
5234        if object.typed_array_parts().is_some() {
5235            return object.typed_array_element(index as usize);
5236        }
5237        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5238        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5239        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5240        // `[1,,3][1]`.
5241        match object.array_get(index as usize) {
5242            Some(Value::Hole) | None => None,
5243            other => other,
5244        }
5245    }
5246
5247    /// Store `object[key] = value`, honouring setters and inherited properties.
5248    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5249        self.set_property_with(object, key, value, DeleteFailure::Throw)
5250    }
5251
5252    /// Store a property, choosing what to do when the object refuses.
5253    ///
5254    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5255    /// mode, which is the one place assignment differs by mode. Native code (the array
5256    /// methods, `JSON`) always asks for the throw.
5257    pub fn set_property_with(
5258        &mut self,
5259        object: &Gc<JsObject>,
5260        key: &str,
5261        value: Value,
5262        on_failure: DeleteFailure,
5263    ) -> JsResult<()> {
5264        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5265    }
5266
5267    /// [`Interp::set_property_with`] with a key that may be a symbol.
5268    pub fn set_property_with_key(
5269        &mut self,
5270        object: &Gc<JsObject>,
5271        key: &PropertyKey,
5272        value: Value,
5273        on_failure: DeleteFailure,
5274    ) -> JsResult<()> {
5275        self.set_property_with_key_receiver_aware(object, key, value, on_failure, true)
5276    }
5277
5278    /// As [`Interp::set_property_with_key`], with the receiver explicit.
5279    ///
5280    /// `same_receiver` is `SameValue(O, Receiver)` from §10.4.5.5 step 1.b.i, and the two
5281    /// branches it separates are observable in opposite directions: when the receiver *is*
5282    /// the view the element store converts `V` first and then asks whether the index is
5283    /// valid (`Set/resized-out-of-bounds-to-in-bounds-index`, where a `valueOf` puts the
5284    /// index back in bounds), and when it is not, an invalid index returns `true` without
5285    /// converting anything (`key-is-out-of-bounds-receiver-is-not-object`).
5286    fn set_property_with_key_receiver_aware(
5287        &mut self,
5288        object: &Gc<JsObject>,
5289        key: &PropertyKey,
5290        value: Value,
5291        on_failure: DeleteFailure,
5292        same_receiver: bool,
5293    ) -> JsResult<()> {
5294        // A proxy's `set` trap decides, and its `false` means the same thing an
5295        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5296        if object.proxy_state().is_some() {
5297            let receiver = Value::Object(object.clone());
5298            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5299                return match (accepted, on_failure) {
5300                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5301                    (false, DeleteFailure::Throw) => {
5302                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5303                    }
5304                };
5305            }
5306        }
5307        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5308        // refusal and means exactly what a proxy's `false` means.
5309        if let Some(exotic) = object.exotic() {
5310            let receiver = Value::Object(object.clone());
5311            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5312                return match (accepted, on_failure) {
5313                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5314                    (false, DeleteFailure::Throw) => {
5315                        Err(self.type_error(format!("property '{key}' is read-only")))
5316                    }
5317                };
5318            }
5319        }
5320        // The element and `length` shortcuts only exist for string keys: an array
5321        // index has no symbol spelling, and a symbol named `length` is an ordinary
5322        // property.
5323        let text = key.as_str();
5324        // A typed array's elements are a window onto its buffer: the store has to go
5325        // through the view's element type so the value is wrapped (or clamped) and so an
5326        // out-of-range or detached write is a silent no-op, as the spec says.
5327        if let Some(text) = text
5328            && let Some(index) = array_index(text)
5329            && let Some(element) = object.typed_array_element_type()
5330        {
5331            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5332            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5333            // in `Interp`, because it is script-observable and the storage borrow inside
5334            // `typed_array_set` must not be held across it.
5335            //
5336            // It runs even for an index that is out of bounds *now*, because `V` itself can
5337            // put it back in bounds: `TypedArraySetElement` converts first and asks
5338            // `IsValidIntegerIndex` afterwards, which is what
5339            // `Set/resized-out-of-bounds-to-in-bounds-index` asserts (a `valueOf` that
5340            // resizes a 0-byte buffer to 1 makes `ta[0] = value` store 100). The write is
5341            // still a no-op when the index stays out of bounds, which is why the extra
5342            // length check that used to guard this has no job left.
5343            if !same_receiver && index as usize >= object.typed_array_length().unwrap_or(0) {
5344                return Ok(());
5345            }
5346            let stored = self.element_value(element, value)?;
5347            if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5348                return Err(self.type_error(reason));
5349            }
5350            return Ok(());
5351        }
5352        if let Some(text) = text
5353            && let Some(index) = array_index(text)
5354            && object.is_array()
5355        {
5356            // An accessor defined on an index lives in the property table while the
5357            // element slot is a hole, so the store has to go through the property first.
5358            // Writing the vector directly skipped the setter entirely.
5359            if let Some(existing) = object.own_property_key(key) {
5360                if existing.is_accessor() {
5361                    return match existing.setter.clone() {
5362                        Some(setter) if !matches!(setter, Value::Undefined) => {
5363                            let receiver = Value::Object(object.clone());
5364                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5365                        }
5366                        _ => match on_failure {
5367                            DeleteFailure::Throw => Err(self.type_error(format!(
5368                                "cannot set property '{text}', it has only a getter"
5369                            ))),
5370                            DeleteFailure::Ignore => Ok(()),
5371                        },
5372                    };
5373                }
5374                if !existing.writable {
5375                    return match on_failure {
5376                        DeleteFailure::Throw => {
5377                            Err(self.type_error(format!("'{text}' is read-only")))
5378                        }
5379                        DeleteFailure::Ignore => Ok(()),
5380                    };
5381                }
5382            }
5383            {
5384                // Growing the array needs a writable `length`.
5385                if (index as usize) >= object.array_length().unwrap_or(0)
5386                    && !object.length_writable()
5387                {
5388                    return match on_failure {
5389                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5390                        DeleteFailure::Ignore => Ok(()),
5391                    };
5392                }
5393                // Adding an index past the end makes the array longer, which a
5394                // non-extensible array refuses.
5395                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5396                    return match on_failure {
5397                        DeleteFailure::Throw => Err(self.type_error(format!(
5398                            "cannot add property '{key}', object is not extensible"
5399                        ))),
5400                        DeleteFailure::Ignore => Ok(()),
5401                    };
5402                }
5403                if object.element_is_locked(index) {
5404                    return match on_failure {
5405                        DeleteFailure::Throw => {
5406                            Err(self.type_error(format!("'{key}' is read-only")))
5407                        }
5408                        DeleteFailure::Ignore => Ok(()),
5409                    };
5410                }
5411                // The element vector is only half of `[[Set]]` for an index: the
5412                // prototype chain is consulted first, and a setter there answers instead
5413                // of the element store. This branch used to write the element directly, so
5414                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5415                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5416                // the reference calls the setter and the array keeps no own index.
5417                if let Some((owner, property)) = lookup_key(object, key)
5418                    && !owner.ptr_eq(object)
5419                {
5420                    match &property {
5421                        property if property.is_accessor() => {
5422                            match &property.setter {
5423                                Some(setter) if !matches!(setter, Value::Undefined) => {
5424                                    let receiver = Value::Object(object.clone());
5425                                    self.call_value(setter.clone(), receiver, vec![value])?;
5426                                }
5427                                _ => {
5428                                    return match on_failure {
5429                                        DeleteFailure::Throw => Err(self.type_error(format!(
5430                                            "cannot set property '{text}', it has only a getter"
5431                                        ))),
5432                                        DeleteFailure::Ignore => Ok(()),
5433                                    };
5434                                }
5435                            }
5436                            return Ok(());
5437                        }
5438                        property if !property.writable => {
5439                            return match on_failure {
5440                                DeleteFailure::Throw => {
5441                                    Err(self.type_error(format!("'{text}' is read-only")))
5442                                }
5443                                DeleteFailure::Ignore => Ok(()),
5444                            };
5445                        }
5446                        _ => {}
5447                    }
5448                }
5449                if object.array_set(self.heap, index as usize, value.clone()) {
5450                    return Ok(());
5451                }
5452                // Past the dense limit the slot is too far out to be worth one `Value`
5453                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5454                // constant time by keeping the index as an ordinary property. The store
5455                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5456                // to a legal program.
5457                object.define_key(key, Property::with_attributes(value, true, true));
5458                // Extend, never shorten: the index may be *inside* the current length (a
5459                // huge `length` with a sparse store), and shortening would delete the
5460                // sparse properties above it — including the one just stored.
5461                if index as usize + 1 > object.array_length().unwrap_or(0) {
5462                    object.array_set_length(self.heap, index as usize + 1);
5463                }
5464                return Ok(());
5465            }
5466        }
5467        if text == Some("length") && object.is_array() {
5468            if !object.length_writable() {
5469                return match on_failure {
5470                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5471                    DeleteFailure::Ignore => Ok(()),
5472                };
5473            }
5474            let length = value.to_number();
5475            if length.is_finite() && length >= 0.0 {
5476                let length = length as usize;
5477                // `a.length = n` with `n` below a non-configurable element cannot
5478                // drop that element, so the whole assignment fails. The spec makes
5479                // this a `TypeError` rather than a silent no-op, in any mode.
5480                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5481                    // Sloppy mode stops the truncation at the blocking element
5482                    // instead of failing; strict mode raises.
5483                    // Both modes stop at the blocking element; they differ in
5484                    // whether that is reported. The reference truncates *then*
5485                    // throws, so the array is left in the shortened state.
5486                    object.array_truncate(self.heap, blocked + 1);
5487                    return match on_failure {
5488                        DeleteFailure::Throw => {
5489                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5490                        }
5491                        DeleteFailure::Ignore => Ok(()),
5492                    };
5493                }
5494                object.array_set_length(self.heap, length);
5495                return Ok(());
5496            }
5497        }
5498        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5499        {
5500            return match on_failure {
5501                DeleteFailure::Throw => Err(self.type_error(format!(
5502                    "cannot add property {}, object is not extensible",
5503                    key
5504                ))),
5505                DeleteFailure::Ignore => Ok(()),
5506            };
5507        }
5508        if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5509            if property.is_accessor() {
5510                match &property.setter {
5511                    Some(setter) if !matches!(setter, Value::Undefined) => {
5512                        let receiver = Value::Object(object.clone());
5513                        self.call_value(setter.clone(), receiver, vec![value])?;
5514                    }
5515                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5516                    // Sloppy code swallows that refusal, strict code raises — the same
5517                    // rule the read-only *data* property below follows, and skipping it
5518                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5519                    // return silently. The reference answers `TypeError: 'x' is
5520                    // read-only`.
5521                    _ => {
5522                        return match on_failure {
5523                            DeleteFailure::Throw => {
5524                                Err(self.type_error(format!("'{key}' is read-only")))
5525                            }
5526                            DeleteFailure::Ignore => Ok(()),
5527                        };
5528                    }
5529                }
5530                return Ok(());
5531            }
5532            // A non-writable data property refuses the write, own **or inherited**: an
5533            // own one stops here because nothing may change it, and an inherited one
5534            // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5535            //
5536            // The `ptr_eq` this used to carry meant an inherited read-only property fell
5537            // through to `define_data_key` and *did* create the shadow — `var o =
5538            // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5539            // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5540            // and `false`.
5541            if !property.writable {
5542                return match on_failure {
5543                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5544                    DeleteFailure::Ignore => Ok(()),
5545                };
5546            }
5547            // An existing writable own property keeps its attributes: only the value
5548            // moves. Redefining instead would reset them, which is how a
5549            // non-configurable global `var` used to become deletable.
5550            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5551                return Ok(());
5552            }
5553        }
5554        // No own data property: create one, shadowing whatever the prototype holds.
5555        object.define_data_key(key, value);
5556        Ok(())
5557    }
5558
5559    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5560    ///
5561    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5562    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5563    /// a virtual accessor gets its setter run without implementing `set_property` at all.
5564    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5565    /// the prototype, so the walk resumes above the object.
5566    fn lookup_for_write(
5567        &mut self,
5568        object: &Gc<JsObject>,
5569        key: &PropertyKey,
5570    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5571        let Some(exotic) = object.exotic() else {
5572            return Ok(lookup_key(object, key));
5573        };
5574        Ok(match exotic.get_own_property(self, object, key)? {
5575            Some(Some(property)) => Some((object.clone(), property)),
5576            Some(None) => lookup_key_above(object, key),
5577            None => lookup_key(object, key),
5578        })
5579    }
5580
5581    /// Delete `object[key]`.
5582    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5583        self.delete_property_key(object, &PropertyKey::from(key))
5584    }
5585
5586    /// [`Interp::delete_property`] with a key that may be a symbol.
5587    pub fn delete_property_key(
5588        &mut self,
5589        object: &Gc<JsObject>,
5590        key: &PropertyKey,
5591    ) -> JsResult<bool> {
5592        // A proxy decides for itself, and may even throw; the invariant checks live in
5593        // `proxy_delete`.
5594        if let Some(answer) = self.proxy_delete(object, key)? {
5595            return Ok(answer);
5596        }
5597        // A host class's `delete_property` trap decides; `false` is a refusal, which the
5598        // caller reports as a failed delete.
5599        if let Some(exotic) = object.exotic()
5600            && let Some(answer) = exotic.delete_property(self, object, key)?
5601        {
5602            return Ok(answer);
5603        }
5604        if let Some(index) = key.as_str().and_then(array_index)
5605            && let Some(length) = object.array_length()
5606            && (index as usize) < length
5607        {
5608            // An accessor defined on an index lives in the property table rather than the
5609            // element vector, so both have to be cleared: `delete` after
5610            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5611            object.delete_key(key);
5612            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5613            // index stops answering `in`.
5614            if object.element_is_undeletable(index) {
5615                return Ok(false);
5616            }
5617            object.array_set(self.heap, index as usize, Value::Hole);
5618            return Ok(true);
5619        }
5620        Ok(object.delete_key(key))
5621    }
5622
5623    // -- proxy traps --------------------------------------------------------
5624    //
5625    // A proxy's internal methods all look the same: ask the handler for the trap, call it
5626    // with the target and the operation's own arguments, then check the answer against
5627    // the target. The checks are not decoration — they are what stops a proxy from
5628    // reporting a `non-configurable` property as missing, which would let a frozen object
5629    // be rewritten by standing in front of it.
5630
5631    /// The target and handler of `object`, or `None` when it is not a proxy.
5632    ///
5633    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5634    /// one has to fail: the slots the traps would have been read from are gone.
5635    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5636        let Some(state) = object.proxy_state() else {
5637            return Ok(None);
5638        };
5639        let state = state.borrow();
5640        match (&state.target, &state.handler) {
5641            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5642            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5643        }
5644    }
5645
5646    /// Call `handler[name]`, or answer `None` when the trap is absent.
5647    ///
5648    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5649    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5650    /// back to the target.
5651    fn proxy_trap(
5652        &mut self,
5653        handler: &Value,
5654        name: &str,
5655        args: Vec<Value>,
5656    ) -> JsResult<Option<Value>> {
5657        let Value::Object(table) = handler else {
5658            return Err(self.type_error("proxy handler is not an object"));
5659        };
5660        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5661        match trap {
5662            Value::Undefined => Ok(None),
5663            Value::Object(function) if function.is_callable() => {
5664                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5665                Ok(Some(answer))
5666            }
5667            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5668        }
5669    }
5670
5671    /// Whether `object`'s own property `key` is one the target refuses to lose.
5672    ///
5673    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5674    /// its value behind the target's back. This goes through
5675    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5676    /// elements and its `length` — both fixed, both outside the table — are covered.
5677    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5678        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5679    }
5680
5681    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5682    fn proxy_get(
5683        &mut self,
5684        object: &Gc<JsObject>,
5685        receiver: &Value,
5686        key: &PropertyKey,
5687    ) -> JsResult<Option<Value>> {
5688        let Some((target, handler)) = self.proxy_parts(object)? else {
5689            return Ok(None);
5690        };
5691        let key_value = self.key_value(key);
5692        let Some(result) = self.proxy_trap(
5693            &handler,
5694            "get",
5695            vec![Value::Object(target.clone()), key_value, receiver.clone()],
5696        )?
5697        else {
5698            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5699            // inherited getter still sees the proxy.
5700            return Ok(Some(
5701                self.get_property_key_for(&target, Some(receiver), key)?
5702                    .unwrap_or(Value::Undefined),
5703            ));
5704        };
5705        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5706            if fixed.is_accessor() {
5707                // A fixed accessor with no getter must read as `undefined`.
5708                let has_getter = fixed
5709                    .getter
5710                    .as_ref()
5711                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
5712                if !has_getter && !matches!(result, Value::Undefined) {
5713                    return Err(self.type_error(format!(
5714                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
5715                    )));
5716                }
5717            } else if !fixed.writable {
5718                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5719                if !fixed_value.same_value(&result) {
5720                    return Err(self.type_error(format!(
5721                        "proxy 'get' disagrees with the non-configurable property '{key}'"
5722                    )));
5723                }
5724            }
5725        }
5726        Ok(Some(result))
5727    }
5728
5729    /// `[[Set]]` on a proxy.
5730    ///
5731    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5732    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5733    /// read-only store has.
5734    fn proxy_set(
5735        &mut self,
5736        object: &Gc<JsObject>,
5737        key: &PropertyKey,
5738        value: Value,
5739        receiver: &Value,
5740    ) -> JsResult<Option<bool>> {
5741        let Some((target, handler)) = self.proxy_parts(object)? else {
5742            return Ok(None);
5743        };
5744        let key_value = self.key_value(key);
5745        let Some(result) = self.proxy_trap(
5746            &handler,
5747            "set",
5748            vec![
5749                Value::Object(target.clone()),
5750                key_value,
5751                value.clone(),
5752                receiver.clone(),
5753            ],
5754        )?
5755        else {
5756            // No trap: store on the target, which is where an ordinary proxy write lands.
5757            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5758            return Ok(Some(true));
5759        };
5760        if !result.to_boolean() {
5761            return Ok(Some(false));
5762        }
5763        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5764            if fixed.is_accessor() {
5765                let has_setter = fixed
5766                    .setter
5767                    .as_ref()
5768                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
5769                if !has_setter {
5770                    return Err(self.type_error(format!(
5771                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5772                    )));
5773                }
5774            } else if !fixed.writable {
5775                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5776                if !fixed_value.same_value(&value) {
5777                    return Err(self.type_error(format!(
5778                        "proxy 'set' changed the non-configurable property '{key}'"
5779                    )));
5780                }
5781            }
5782        }
5783        // A new property cannot appear on a target that refuses new properties.
5784        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5785            return Err(self.type_error(format!(
5786                "proxy 'set' added '{key}' to a non-extensible target"
5787            )));
5788        }
5789        Ok(Some(true))
5790    }
5791
5792    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5793    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5794        let Some((target, handler)) = self.proxy_parts(object)? else {
5795            return Ok(None);
5796        };
5797        let key_value = self.key_value(key);
5798        let Some(result) = self.proxy_trap(
5799            &handler,
5800            "has",
5801            vec![Value::Object(target.clone()), key_value],
5802        )?
5803        else {
5804            return Ok(Some(self.has_own_or_inherited(&target, key)?));
5805        };
5806        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5807            return Err(self.type_error(format!(
5808                "proxy 'has' denied the non-configurable property '{key}'"
5809            )));
5810        }
5811        // A non-extensible target cannot grow, so every own property it *has* is fixed.
5812        if !result.to_boolean()
5813            && !target.is_extensible()
5814            && Self::ordinary_own_property(&target, key).is_some()
5815        {
5816            return Err(self.type_error(format!(
5817                "proxy 'has' denied the own property '{key}' of a non-extensible target"
5818            )));
5819        }
5820        Ok(Some(result.to_boolean()))
5821    }
5822
5823    /// `[[Delete]]` on a proxy.
5824    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5825        let Some((target, handler)) = self.proxy_parts(object)? else {
5826            return Ok(None);
5827        };
5828        let key_value = self.key_value(key);
5829        let Some(result) = self.proxy_trap(
5830            &handler,
5831            "deleteProperty",
5832            vec![Value::Object(target.clone()), key_value],
5833        )?
5834        else {
5835            return Ok(Some(self.delete_property_key(&target, key)?));
5836        };
5837        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5838            return Err(self.type_error(format!(
5839                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5840            )));
5841        }
5842        if result.to_boolean()
5843            && !target.is_extensible()
5844            && Self::ordinary_own_property(&target, key).is_some()
5845        {
5846            return Err(self.type_error(format!(
5847                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5848            )));
5849        }
5850        Ok(Some(result.to_boolean()))
5851    }
5852
5853    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5854    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5855        let Some((target, handler)) = self.proxy_parts(object)? else {
5856            return Ok(None);
5857        };
5858        let Some(result) =
5859            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5860        else {
5861            // No trap: the target's own keys, already in the order an object reports.
5862            return Ok(Some(self.object_own_property_keys(&target)?));
5863        };
5864        // `CreateListFromArrayLike` with the string-or-symbol restriction.
5865        let list = self.list_from_array_like(&result, true)?;
5866        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5867        for value in list {
5868            let key = self.propkey(&value)?;
5869            if keys.contains(&key) {
5870                return Err(self.type_error(format!(
5871                    "proxy 'ownKeys' returned the duplicate key '{key}'"
5872                )));
5873            }
5874            keys.push(key);
5875        }
5876        for (key, property) in target.property_entries() {
5877            if !property.configurable && !keys.contains(&key) {
5878                return Err(self.type_error(format!(
5879                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5880                )));
5881            }
5882            if !target.is_extensible() && !keys.contains(&key) {
5883                return Err(self.type_error(format!(
5884                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5885                )));
5886            }
5887        }
5888        if !target.is_extensible() {
5889            let own = target.property_entries().len();
5890            if keys.len() != own {
5891                return Err(
5892                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5893                );
5894            }
5895        }
5896        Ok(Some(keys))
5897    }
5898
5899    /// `[[GetOwnProperty]]` on a proxy.
5900    fn proxy_get_own_property(
5901        &mut self,
5902        object: &Gc<JsObject>,
5903        key: &PropertyKey,
5904    ) -> JsResult<Option<Option<Property>>> {
5905        let Some((target, handler)) = self.proxy_parts(object)? else {
5906            return Ok(None);
5907        };
5908        let key_value = self.key_value(key);
5909        let Some(result) = self.proxy_trap(
5910            &handler,
5911            "getOwnPropertyDescriptor",
5912            vec![Value::Object(target.clone()), key_value],
5913        )?
5914        else {
5915            // No trap: the target's own descriptor is the answer. This has to go through
5916            // the same synthesis an ordinary object gets, because a proxy's own property
5917            // table is empty by design — reading it directly reported `undefined` for
5918            // every key, including an array's indices and `length`.
5919            return Ok(Some(Self::ordinary_own_property(&target, key)));
5920        };
5921        let answer = if matches!(result, Value::Undefined) {
5922            None
5923        } else {
5924            Some(self.property_from_descriptor(&result)?)
5925        };
5926        let fixed = Self::is_fixed_property(&target, key);
5927        match (&answer, &fixed) {
5928            // A non-configurable property cannot be reported as absent.
5929            (None, Some(_)) => {
5930                return Err(self.type_error(format!(
5931                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5932                )));
5933            }
5934            (Some(descriptor), Some(fixed)) => {
5935                if descriptor.configurable {
5936                    return Err(self.type_error(format!(
5937                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5938                    )));
5939                }
5940                if fixed.is_accessor() != descriptor.is_accessor() {
5941                    return Err(self.type_error(format!(
5942                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5943                    )));
5944                }
5945                if !fixed.is_accessor() && !fixed.writable {
5946                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5947                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5948                    if !fixed_value.same_value(&reported) {
5949                        return Err(self.type_error(format!(
5950                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5951                        )));
5952                    }
5953                }
5954            }
5955            _ => {}
5956        }
5957        Ok(Some(answer))
5958    }
5959
5960    /// `[[DefineOwnProperty]]` on a proxy.
5961    fn proxy_define_property(
5962        &mut self,
5963        object: &Gc<JsObject>,
5964        key: &PropertyKey,
5965        property: Property,
5966    ) -> JsResult<Option<bool>> {
5967        let Some((target, handler)) = self.proxy_parts(object)? else {
5968            return Ok(None);
5969        };
5970        let key_value = self.key_value(key);
5971        let descriptor = self.descriptor_from_property(&property);
5972        let Some(result) = self.proxy_trap(
5973            &handler,
5974            "defineProperty",
5975            vec![Value::Object(target.clone()), key_value, descriptor],
5976        )?
5977        else {
5978            return Ok(None);
5979        };
5980        if !result.to_boolean() {
5981            return Ok(Some(false));
5982        }
5983        let fixed = Self::is_fixed_property(&target, key);
5984        let creating = Self::ordinary_own_property(&target, key).is_none();
5985        if creating && !target.is_extensible() {
5986            return Err(self.type_error(format!(
5987                "proxy 'defineProperty' added '{key}' to a non-extensible target"
5988            )));
5989        }
5990        if let Some(fixed) = fixed {
5991            if property.configurable {
5992                return Err(self.type_error(format!(
5993                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
5994                )));
5995            }
5996            if !fixed.writable && property.writable && !fixed.is_accessor() {
5997                return Err(self.type_error(format!(
5998                    "proxy 'defineProperty' made the read-only '{key}' writable"
5999                )));
6000            }
6001        }
6002        Ok(Some(true))
6003    }
6004
6005    /// `[[GetPrototypeOf]]` on a proxy.
6006    fn proxy_get_prototype_of(
6007        &mut self,
6008        object: &Gc<JsObject>,
6009    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6010        let Some((target, handler)) = self.proxy_parts(object)? else {
6011            return Ok(None);
6012        };
6013        let Some(result) = self.proxy_trap(
6014            &handler,
6015            "getPrototypeOf",
6016            vec![Value::Object(target.clone())],
6017        )?
6018        else {
6019            return Ok(Some(target.proto()));
6020        };
6021        let proto = match &result {
6022            Value::Null => None,
6023            Value::Object(proto) => Some(proto.clone()),
6024            _ => {
6025                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
6026            }
6027        };
6028        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
6029            return Err(self.type_error(
6030                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
6031            ));
6032        }
6033        Ok(Some(proto))
6034    }
6035
6036    /// `[[SetPrototypeOf]]` on a proxy.
6037    fn proxy_set_prototype_of(
6038        &mut self,
6039        object: &Gc<JsObject>,
6040        proto: Option<Gc<JsObject>>,
6041    ) -> JsResult<Option<bool>> {
6042        let Some((target, handler)) = self.proxy_parts(object)? else {
6043            return Ok(None);
6044        };
6045        let proto_value = match &proto {
6046            Some(proto) => Value::Object(proto.clone()),
6047            None => Value::Null,
6048        };
6049        let Some(result) = self.proxy_trap(
6050            &handler,
6051            "setPrototypeOf",
6052            vec![Value::Object(target.clone()), proto_value],
6053        )?
6054        else {
6055            target.set_proto(proto);
6056            return Ok(Some(true));
6057        };
6058        if result.to_boolean()
6059            && !target.is_extensible()
6060            && !same_proto(proto.as_ref(), target.proto().as_ref())
6061        {
6062            return Err(self.type_error(
6063                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6064            ));
6065        }
6066        Ok(Some(result.to_boolean()))
6067    }
6068
6069    /// `[[IsExtensible]]` on a proxy.
6070    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6071        let Some((target, handler)) = self.proxy_parts(object)? else {
6072            return Ok(None);
6073        };
6074        let Some(result) = self.proxy_trap(
6075            &handler,
6076            "isExtensible",
6077            vec![Value::Object(target.clone())],
6078        )?
6079        else {
6080            return Ok(Some(target.is_extensible()));
6081        };
6082        // The answer is not the proxy's to invent: it must agree with the target, or a
6083        // script could learn `false` while the target keeps accepting new properties.
6084        if result.to_boolean() != target.is_extensible() {
6085            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6086        }
6087        Ok(Some(result.to_boolean()))
6088    }
6089
6090    /// `[[PreventExtensions]]` on a proxy.
6091    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6092        let Some((target, handler)) = self.proxy_parts(object)? else {
6093            return Ok(None);
6094        };
6095        let Some(result) = self.proxy_trap(
6096            &handler,
6097            "preventExtensions",
6098            vec![Value::Object(target.clone())],
6099        )?
6100        else {
6101            target.set_extensible(false);
6102            return Ok(Some(true));
6103        };
6104        if result.to_boolean() && target.is_extensible() {
6105            return Err(self.type_error(
6106                "proxy 'preventExtensions' reported success but the target is still extensible",
6107            ));
6108        }
6109        Ok(Some(result.to_boolean()))
6110    }
6111
6112    /// `[[Call]]` on a proxy, through the `apply` trap.
6113    fn proxy_apply(
6114        &mut self,
6115        object: &Gc<JsObject>,
6116        this: Value,
6117        args: Vec<Value>,
6118    ) -> JsResult<Option<Value>> {
6119        let Some((target, handler)) = self.proxy_parts(object)? else {
6120            return Ok(None);
6121        };
6122        // The trap gets the arguments as one array, which is the shape the spec passes
6123        // and the shape `apply` traps are written against (`args[0]` is the first one).
6124        let arguments = self.new_array(args.clone());
6125        let this_for_trap = this.clone();
6126        let Some(result) = self.proxy_trap(
6127            &handler,
6128            "apply",
6129            vec![
6130                Value::Object(target.clone()),
6131                this_for_trap,
6132                Value::Object(arguments),
6133            ],
6134        )?
6135        else {
6136            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6137        };
6138        Ok(Some(result))
6139    }
6140
6141    /// `[[Construct]]` on a proxy, through the `construct` trap.
6142    fn proxy_construct(
6143        &mut self,
6144        object: &Gc<JsObject>,
6145        args: Vec<Value>,
6146        new_target: &Value,
6147    ) -> JsResult<Option<Value>> {
6148        let Some((target, handler)) = self.proxy_parts(object)? else {
6149            return Ok(None);
6150        };
6151        if !target.is_callable() {
6152            return Err(self.type_error("proxy target is not a constructor"));
6153        }
6154        let arguments = self.new_array(args.clone());
6155        let Some(result) = self.proxy_trap(
6156            &handler,
6157            "construct",
6158            vec![
6159                Value::Object(target.clone()),
6160                Value::Object(arguments),
6161                new_target.clone(),
6162            ],
6163        )?
6164        else {
6165            return Ok(Some(self.construct(
6166                Value::Object(target),
6167                new_target.clone(),
6168                args,
6169            )?));
6170        };
6171        if !matches!(result, Value::Object(_)) {
6172            return Err(self.type_error("proxy 'construct' must return an object"));
6173        }
6174        Ok(Some(result))
6175    }
6176
6177    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6178    pub(crate) fn has_own_or_inherited(
6179        &mut self,
6180        object: &Gc<JsObject>,
6181        key: &PropertyKey,
6182    ) -> JsResult<bool> {
6183        // The object itself first: it may be a proxy, and then the answer is its trap's.
6184        if let Some(answer) = self.proxy_has(object, key)? {
6185            return Ok(answer);
6186        }
6187        // An integer-indexed exotic object answers a canonical numeric index from
6188        // `IsValidIntegerIndex` alone (§10.4.5.4 step 1.b.i) — **without** walking the
6189        // prototype chain. That is observable: a view the buffer has been resized away from
6190        // has no indices, so `2 in view` is `false` even when
6191        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
6192        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
6193        // The `[[HasProperty]]` that `in` compiles to goes through here, which is why the
6194        // same rule is repeated in `has_property_key` rather than living only there.
6195        if object.typed_array_parts().is_some()
6196            && let Some(index) = key.as_str().and_then(array_index)
6197        {
6198            return Ok(object
6199                .typed_array_length()
6200                .is_some_and(|length| (index as usize) < length));
6201        }
6202        // A host class answers `in` for its own keys, which may live nowhere in a property
6203        // table — `"x" in point` is true because the class says so, not because a property
6204        // exists.
6205        if let Some(exotic) = object.exotic()
6206            && let Some(answer) = exotic.has_property(self, object, key)?
6207        {
6208            return Ok(answer);
6209        }
6210        // `has_own` rather than `own_property_key`: an array's elements and its derived
6211        // `length` are invisible to the property table, and `Array.prototype` is an array.
6212        // A host class's `get_own_property` counts too, because the reference's
6213        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6214        // lives — a class with only `get_own_property` answers `in` through it.
6215        if self.exotic_has_own(object, key)? {
6216            return Ok(true);
6217        }
6218        // A hole is *not* the end of the search: the chain may still have the key, which
6219        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6220        for ancestor in object.chain() {
6221            // A proxy further up the chain answers for itself.
6222            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6223                return Ok(answer);
6224            }
6225            // Same for a host class: a prototype may be one, and `in` reaches it.
6226            if let Some(exotic) = ancestor.exotic()
6227                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6228            {
6229                return Ok(answer);
6230            }
6231            if self.exotic_has_own(&ancestor, key)? {
6232                return Ok(true);
6233            }
6234        }
6235        Ok(false)
6236    }
6237
6238    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6239    /// trap included.
6240    ///
6241    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6242    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6243    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6244        if let Some(exotic) = object.exotic()
6245            && let Some(answer) = exotic.get_own_property(self, object, key)?
6246        {
6247            return Ok(answer.is_some());
6248        }
6249        Ok(has_own(object, key))
6250    }
6251
6252    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6253    ///
6254    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6255    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6256    /// `TypeError` instead of a property named `"1.5"`.
6257    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6258        let object = self.object_from(value)?;
6259        let length = self
6260            .get_property(&object, "length")?
6261            .map(|value| value.to_number())
6262            .unwrap_or(0.0);
6263        if !length.is_finite() || length < 0.0 {
6264            return Err(self.type_error("invalid array-like length"));
6265        }
6266        let length = length as usize;
6267        let mut items = Vec::with_capacity(length.min(1024));
6268        for index in 0..length {
6269            let item = self
6270                .get_property(&object, &index.to_string())?
6271                .unwrap_or(Value::Undefined);
6272            if keys_only && matches!(&item, Value::Symbol(_)) {
6273                items.push(item);
6274                continue;
6275            }
6276            if keys_only && !matches!(&item, Value::String(_)) {
6277                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6278            }
6279            items.push(item);
6280        }
6281        Ok(items)
6282    }
6283
6284    /// A `Property` from the descriptor object a trap returned.
6285    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6286        let object = self.object_from(value)?;
6287        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6288            interp.get_property(&object, name)
6289        };
6290        let getter = field(self, "get")?;
6291        let setter = field(self, "set")?;
6292        let accessor = getter.is_some() || setter.is_some();
6293        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6294            Ok(interp
6295                .get_property(&object, name)?
6296                .is_some_and(|value| value.to_boolean()))
6297        };
6298        let enumerable = boolean(self, "enumerable")?;
6299        let configurable = boolean(self, "configurable")?;
6300        if accessor {
6301            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6302                return Err(
6303                    self.type_error("a descriptor cannot be both a data property and an accessor")
6304                );
6305            }
6306            Ok(Property {
6307                getter: getter.or(Some(Value::Undefined)),
6308                setter: setter.or(Some(Value::Undefined)),
6309                enumerable,
6310                configurable,
6311                writable: false,
6312                value: None,
6313            })
6314        } else {
6315            Ok(Property {
6316                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6317                writable: boolean(self, "writable")?,
6318                enumerable,
6319                configurable,
6320                getter: None,
6321                setter: None,
6322            })
6323        }
6324    }
6325
6326    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6327    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6328        let object = self.new_object(None);
6329        if property.is_accessor() {
6330            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6331            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6332            object.define_data("get", getter);
6333            object.define_data("set", setter);
6334        } else {
6335            let value = property.value.clone().unwrap_or(Value::Undefined);
6336            object.define_data("value", value);
6337            object.define_data("writable", Value::Bool(property.writable));
6338        }
6339        object.define_data("enumerable", Value::Bool(property.enumerable));
6340        object.define_data("configurable", Value::Bool(property.configurable));
6341        Value::Object(object)
6342    }
6343
6344    // -- calling ------------------------------------------------------------
6345
6346    /// Call `callee` with `this` and `args`.
6347    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6348        let Value::Object(function) = &callee else {
6349            // `typeof x === "function"` is not enough to make `x()` legal: only a
6350            // callable object is. `null` and `undefined` need no special wording
6351            // here — their `ToString` already reads the way the reference's does.
6352            let what = format!("{} is not a function", callee.to_js_string());
6353            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6354        };
6355        // A proxy of a function is called through its `apply` trap. It has no
6356        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6357        // below, and a proxy of a non-function has nothing to forward to.
6358        if function.proxy_state().is_some() {
6359            return match self.proxy_apply(function, this, args)? {
6360                Some(result) => Ok(result),
6361                None => Err(Signal::Throw(
6362                    self.make_error("TypeError", "proxy target is not callable"),
6363                )),
6364            };
6365        }
6366        let callable = function.with(|data| match &data.kind {
6367            ObjectKind::Function(callable) => match callable {
6368                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6369                // The `Rc` is cloned out so the borrow of this object's data is released
6370                // before the closure runs: the closure may touch the same object.
6371                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6372                Callable::Bound {
6373                    target,
6374                    this,
6375                    args: leading,
6376                } => Some(NativeCall::Bound {
6377                    target: target.clone(),
6378                    this: this.clone(),
6379                    leading: leading.clone(),
6380                }),
6381                Callable::Bytecode { code, env } => {
6382                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
6383                }
6384                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6385                Callable::PromiseResolve(promise) => {
6386                    Some(NativeCall::PromiseResolve(promise.clone()))
6387                }
6388                Callable::PromiseReject(promise) => {
6389                    Some(NativeCall::PromiseReject(promise.clone()))
6390                }
6391                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6392                    state: state.clone(),
6393                }),
6394                Callable::ThenShim {
6395                    handler,
6396                    resolve,
6397                    reject,
6398                    fulfilled,
6399                } => Some(NativeCall::ThenShim {
6400                    handler: handler.clone(),
6401                    resolve: resolve.clone(),
6402                    reject: reject.clone(),
6403                    fulfilled: *fulfilled,
6404                }),
6405                Callable::AwaitResume {
6406                    coroutine,
6407                    promise,
6408                    kind,
6409                } => Some(NativeCall::AwaitResume {
6410                    coroutine: coroutine.clone(),
6411                    promise: promise.clone(),
6412                    kind: *kind,
6413                }),
6414                Callable::CombinatorSettle {
6415                    state,
6416                    index,
6417                    fulfilled,
6418                } => Some(NativeCall::CombinatorSettle {
6419                    state: state.clone(),
6420                    index: *index,
6421                    fulfilled: *fulfilled,
6422                }),
6423                Callable::FinallyShim {
6424                    callback,
6425                    fulfilled,
6426                    constructor,
6427                } => Some(NativeCall::FinallyShim {
6428                    callback: callback.clone(),
6429                    fulfilled: *fulfilled,
6430                    constructor: constructor.clone(),
6431                }),
6432                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6433                Callable::CompletedReturn {
6434                    generator,
6435                    promise,
6436                    rejected,
6437                } => Some(NativeCall::CompletedReturn {
6438                    generator: generator.clone(),
6439                    promise: promise.clone(),
6440                    rejected: *rejected,
6441                }),
6442                Callable::YieldResult {
6443                    generator,
6444                    promise,
6445                    done,
6446                } => Some(NativeCall::YieldResult {
6447                    generator: generator.clone(),
6448                    promise: promise.clone(),
6449                    done: *done,
6450                }),
6451                Callable::DisposeStep {
6452                    remaining,
6453                    promise,
6454                    error,
6455                    rejected,
6456                } => Some(NativeCall::DisposeStep {
6457                    remaining: remaining.clone(),
6458                    promise: promise.clone(),
6459                    error: error.clone(),
6460                    rejected: *rejected,
6461                }),
6462                Callable::GeneratorResume {
6463                    generator,
6464                    promise,
6465                    kind,
6466                } => Some(NativeCall::GeneratorResume {
6467                    generator: generator.clone(),
6468                    promise: promise.clone(),
6469                    kind: *kind,
6470                }),
6471                Callable::SettlePromise {
6472                    promise,
6473                    value,
6474                    rejected,
6475                } => Some(NativeCall::SettlePromise {
6476                    promise: promise.clone(),
6477                    value: value.clone(),
6478                    rejected: *rejected,
6479                }),
6480            },
6481            _ => None,
6482        });
6483        match callable {
6484            Some(NativeCall::Host(func)) => {
6485                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6486                // function by name rather than stopping at the caller.
6487                let frame_less = function
6488                    .own_property("_frame_less")
6489                    .and_then(|property| property.value)
6490                    .is_some_and(|value| value.to_boolean());
6491                let outer = if frame_less {
6492                    None
6493                } else {
6494                    self.native_frames
6495                        .push((function.clone(), self.frames.len()));
6496                    Some(self.current_native.replace(function.clone()))
6497                };
6498                let result = {
6499                    let mut body = func.borrow_mut();
6500                    body(self, this, &args)
6501                };
6502                if !frame_less {
6503                    self.native_frames.pop();
6504                    self.current_native = outer.flatten();
6505                }
6506                result
6507            }
6508            Some(NativeCall::Native(func)) => {
6509                // A function marked `_frame_less` is one the reference implements
6510                // without a call frame — `eval` is the only one so far.
6511                let frame_less = function
6512                    .own_property("_frame_less")
6513                    .and_then(|property| property.value)
6514                    .is_some_and(|value| value.to_boolean());
6515                let outer = if frame_less {
6516                    None
6517                } else {
6518                    self.native_frames
6519                        .push((function.clone(), self.frames.len()));
6520                    Some(self.current_native.replace(function.clone()))
6521                };
6522                let result = func(self, this, &args);
6523                if !frame_less {
6524                    self.native_frames.pop();
6525                    self.current_native = outer.flatten();
6526                }
6527                result
6528            }
6529            Some(NativeCall::Revoker(slots)) => {
6530                // Idempotent: revoking twice answers `undefined` again rather than
6531                // complaining, which is what the spec says and what a `finally` block
6532                // relies on.
6533                let mut state = slots.borrow_mut();
6534                state.target = None;
6535                state.handler = None;
6536                Ok(Value::Undefined)
6537            }
6538            Some(NativeCall::PromiseResolve(promise)) => {
6539                // One-shot: a second call is silently ignored, which
6540                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6541                let value = args.first().cloned().unwrap_or(Value::Undefined);
6542                self.resolve_promise_with(&promise, value)?;
6543                Ok(Value::Undefined)
6544            }
6545            Some(NativeCall::PromiseReject(promise)) => {
6546                let reason = args.first().cloned().unwrap_or(Value::Undefined);
6547                self.reject_promise(&promise, reason);
6548                Ok(Value::Undefined)
6549            }
6550            Some(NativeCall::ThenShim {
6551                handler,
6552                resolve,
6553                reject,
6554                fulfilled,
6555            }) => {
6556                // `PerformPromiseThen` with a capability: run the handler, then settle
6557                // through the capability's own pair. A throw from the handler is the
6558                // rejection, and a throw from the capability's `resolve` is not caught —
6559                // exactly the spec's `?`.
6560                let value = args.first().cloned().unwrap_or(Value::Undefined);
6561                match handler {
6562                    Some(handler) => {
6563                        match self.call_value(handler, Value::Undefined, vec![value]) {
6564                            Ok(result) => {
6565                                self.call_value(resolve, Value::Undefined, vec![result])?;
6566                            }
6567                            Err(Signal::Throw(reason)) => {
6568                                self.call_value(reject, Value::Undefined, vec![reason])?;
6569                            }
6570                            Err(signal) => return Err(signal),
6571                        }
6572                    }
6573                    None => {
6574                        let handler = if fulfilled { resolve } else { reject };
6575                        self.call_value(handler, Value::Undefined, vec![value])?;
6576                    }
6577                }
6578                Ok(Value::Undefined)
6579            }
6580            Some(NativeCall::CapabilityExecutor { state }) => {
6581                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6582                // slot holds a value yet. The test is on the *values*, not on a call count —
6583                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6584                // called-twice`'s first case does exactly that), while a second call after a
6585                // real pair is the `TypeError`.
6586                let defined = |name: &str| {
6587                    state
6588                        .own_property(name)
6589                        .and_then(|property| property.value)
6590                        .is_some_and(|value| !matches!(value, Value::Undefined))
6591                };
6592                if defined("resolve") || defined("reject") {
6593                    return Err(self.type_error("promise capability executor called twice"));
6594                }
6595                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6596                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6597                state.define_data("resolve", resolve);
6598                state.define_data("reject", reject);
6599                Ok(Value::Undefined)
6600            }
6601            Some(NativeCall::CombinatorSettle {
6602                state,
6603                index,
6604                fulfilled,
6605            }) => {
6606                let value = args.first().cloned().unwrap_or(Value::Undefined);
6607                self.settle_combinator(&state, index, fulfilled, value)?;
6608                Ok(Value::Undefined)
6609            }
6610            Some(NativeCall::AwaitResume {
6611                coroutine,
6612                promise,
6613                kind,
6614            }) => {
6615                // Resume *inline*, in the reaction that delivered the value. Deferring it
6616                // by another job inserts a tick between every `await` and its
6617                // continuation, which reorders `await` against unrelated `then` chains —
6618                // `f().then(g)` then runs before `f`'s own next statement.
6619                self.drive_async(
6620                    &coroutine,
6621                    &promise,
6622                    kind,
6623                    args.first().cloned().unwrap_or(Value::Undefined),
6624                )
6625                .map(|()| Value::Undefined)
6626            }
6627            Some(NativeCall::FinallyShim {
6628                callback,
6629                fulfilled,
6630                constructor,
6631            }) => {
6632                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6633                // that settles with the *original* outcome once the callback's result has
6634                // settled. The callback's own value is discarded — that is the whole
6635                // difference between `finally` and `then`.
6636                let original = args.first().cloned().unwrap_or(Value::Undefined);
6637                let result = match &callback {
6638                    Some(callback) => {
6639                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6640                    }
6641                    None => Value::Undefined,
6642                };
6643                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6644                // already a promise of this constructor is reused rather than rewrapped.
6645                let resolved = self.promise_resolve_for(&constructor, result)?;
6646                let Value::Object(resolved) = resolved else {
6647                    return Ok(original);
6648                };
6649                // The wait is a chained promise rather than a bare return, so a callback
6650                // that returns a slow promise really does delay the continuation.
6651                let waiting = self.new_promise();
6652                let pass = JsObject::function(
6653                    self.heap,
6654                    Some(self.realm.function_proto.clone()),
6655                    Callable::SettlePromise {
6656                        promise: waiting.clone(),
6657                        value: original,
6658                        rejected: !fulfilled,
6659                    },
6660                );
6661                let pass = Value::Object(pass);
6662                // Whichever way the callback's promise settles, the original outcome wins.
6663                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6664                Ok(Value::Object(waiting))
6665            }
6666            Some(NativeCall::DisposeStep {
6667                remaining,
6668                promise,
6669                error,
6670                rejected,
6671            }) => {
6672                let error = if rejected {
6673                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
6674                    self.merge_dispose_error(reason, error)
6675                } else {
6676                    error
6677                };
6678                self.dispose_step(&remaining, &promise, error)?;
6679                Ok(Value::Undefined)
6680            }
6681            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6682            Some(NativeCall::CompletedReturn {
6683                generator,
6684                promise,
6685                rejected,
6686            }) => {
6687                let value = args.first().cloned().unwrap_or(Value::Undefined);
6688                let outcome = if rejected {
6689                    AsyncOutcome::Error(value)
6690                } else {
6691                    AsyncOutcome::Value(self.iterator_result(value, true)?)
6692                };
6693                self.settle_async_request(&generator, &promise, outcome)?;
6694                Ok(Value::Undefined)
6695            }
6696            Some(NativeCall::YieldResult {
6697                generator,
6698                promise,
6699                done,
6700            }) => {
6701                let value = args.first().cloned().unwrap_or(Value::Undefined);
6702                let result = self.iterator_result(value, done)?;
6703                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6704                Ok(Value::Undefined)
6705            }
6706            Some(NativeCall::GeneratorResume {
6707                generator,
6708                promise,
6709                kind,
6710            }) => {
6711                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6712                // tick and reorders the generator against other chains.
6713                self.step_async_generator(
6714                    &generator,
6715                    &promise,
6716                    kind,
6717                    args.first().cloned().unwrap_or(Value::Undefined),
6718                )
6719                .map(|()| Value::Undefined)
6720            }
6721            Some(NativeCall::SettlePromise {
6722                promise,
6723                value,
6724                rejected,
6725            }) => {
6726                if rejected {
6727                    self.reject_promise(&promise, value);
6728                } else {
6729                    self.fulfill_promise(&promise, value);
6730                }
6731                Ok(Value::Undefined)
6732            }
6733            Some(NativeCall::Bound {
6734                target,
6735                this: bound_this,
6736                leading,
6737            }) => {
6738                let mut all = leading;
6739                all.extend(args);
6740                self.call_value(target, bound_this, all)
6741            }
6742            Some(NativeCall::Bytecode(code, env)) => {
6743                if code.code.kind.is_generator() {
6744                    return self.new_generator(callee, this, args);
6745                }
6746                if code.code.kind.is_async() {
6747                    // Same coroutine machinery as a generator; the difference is only in
6748                    // what the completion does — see `new_async_function`.
6749                    return self.new_async_function(callee, this, args);
6750                }
6751                self.execute(code, env, this, args, callee)
6752            }
6753            None => Err(Signal::Throw(
6754                self.make_error("TypeError", "not a function"),
6755            )),
6756        }
6757    }
6758
6759    /// Give a freshly built function its own `prototype` object.
6760    ///
6761    /// Every function that can be used with `new` carries one, and its
6762    /// `constructor` points back at the function — a reference cycle, which is
6763    /// exactly what the collector's cycle pass exists to reclaim.
6764    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6765        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6766        let constructor = Value::Object(function.clone());
6767        prototype.define(
6768            "constructor",
6769            Property::with_attributes(constructor, true, false),
6770        );
6771        let value = Value::Object(prototype);
6772        function.define("prototype", Property::prototype_of(value, true));
6773    }
6774
6775    /// The object `special_object` builds.
6776    ///
6777    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6778    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6779    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6780    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6781    /// write through `arguments` does not reach the parameter.
6782    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6783        match magic {
6784            0 | 1 => {
6785                let args = self.frame().passed().to_vec();
6786                let proto = self.realm.object_proto.clone();
6787                let object = self.new_object(Some(proto));
6788                // The marker `Object.prototype.toString` needs: an arguments object is an
6789                // ordinary object apart from reporting `[object Arguments]`, and that has
6790                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6791                // show up ahead of them in a key listing anyway — it is non-enumerable.
6792                self.internal_set(&object, "_class", self.string("Arguments"));
6793                // `length` is writable and configurable but neither enumerable nor a
6794                // plain data property: `Object.keys(arguments)` lists the indices only,
6795                // which is how `{...arguments}` copies them without the length.
6796                object.define(
6797                    "length",
6798                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
6799                );
6800                for (index, value) in args.into_iter().enumerate() {
6801                    object.define_data(&index.to_string(), value);
6802                }
6803                // An arguments object is iterable: `[...arguments]` and
6804                // `for (const a of arguments)` both work, through the *array* iterator
6805                // because the object is array-like. Without this the whole spread form
6806                // reported "not iterable".
6807                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6808                let values = self
6809                    .realm
6810                    .array_proto
6811                    .own_property("values")
6812                    .and_then(|property| property.value);
6813                if let Some(values) = values {
6814                    object.define_key(
6815                        &iterator_key,
6816                        Property::with_attributes(values, true, false),
6817                    );
6818                }
6819                Ok(Value::Object(object))
6820            }
6821            // `this.active_func`: the constructor `super()` resolves against.
6822            //
6823            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
6824            // own, so it inherits this from the function it was written in along with `this`
6825            // — and that is a lexical relationship, not a stack one: an arrow that escaped
6826            // the constructor and is called back later (`iter.return = () => super()`) has
6827            // the constructor nowhere on the stack. The compiler therefore reads it out of
6828            // a closure variable of the enclosing function, exactly as the reference does
6829            // with its `this_active_func` local.
6830            2 => Ok(self
6831                .current_callee()
6832                .map_or(Value::Undefined, Value::Object)),
6833            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6834            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6835            // its own either, so the lookup walks out to the nearest non-arrow frame for
6836            // the same reason as `this.active_func` above — without that, `super()` inside
6837            // an arrow passed `undefined` as the new target and the parent constructor was
6838            // then rejected for being invoked without `new`.
6839            3 => Ok(self
6840                .eval_new_target
6841                .clone()
6842                .unwrap_or_else(|| self.frame().new_target.clone())),
6843            // `[[HomeObject]]` of the function being run: what `super` is relative to.
6844            // An arrow has none of its own, so the lookup walks out to the enclosing
6845            // method — which is why `super` works inside an arrow inside a method.
6846            4 => Ok(self
6847                .frames
6848                .iter()
6849                .rev()
6850                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6851                .map_or(Value::Undefined, Value::Object)),
6852            // `import.meta`: the innermost module body's meta object. Outside a module
6853            // the compiler never emits this, so an empty fallback is unreachable rather
6854            // than permissive.
6855            6 => {
6856                let name = self.module_stack.last().cloned();
6857                let meta = name
6858                    .and_then(|name| self.modules.get(&name).cloned())
6859                    .and_then(|module| module.with(|r| r.import_meta.clone()));
6860                Ok(meta.map_or(Value::Undefined, Value::Object))
6861            }
6862            other => Err(Signal::Throw(self.make_error(
6863                "InternalError",
6864                &format!("special_object {other} is not implemented yet"),
6865            ))),
6866        }
6867    }
6868
6869    /// `[[HomeObject]]` of the innermost function that has one, if any.
6870    ///
6871    /// An arrow has none, so the search walks out to the enclosing method — the same
6872    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
6873    /// inside a method.
6874    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
6875        self.frames
6876            .iter()
6877            .rev()
6878            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6879    }
6880
6881    /// The dispose method a `using` declaration should snapshot, or an error.
6882    ///
6883    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
6884    /// is what makes a resource that only knows the synchronous protocol usable in both
6885    /// forms.
6886    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
6887        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
6888        if value.is_nullish() {
6889            return Ok(Value::Undefined);
6890        }
6891        let Some(object) = value.as_object() else {
6892            return Err(self.type_error("not an object"));
6893        };
6894        let mut method = if await_form {
6895            let found = self.get_property_key(
6896                object,
6897                &self.realm.well_known_key(WellKnown::AsyncDisposable),
6898            )?;
6899            match found {
6900                Some(found) if !found.is_nullish() => Some(found),
6901                _ => self
6902                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
6903            }
6904        } else {
6905            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
6906        };
6907        let Some(found) = method.take() else {
6908            return Err(self.type_error("value is not disposable"));
6909        };
6910        if found.is_nullish() {
6911            return Err(self.type_error("value is not disposable"));
6912        }
6913        let callable = found.as_object().is_some_and(|object| object.is_callable());
6914        if !callable {
6915            return Err(self.type_error("dispose method is not a function"));
6916        }
6917        Ok(found)
6918    }
6919
6920    /// Call one resource's disposer, folding a failure into `error_state`.
6921    ///
6922    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
6923    /// because a captured `using` binding lives in its reference cell and the local slot is
6924    /// stale — a closure over the resource is legal and must not change what is disposed.
6925    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
6926        let value = self.get_loc(slot);
6927        let method = self.get_loc(slot + 1);
6928        // A resource that was never initialised — its declaration threw — or that is
6929        // `null`/`undefined` has nothing to dispose.
6930        if value.is_nullish() || matches!(value, Value::Uninitialized) {
6931            return Ok(error_state);
6932        }
6933        if matches!(method, Value::Undefined | Value::Uninitialized) {
6934            return Ok(error_state);
6935        }
6936        match self.call_value(method, value, Vec::new()) {
6937            Ok(_) => Ok(error_state),
6938            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
6939            Err(other) => Err(other),
6940        }
6941    }
6942
6943    /// Combine a disposal failure with whatever was already going wrong.
6944    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
6945        if matches!(error_state, Value::Uninitialized) {
6946            return new_error;
6947        }
6948        self.new_suppressed_error(new_error, error_state)
6949    }
6950
6951    /// A `SuppressedError` instance built straight from its prototype.
6952    ///
6953    /// Not through the constructor: a script that rewrites
6954    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
6955    /// error wrapping.
6956    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
6957        let proto = self
6958            .realm
6959            .suppressed_error_proto
6960            .clone()
6961            .unwrap_or_else(|| self.realm.error_proto.clone());
6962        let object = self.new_object(Some(proto));
6963        object.define("error", Property::with_attributes(error, true, true));
6964        object.define(
6965            "suppressed",
6966            Property::with_attributes(suppressed, true, true),
6967        );
6968        object.define(
6969            "message",
6970            Property::with_attributes(self.string("SuppressedError"), true, true),
6971        );
6972        self.internal_set(&object, "_class", self.string("Error"));
6973        self.add_stack(&object);
6974        Value::Object(object)
6975    }
6976
6977    /// Call `callee`, or push its frame and let the main loop run it.
6978    ///
6979    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
6980    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
6981    /// continues, so `function f(){ return f() }` costs heap and stops at
6982    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
6983    /// is entered directly, and natives do not re-enter JavaScript in this
6984    /// milestone.
6985    ///
6986    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
6987    /// because the returning frame will.
6988    /// The elements of an array-like value, as a call argument list.
6989    ///
6990    /// `apply` accepts any array-like, not only a real array: the reference reads
6991    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
6992    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
6993        let Some(object) = value.as_object().cloned() else {
6994            if value.is_nullish() {
6995                // `f.apply(this, null)` passes no arguments at all.
6996                return Ok(Vec::new());
6997            }
6998            return Err(self.type_error("createListFromArrayLike called on non-object"));
6999        };
7000        let length = match self.get_property(&object, "length")? {
7001            Some(length) => length.to_number(),
7002            None => 0.0,
7003        };
7004        if !length.is_finite() || length <= 0.0 {
7005            return Ok(Vec::new());
7006        }
7007        let length = (length as usize).min(1_000_000);
7008        let mut args = Vec::with_capacity(length);
7009        for index in 0..length {
7010            let element = self.get_property(&object, &index.to_string())?;
7011            args.push(element.unwrap_or(Value::Undefined));
7012        }
7013        Ok(args)
7014    }
7015
7016    /// Turn a call to a generator function into a generator object.
7017    ///
7018    /// The frame is built exactly as an ordinary call would build it, then detached and
7019    /// stored in the generator before any body instruction runs — which is what makes
7020    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
7021    /// is `initial_yield`, the first instruction of every suspending body.
7022    pub fn new_generator(
7023        &mut self,
7024        function: Value,
7025        this: Value,
7026        args: Vec<Value>,
7027    ) -> JsResult<Value> {
7028        let Some(object) = function.as_object().cloned() else {
7029            return Err(self.type_error("not a generator function"));
7030        };
7031        let Some((code, env)) = bytecode_of(&object) else {
7032            return Err(self.type_error("not a generator function"));
7033        };
7034        let is_async = code.code.kind.is_async();
7035        self.push_frame(code, env, this, args, function)?;
7036        let frame = self.frames.pop().expect("push_frame just pushed it");
7037        // A fresh generator is *suspended at start*: the body has not run, so a
7038        // `return`/`throw` on it finishes without executing anything.
7039        let mut state = GeneratorState {
7040            frame: Some(frame),
7041            phase: GeneratorPhase::SuspendedStart,
7042            parked_on_await: false,
7043            parked_on_yield_star: false,
7044            requests: std::collections::VecDeque::new(),
7045            async_busy: false,
7046        };
7047        // Run to the first suspension. For a generator that is `initial_yield`, so no
7048        // body code runs; for a malformed body it would be the first `yield`.
7049        // An `async function*` answers an async generator: same coroutine, but its
7050        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7051        let proto = if is_async {
7052            self.realm
7053                .async_generator_proto
7054                .clone()
7055                .unwrap_or_else(|| self.realm.generator_proto.clone())
7056        } else {
7057            self.realm.generator_proto.clone()
7058        };
7059        let generator = self.new_object(Some(proto));
7060        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7061            Ok(_) => {}
7062            Err(error) => return Err(error),
7063        }
7064        generator.with_mut(|data| {
7065            data.kind = ObjectKind::Generator(Box::new(state));
7066        });
7067        Ok(Value::Object(generator))
7068    }
7069
7070    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7071    ///
7072    /// Returns the `{value, done}` object itself rather than the pair, because a
7073    /// `yield*` suspension already has one — the inner iterator's own result — and the
7074    /// protocol says to hand that straight through rather than nest it.
7075    /// Advance a generator and report *why* it parked.
7076    ///
7077    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7078    /// "hand this value to the caller" — but an async generator does: an `await` has to
7079    /// settle before it can answer, while a `yield` is the answer.
7080    fn resume_generator_detailed(
7081        &mut self,
7082        generator: &Gc<JsObject>,
7083        kind: ResumeKind,
7084        value: Value,
7085    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7086        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7087            ObjectKind::Generator(state) => Some(std::mem::replace(
7088                state.as_mut(),
7089                GeneratorState {
7090                    frame: None,
7091                    phase: GeneratorPhase::Executing,
7092                    parked_on_await: false,
7093                    parked_on_yield_star: false,
7094                    requests: std::collections::VecDeque::new(),
7095                    async_busy: false,
7096                },
7097            )),
7098            _ => None,
7099        }) else {
7100            return Err(self.type_error("not a generator"));
7101        };
7102        let result = self.step_generator(&mut state, kind, value);
7103        generator.with_mut(|data| {
7104            data.kind = ObjectKind::Generator(Box::new(state));
7105        });
7106        result
7107    }
7108
7109    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7110    ///
7111    /// Returns the `{value, done}` object itself rather than the pair, because a
7112    /// `yield*` suspension already has one — the inner iterator's own result — and the
7113    /// protocol says to hand that straight through rather than nest it.
7114    pub fn resume_generator(
7115        &mut self,
7116        generator: &Gc<JsObject>,
7117        kind: ResumeKind,
7118        value: Value,
7119    ) -> JsResult<Value> {
7120        let (value, done, ready, _reason) =
7121            self.resume_generator_detailed(generator, kind, value)?;
7122        if ready {
7123            return Ok(value);
7124        }
7125        self.iterator_result(value, done)
7126    }
7127
7128    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7129    ///
7130    /// The body is the same coroutine a sync generator runs; what changes is that an
7131    /// `await` inside it has to settle before the method can answer, so the step is
7132    /// driven off the job queue rather than returning inline.
7133    pub fn resume_async_generator(
7134        &mut self,
7135        generator: &Gc<JsObject>,
7136        kind: ResumeKind,
7137        value: Value,
7138    ) -> JsResult<Value> {
7139        let promise = self.new_promise();
7140        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7141        // that order, and the second value must reach the *second* `yield`.
7142        let idle = generator.with_mut(|data| match &mut data.kind {
7143            ObjectKind::Generator(state) => {
7144                state.requests.push_back(AsyncRequest {
7145                    kind,
7146                    value,
7147                    promise: promise.clone(),
7148                });
7149                !state.async_busy
7150            }
7151            _ => false,
7152        });
7153        if idle {
7154            self.next_async_request(generator)?;
7155        }
7156        Ok(Value::Object(promise))
7157    }
7158
7159    /// Serve the front queued request, if the generator is free to run one.
7160    ///
7161    /// A finished generator answers from the queue without running anything:
7162    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7163    /// first, and `throw(e)` rejects.
7164    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7165        enum Front {
7166            Idle,
7167            Run(ResumeKind, Value, Gc<JsObject>),
7168            Finished(ResumeKind, Value, Gc<JsObject>),
7169        }
7170        let front = generator.with_mut(|data| match &mut data.kind {
7171            ObjectKind::Generator(state) => {
7172                let Some(request) = state.requests.front() else {
7173                    return Front::Idle;
7174                };
7175                // Busy means a request is still in flight — awaiting inside the body, not
7176                // finished. Serving another now would interleave two requests.
7177                if state.async_busy && state.phase != GeneratorPhase::Completed {
7178                    return Front::Idle;
7179                }
7180                let kind = request.kind;
7181                let value = request.value.clone();
7182                let promise = request.promise.clone();
7183                state.async_busy = true;
7184                if state.phase == GeneratorPhase::Completed {
7185                    Front::Finished(kind, value, promise)
7186                } else {
7187                    Front::Run(kind, value, promise)
7188                }
7189            }
7190            _ => Front::Idle,
7191        });
7192        match front {
7193            Front::Idle => Ok(()),
7194            Front::Run(kind, value, promise) => {
7195                self.step_async_generator(generator, &promise, kind, value)
7196            }
7197            Front::Finished(kind, value, promise) => match kind {
7198                ResumeKind::Throw => {
7199                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7200                }
7201                ResumeKind::Next | ResumeKind::Start => {
7202                    let result = self.iterator_result(Value::Undefined, true)?;
7203                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7204                }
7205                ResumeKind::Return => {
7206                    // `js_async_generator_completed_return`: the value is awaited before it
7207                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7208                    // finished generator answers `1`, not a promise.
7209                    let resolved = match self.promise_resolve_value(value) {
7210                        Ok(resolved) => resolved,
7211                        Err(Signal::Throw(reason)) => {
7212                            return self.settle_async_request(
7213                                generator,
7214                                &promise,
7215                                AsyncOutcome::Error(reason),
7216                            );
7217                        }
7218                        Err(other) => return Err(other),
7219                    };
7220                    let done = JsObject::function(
7221                        self.heap,
7222                        Some(self.realm.function_proto.clone()),
7223                        Callable::CompletedReturn {
7224                            generator: generator.clone(),
7225                            promise: promise.clone(),
7226                            rejected: false,
7227                        },
7228                    );
7229                    let failed = JsObject::function(
7230                        self.heap,
7231                        Some(self.realm.function_proto.clone()),
7232                        Callable::CompletedReturn {
7233                            generator: generator.clone(),
7234                            promise: promise.clone(),
7235                            rejected: true,
7236                        },
7237                    );
7238                    let Value::Object(resolved) = resolved else {
7239                        return self.settle_async_request(
7240                            generator,
7241                            &promise,
7242                            AsyncOutcome::Error(Value::Undefined),
7243                        );
7244                    };
7245                    self.perform_then(
7246                        &resolved,
7247                        Some(Value::Object(done)),
7248                        Some(Value::Object(failed)),
7249                    )?;
7250                    Ok(())
7251                }
7252            },
7253        }
7254    }
7255
7256    /// Settle the front request and start the next one.
7257    ///
7258    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7259    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7260    /// generator would strand every later request.
7261    fn settle_async_request(
7262        &mut self,
7263        generator: &Gc<JsObject>,
7264        promise: &Gc<JsObject>,
7265        outcome: AsyncOutcome,
7266    ) -> JsResult<()> {
7267        let settled = generator.with_mut(|data| match &mut data.kind {
7268            ObjectKind::Generator(state) => {
7269                let front = state.requests.front();
7270                debug_assert!(
7271                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7272                    "a request settled outside its turn"
7273                );
7274                state.requests.pop_front();
7275                state.async_busy = false;
7276                true
7277            }
7278            _ => false,
7279        });
7280        if settled {
7281            match outcome {
7282                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7283                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7284            }
7285        }
7286        self.next_async_request(generator)
7287    }
7288
7289    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7290    ///
7291    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7292    /// disposer runs **synchronously** — the reference starts it before returning, which
7293    /// a test can observe by logging after the call — and the rest follow once their
7294    /// predecessor settles.
7295    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7296        let promise = self.new_promise();
7297        let mut pairs = Vec::with_capacity(resources.len());
7298        for (value, method) in resources {
7299            let pair = self.new_array(vec![value, method]);
7300            pairs.push(Value::Object(pair));
7301        }
7302        let remaining = self.new_array(pairs);
7303        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7304        Ok(Value::Object(promise))
7305    }
7306
7307    /// One link of the `disposeAsync` chain.
7308    ///
7309    /// Loops while the disposers finish synchronously, and parks on the first thenable it
7310    /// meets — pushing itself back in as the continuation, with the accumulated error
7311    /// carried along so a later failure can still be folded into the `SuppressedError`.
7312    fn dispose_step(
7313        &mut self,
7314        remaining: &Gc<JsObject>,
7315        promise: &Gc<JsObject>,
7316        mut error: Value,
7317    ) -> JsResult<()> {
7318        loop {
7319            let length = remaining.array_length().unwrap_or(0);
7320            if length == 0 {
7321                if matches!(error, Value::Uninitialized) {
7322                    self.fulfill_promise(promise, Value::Undefined);
7323                } else {
7324                    self.reject_promise(promise, error);
7325                }
7326                return Ok(());
7327            }
7328            let Some(Value::Object(pair)) = remaining
7329                .array_get(length - 1)
7330                .filter(|v| !matches!(v, Value::Hole))
7331            else {
7332                remaining.array_truncate(self.heap, length - 1);
7333                continue;
7334            };
7335            remaining.array_truncate(self.heap, length - 1);
7336            let value = pair.array_get(0).unwrap_or(Value::Undefined);
7337            let Some(Value::Object(method)) = pair.array_get(1) else {
7338                continue;
7339            };
7340            if !method.is_callable() {
7341                continue;
7342            }
7343            match self.call_value(Value::Object(method), value, Vec::new()) {
7344                Ok(result) => {
7345                    if !self.is_thenable(&result)? {
7346                        // Finished synchronously; the next disposer is the next iteration.
7347                        continue;
7348                    }
7349                    let awaited = match self.promise_resolve_value(result) {
7350                        Ok(awaited) => awaited,
7351                        Err(Signal::Throw(reason)) => {
7352                            self.reject_promise(promise, reason);
7353                            return Ok(());
7354                        }
7355                        Err(other) => return Err(other),
7356                    };
7357                    let Value::Object(awaited) = awaited else {
7358                        continue;
7359                    };
7360                    let ok = JsObject::function(
7361                        self.heap,
7362                        Some(self.realm.function_proto.clone()),
7363                        Callable::DisposeStep {
7364                            remaining: remaining.clone(),
7365                            promise: promise.clone(),
7366                            error: error.clone(),
7367                            rejected: false,
7368                        },
7369                    );
7370                    let failed = JsObject::function(
7371                        self.heap,
7372                        Some(self.realm.function_proto.clone()),
7373                        Callable::DisposeStep {
7374                            remaining: remaining.clone(),
7375                            promise: promise.clone(),
7376                            error,
7377                            rejected: true,
7378                        },
7379                    );
7380                    self.perform_then(
7381                        &awaited,
7382                        Some(Value::Object(ok)),
7383                        Some(Value::Object(failed)),
7384                    )?;
7385                    return Ok(());
7386                }
7387                Err(Signal::Throw(thrown)) => {
7388                    error = self.merge_dispose_error(thrown, error);
7389                }
7390                Err(other) => return Err(other),
7391            }
7392        }
7393    }
7394
7395    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7396    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7397        let Value::Object(object) = value else {
7398            return Ok(false);
7399        };
7400        Ok(matches!(
7401            self.get_property(object, "then")?,
7402            Some(Value::Object(then)) if then.is_callable()
7403        ))
7404    }
7405
7406    /// One step of an async generator, settling `promise` with an `{value, done}` result.
7407    fn step_async_generator(
7408        &mut self,
7409        generator: &Gc<JsObject>,
7410        promise: &Gc<JsObject>,
7411        kind: ResumeKind,
7412        value: Value,
7413    ) -> JsResult<()> {
7414        let stepped = self.resume_generator_detailed(generator, kind, value);
7415        let (value, done, ready, reason) = match stepped {
7416            Ok(stepped) => stepped,
7417            Err(Signal::Throw(reason)) => {
7418                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7419            }
7420            Err(other) => return Err(other),
7421        };
7422        // Only an `await` has to wait before the method can answer.
7423        if !done && reason == Some(SuspendKind::Await) {
7424            let awaited = match self.promise_resolve_value(value) {
7425                Ok(awaited) => awaited,
7426                Err(Signal::Throw(reason)) => {
7427                    return self.settle_async_request(
7428                        generator,
7429                        promise,
7430                        AsyncOutcome::Error(reason),
7431                    );
7432                }
7433                Err(other) => return Err(other),
7434            };
7435            let Value::Object(awaited) = awaited else {
7436                return Ok(());
7437            };
7438            let resumed = JsObject::function(
7439                self.heap,
7440                Some(self.realm.function_proto.clone()),
7441                Callable::GeneratorResume {
7442                    generator: generator.clone(),
7443                    promise: promise.clone(),
7444                    kind: ResumeKind::Next,
7445                },
7446            );
7447            let raised = JsObject::function(
7448                self.heap,
7449                Some(self.realm.function_proto.clone()),
7450                Callable::GeneratorResume {
7451                    generator: generator.clone(),
7452                    promise: promise.clone(),
7453                    kind: ResumeKind::Throw,
7454                },
7455            );
7456            self.perform_then(
7457                &awaited,
7458                Some(Value::Object(resumed)),
7459                Some(Value::Object(raised)),
7460            )?;
7461            return Ok(());
7462        }
7463        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7464        // completes it — both arrive as the settled value rather than as the promise
7465        // object. A plain value skips the round trip, which is also what keeps `yield 1`
7466        // from costing an extra tick.
7467        let awaits_value = self.is_thenable(&value)?;
7468        if awaits_value {
7469            let awaited = match self.promise_resolve_value(value) {
7470                Ok(awaited) => awaited,
7471                Err(Signal::Throw(reason)) => {
7472                    return self.settle_async_request(
7473                        generator,
7474                        promise,
7475                        AsyncOutcome::Error(reason),
7476                    );
7477                }
7478                Err(other) => return Err(other),
7479            };
7480            let Value::Object(awaited) = awaited else {
7481                return Ok(());
7482            };
7483            // A rejected yield throws *at the yield* inside the body, so the rejection
7484            // resumes the generator rather than the method's promise.
7485            let answer = JsObject::function(
7486                self.heap,
7487                Some(self.realm.function_proto.clone()),
7488                Callable::YieldResult {
7489                    generator: generator.clone(),
7490                    promise: promise.clone(),
7491                    done,
7492                },
7493            );
7494            let raise = JsObject::function(
7495                self.heap,
7496                Some(self.realm.function_proto.clone()),
7497                Callable::GeneratorResume {
7498                    generator: generator.clone(),
7499                    promise: promise.clone(),
7500                    kind: ResumeKind::Throw,
7501                },
7502            );
7503            self.perform_then(
7504                &awaited,
7505                Some(Value::Object(answer)),
7506                Some(Value::Object(raise)),
7507            )?;
7508            return Ok(());
7509        }
7510        let result = if ready {
7511            // `yield*` handed back the inner iterator's own result object.
7512            value
7513        } else {
7514            self.iterator_result(value, done)?
7515        };
7516        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7517    }
7518
7519    /// The `{value, done}` object an iterator method answers with.
7520    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7521        let result = self.new_object(Some(self.realm.object_proto.clone()));
7522        result.define_data("value", value);
7523        result.define_data("done", Value::Bool(done));
7524        Ok(Value::Object(result))
7525    }
7526
7527    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7528    fn step_generator(
7529        &mut self,
7530        state: &mut GeneratorState,
7531        kind: ResumeKind,
7532        value: Value,
7533    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7534        match state.phase {
7535            GeneratorPhase::Executing => {
7536                return Err(self.type_error("cannot invoke a running generator"));
7537            }
7538            GeneratorPhase::Completed => {
7539                // A finished generator answers every resumption without running.
7540                return Ok(match kind {
7541                    ResumeKind::Throw => return Err(Signal::Throw(value)),
7542                    ResumeKind::Return => (value, true, false, None),
7543                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7544                });
7545            }
7546            GeneratorPhase::SuspendedStart => {
7547                if kind != ResumeKind::Next && kind != ResumeKind::Start {
7548                    // The body never started, so there is nothing to unwind or return
7549                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7550                    state.frame = None;
7551                    state.phase = GeneratorPhase::Completed;
7552                    return Ok(match kind {
7553                        ResumeKind::Throw => return Err(Signal::Throw(value)),
7554                        _ => (value, true, false, None),
7555                    });
7556                }
7557            }
7558            GeneratorPhase::SuspendedYield => {}
7559        }
7560
7561        let Some(mut frame) = state.frame.take() else {
7562            return Ok((Value::Undefined, true, false, None));
7563        };
7564        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7565        // number that says which method resumed it; the emitted `if_false` branches on
7566        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7567        let mut raised = None;
7568        match kind {
7569            ResumeKind::Next | ResumeKind::Start => {
7570                if state.phase == GeneratorPhase::SuspendedYield {
7571                    frame.stack.push(value);
7572                    // An `await` resumes with its value alone; only a `yield` gets the
7573                    // magic number that says which of `next`/`return` resumed it.
7574                    if !state.parked_on_await {
7575                        frame.stack.push(Value::Int(RESUME_NEXT));
7576                    }
7577                }
7578            }
7579            ResumeKind::Return => {
7580                // A `return` on a not-yet-started generator is handled above, so this is
7581                // always a real resumption.
7582                frame.stack.push(value);
7583                frame.stack.push(Value::Int(RESUME_RETURN));
7584            }
7585            ResumeKind::Throw => {
7586                // At a `yield*` the exception is *data* for the delegation: the compiled
7587                // code resumes with the value and magic `2` and calls the inner iterator's
7588                // `throw`. Everywhere else it is raised at the suspension point, so the
7589                // body's own handler sees it.
7590                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7591                    frame.stack.push(value);
7592                    frame.stack.push(Value::Int(RESUME_THROW));
7593                } else {
7594                    raised = Some(value);
7595                }
7596            }
7597        }
7598        state.phase = GeneratorPhase::Executing;
7599
7600        let depth = self.frames.len();
7601        self.frames.push(frame);
7602        // A `throw` unwinds from where the frame parked, exactly as if the exception had
7603        // happened at the `yield`.
7604        if let Some(exception) = raised {
7605            if self.catch_here(exception.clone()).is_none() {
7606                self.pop_frame();
7607                state.phase = GeneratorPhase::Completed;
7608                return Err(Signal::Throw(exception));
7609            }
7610        }
7611
7612        // Only the generator's *own* frame ends the generator. The body may call ordinary
7613        // functions, and those push frames of their own: a `Step::Return` from one of them
7614        // is a nested call finishing, not the generator completing. Miscounting that is
7615        // silent — the generator reports the callee's value as its own result and marks
7616        // itself done — so the depth comparison is load-bearing, not defensive.
7617        let own_frame = depth + 1;
7618        loop {
7619            match self.step() {
7620                Ok(Step::Continue) => {}
7621                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7622                    let mut frame = self.frames.pop().expect("a frame is live");
7623                    // `yield` left the value on the stack; `initial_yield` left nothing.
7624                    let yielded = if reason == SuspendKind::Initial {
7625                        Value::Undefined
7626                    } else {
7627                        frame.stack.pop().unwrap_or(Value::Undefined)
7628                    };
7629                    state.frame = Some(frame);
7630                    state.parked_on_await = reason == SuspendKind::Await;
7631                    state.parked_on_yield_star =
7632                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7633                    state.phase = if reason == SuspendKind::Initial {
7634                        GeneratorPhase::SuspendedStart
7635                    } else {
7636                        GeneratorPhase::SuspendedYield
7637                    };
7638                    // `yield*` hands the inner iterator's own result object straight
7639                    // back, so the caller sees one `{value, done}` rather than a nested
7640                    // one — which is why the third field says "already a result".
7641                    return Ok((
7642                        yielded,
7643                        false,
7644                        reason == SuspendKind::YieldStar,
7645                        Some(reason),
7646                    ));
7647                }
7648                Ok(Step::Suspend(_)) => {
7649                    // A `yield` in a frame other than the generator's would mean a
7650                    // generator body entered as an ordinary call, which
7651                    // `call_or_push` prevents.
7652                    self.unwind_to(depth);
7653                    state.phase = GeneratorPhase::Completed;
7654                    return Err(Signal::Throw(self.make_error(
7655                        "InternalError",
7656                        "a generator body ran as an ordinary call",
7657                    )));
7658                }
7659                Ok(Step::Return(value)) => {
7660                    self.pop_frame();
7661                    if self.frames.len() > depth {
7662                        // A nested call finished: hand the value back to its caller and
7663                        // keep running the generator body.
7664                        self.frames
7665                            .last_mut()
7666                            .expect("a caller is live")
7667                            .stack
7668                            .push(value);
7669                        continue;
7670                    }
7671                    state.phase = GeneratorPhase::Completed;
7672                    // The reference closes the generator's closure variables here; ours
7673                    // live in cells the frame owned, which the drop below releases.
7674                    return Ok((value, true, false, None));
7675                }
7676                Err(Signal::Throw(exception)) => {
7677                    // The frame that threw gets the first chance to catch, exactly as in
7678                    // the ordinary call loop; a frame above the generator's is popped and
7679                    // the exception carries on down.
7680                    let exception = exception;
7681                    loop {
7682                        if self.frames.len() <= depth {
7683                            // The generator's own frame is gone, so nothing here caught it.
7684                            state.phase = GeneratorPhase::Completed;
7685                            return Err(Signal::Throw(exception));
7686                        }
7687                        if self.catch_here(exception.clone()).is_some() {
7688                            break;
7689                        }
7690                        self.pop_frame();
7691                    }
7692                }
7693                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7694            }
7695        }
7696    }
7697
7698    /// Pop frames until `depth` are left, keeping their buffers.
7699    fn unwind_to(&mut self, depth: usize) {
7700        while self.frames.len() > depth {
7701            self.pop_frame();
7702        }
7703    }
7704    fn call_or_push(
7705        &mut self,
7706        callee: Value,
7707        this: Value,
7708        args: Vec<Value>,
7709    ) -> JsResult<Option<Value>> {
7710        if let Value::Object(function) = &callee
7711            && let Some((code, env)) = bytecode_of(function)
7712        {
7713            // Calling a generator function does not run anything: it captures the
7714            // arguments in a frame and hands back the generator object.
7715            if code.code.kind.is_generator() {
7716                return self.new_generator(callee, this, args).map(Some);
7717            }
7718            // An async function answers a promise and runs its body as a coroutine, so it
7719            // takes the same path as a plain call into it.
7720            if code.code.kind.is_async() {
7721                return self.new_async_function(callee, this, args).map(Some);
7722            }
7723            self.push_frame(code, env, this, args, callee)?;
7724            return Ok(None);
7725        }
7726        self.call_value(callee, this, args).map(Some)
7727    }
7728
7729    /// `new callee(args)`.
7730    ///
7731    /// A constructor differs from a plain call in three ways: it gets a fresh object
7732    /// as `this` whose prototype is the constructor's `prototype` property, its
7733    /// return value is *replaced* by that object unless it returns an object itself,
7734    /// and a native constructor is expected to initialise the object it is given
7735    /// rather than build one.
7736    pub fn construct(
7737        &mut self,
7738        callee: Value,
7739        new_target: Value,
7740        args: Vec<Value>,
7741    ) -> JsResult<Value> {
7742        // `new` on a bound function constructs its *target*, prepending the arguments
7743        // the bind fixed and ignoring the bound `this` — a bound function is a
7744        // constructor only when its target is one, and `new` always makes a fresh
7745        // object of the target's prototype rather than reusing the bound receiver.
7746        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7747        // ran the body with `this === null` and threw on `this.x = a`.
7748        let mut callee = callee;
7749        let mut new_target = new_target;
7750        let mut args = args;
7751        loop {
7752            let Some(object) = callee.as_object().cloned() else {
7753                return Err(Signal::Throw(
7754                    self.make_error("TypeError", "not a constructor"),
7755                ));
7756            };
7757            // A proxy of a function constructs through its `construct` trap, and the
7758            // trap's answer is the result directly — no fresh object is made here.
7759            if object.proxy_state().is_some() {
7760                return match self.proxy_construct(&object, args, &new_target)? {
7761                    Some(result) => Ok(result),
7762                    None => Err(Signal::Throw(
7763                        self.make_error("TypeError", "proxy target is not a constructor"),
7764                    )),
7765                };
7766            }
7767            // A generator function has no `[[Construct]]`, and the reference names it in
7768            // the message: `new (function* G(){})()` reports "G is not a constructor".
7769            if object.with(|data| match &data.kind {
7770                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7771                    code.code.kind.is_generator()
7772                }
7773                _ => false,
7774            }) {
7775                let name = object
7776                    .own_property("name")
7777                    .and_then(|property| property.value)
7778                    .map(|value| value.to_js_string())
7779                    .unwrap_or_default();
7780                return Err(Signal::Throw(
7781                    self.make_error("TypeError", &format!("{name} is not a constructor")),
7782                ));
7783            }
7784            let bound = object.with(|data| match &data.kind {
7785                ObjectKind::Function(Callable::Bound {
7786                    target,
7787                    args: leading,
7788                    ..
7789                }) => Some((target.clone(), leading.clone())),
7790                _ => None,
7791            });
7792            let Some((target, leading)) = bound else {
7793                // Not a bound function, so this object is the callee. §7.2.4
7794                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7795                // refusals above cover only the built-ins the reference also refuses by
7796                // name. Everything else — a method, an arrow, an async function — has no
7797                // `[[Construct]]` either, and answering "yes" here made
7798                // `new (Array.prototype.map)` build an object instead of throwing.
7799                if !object.is_constructor() {
7800                    let name = object
7801                        .own_property("name")
7802                        .and_then(|property| property.value)
7803                        .map(|value| value.to_js_string())
7804                        .unwrap_or_default();
7805                    return Err(Signal::Throw(
7806                        self.make_error("TypeError", &format!("{name} is not a constructor")),
7807                    ));
7808                }
7809                break;
7810            };
7811            let mut all = leading;
7812            all.extend(args);
7813            args = all;
7814            // A bound function that is its own `new.target` stands in for its target:
7815            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
7816            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
7817            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
7818                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
7819                _ => false,
7820            };
7821            if same_wrapper {
7822                new_target = target.clone();
7823            }
7824            callee = target;
7825        }
7826        let Value::Object(function) = &callee else {
7827            unreachable!("the loop above only breaks on an object");
7828        };
7829        // The fresh object's prototype comes from `new.target`, not from the callee: a
7830        // derived constructor reaches here through `super()`, and the instance must be a
7831        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7832        // an object inheriting `D.prototype` rather than `C.prototype`.
7833        let prototype_source = match new_target.as_object() {
7834            Some(target) => target.clone(),
7835            None => function.clone(),
7836        };
7837        // A native constructor builds its own instance, through `new_ctor_instance`, once it
7838        // has validated its arguments. Pre-building one here would read
7839        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7840        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7841        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7842        let is_native = function.native_creates_own_instance();
7843        let this = if is_native {
7844            Value::Undefined
7845        } else {
7846            let prototype = self.get_property(&prototype_source, "prototype")?;
7847            let prototype = match prototype {
7848                Some(Value::Object(proto)) => Some(proto),
7849                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7850                // object, the answer is the realm's *intrinsic* prototype for this
7851                // constructor, not `%Object.prototype%`.
7852                _ => {
7853                    let fallback = self.get_property(function, "prototype")?;
7854                    match fallback {
7855                        Some(Value::Object(proto)) => Some(proto),
7856                        _ => Some(self.realm.object_proto.clone()),
7857                    }
7858                }
7859            };
7860            Value::Object(self.new_object(prototype))
7861        };
7862        // `new.target` inside the body is the constructor that was written, so a bound
7863        // function's target sees itself rather than the bound wrapper.
7864        //
7865        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7866        // `?`, so assigning `None` after the call would be skipped and the failed
7867        // `new.target` would stay visible to every later native call. The symptom was a
7868        // native constructor refusing a plain call — `var s = Symbol(); new
7869        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
7870        // "FinalizationRegistry is not a constructor".
7871        let outer_new_target = self.pending_new_target.replace(new_target);
7872        let result = self.call_value(callee, this.clone(), args);
7873        self.pending_new_target = outer_new_target;
7874        let result = result?;
7875        // A constructor that returns an object overrides `this`; any other return
7876        // value (including `undefined`) is ignored.
7877        Ok(match result {
7878            Value::Object(_) => result,
7879            _ => this,
7880        })
7881    }
7882
7883    /// `new.target` for the call currently being made.
7884    ///
7885    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
7886    /// it as `this`), but a *host* constructor that builds its own instance is handed
7887    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
7888    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
7889    /// it here.
7890    ///
7891    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
7892    /// receives for a plain call.
7893    pub fn current_new_target(&self) -> Value {
7894        self.pending_new_target.clone().unwrap_or(Value::Undefined)
7895    }
7896
7897    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
7898    ///
7899    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
7900    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
7901    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
7902        let constructor = self.realm.errors.get("AggregateError").cloned();
7903        let Some(constructor) = constructor else {
7904            return self.make_error("AggregateError", message);
7905        };
7906        let list = self.new_array(errors);
7907        match self.construct(
7908            Value::Object(constructor.clone()),
7909            Value::Object(constructor),
7910            vec![Value::Object(list), self.string(message)],
7911        ) {
7912            Ok(value) => value,
7913            // A user could have replaced `AggregateError` with something that throws; the
7914            // engine still owes the caller a rejection, so it falls back rather than
7915            // turning `Promise.any`'s rejection into a throw.
7916            Err(_) => self.make_error("AggregateError", message),
7917        }
7918    }
7919
7920    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
7921    ///
7922    /// The error classes themselves arrive with the builtins milestone; what
7923    /// matters here is that the thrown value stringifies the way a script printing
7924    /// the caught value expects.
7925    ///
7926    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
7927    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
7928    /// rely on when they print a caught value.
7929    pub fn make_error(&self, name: &str, message: &str) -> Value {
7930        let proto = self
7931            .realm
7932            .errors
7933            .get(name)
7934            .map(|constructor| self.prototype_of(constructor))
7935            .unwrap_or_else(|| self.realm.error_proto.clone());
7936        let error = self.new_object(Some(proto));
7937        // `name` and `message` are own properties of the instance, which is what
7938        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
7939        // `Error`.
7940        error.define(
7941            "name",
7942            Property::with_attributes(self.string(name), true, false),
7943        );
7944        error.define(
7945            "message",
7946            Property::with_attributes(self.string(message), true, false),
7947        );
7948        // The internal class, which is what tells a printer this is an error rather than a
7949        // plain object with `name` and `message` properties. The constructor path sets it
7950        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
7951        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
7952        // literally `"Error"` in both places — the *name* is read from `name`, which is why
7953        // a `RangeError` still prints as `RangeError`.
7954        self.internal_set(&error, "_class", self.string("Error"));
7955        // The trace is captured where the error is *made*, which is where the reference
7956        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
7957        // way out, so a caught engine error already has its stack even if the handler
7958        // never rethrows it.
7959        self.add_stack(&error);
7960        Value::Object(error)
7961    }
7962
7963    /// Give an error object its `stack` property, from the current frame stack.
7964    ///
7965    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
7966    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
7967    /// `stack` a script set, is not rewritten.
7968    pub fn add_stack(&self, object: &Gc<JsObject>) {
7969        self.add_stack_skipping(object, 0);
7970    }
7971
7972    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
7973    ///
7974    /// An `Error` constructor passes 1: the reference builds those traces with
7975    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
7976    /// constructor itself, while a `RangeError` raised inside `toISOString` does
7977    /// report `at toISOString (native)`.
7978    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
7979        if object.has_own("stack") {
7980            return;
7981        }
7982        let trace = self.stack_trace_skipping(skip);
7983        let text = self.string(trace);
7984        object.define("stack", Property::with_attributes(text, true, true));
7985    }
7986
7987    /// The function object currently being called, if any.
7988    ///
7989    /// A native function is a bare `fn` pointer, so it cannot capture which class
7990    /// it belongs to; it reads that from the callee instead. This is also what a
7991    /// stack trace would use.
7992    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
7993        match &self.frames.last()?.callee {
7994            Value::Object(object) => Some(object.clone()),
7995            _ => None,
7996        }
7997    }
7998
7999    /// The `prototype` property of a constructor, falling back to
8000    /// `Object.prototype` for anything that is not shaped like one.
8001    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
8002        constructor
8003            .own_property("prototype")
8004            .and_then(|property| property.value)
8005            .and_then(|value| value.as_object().cloned())
8006            .unwrap_or_else(|| self.realm.object_proto.clone())
8007    }
8008
8009    /// Throw a `TypeError` carrying `message`.
8010    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
8011        Signal::Throw(self.make_error("TypeError", message.as_ref()))
8012    }
8013
8014    /// Throw a `RangeError` carrying `message`.
8015    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
8016        Signal::Throw(self.make_error("RangeError", message.as_ref()))
8017    }
8018
8019    /// The `ReferenceError` a read of an uninitialised binding raises.
8020    /// The name of the binding `slot` refers to, for an error message.
8021    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
8022        match kind {
8023            VarSlot::Loc => self
8024                .frame()
8025                .code
8026                .code
8027                .vars
8028                .get(slot)
8029                .map(|v| v.name.clone()),
8030            VarSlot::Closure => self
8031                .frame()
8032                .code
8033                .code
8034                .closure_vars
8035                .get(slot)
8036                .map(|c| c.name.clone()),
8037        }
8038        .unwrap_or_default()
8039    }
8040
8041    /// Whether `slot` names a `const` binding, which rejects every store after its
8042    /// initialiser.
8043    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8044        match kind {
8045            VarSlot::Loc => self
8046                .frame()
8047                .code
8048                .code
8049                .vars
8050                .get(slot)
8051                .is_some_and(|v| v.is_const),
8052            VarSlot::Closure => self
8053                .frame()
8054                .code
8055                .code
8056                .closure_vars
8057                .get(slot)
8058                .is_some_and(|c| c.is_const),
8059        }
8060    }
8061
8062    /// The `TypeError` a store to a `const` binding raises.
8063    ///
8064    /// `const` is enforced here rather than at compile time because the binding can be
8065    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8066    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8067    /// both halves of what "checked store" means: the dead zone is over, and the
8068    /// binding is writable.
8069    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8070        let name = self.binding_name(slot, kind);
8071        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8072    }
8073
8074    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8075        let name = match kind {
8076            VarSlot::Loc => self
8077                .frame()
8078                .code
8079                .code
8080                .vars
8081                .get(slot)
8082                .map(|v| v.name.clone()),
8083            VarSlot::Closure => self
8084                .frame()
8085                .code
8086                .code
8087                .closure_vars
8088                .get(slot)
8089                .map(|c| c.name.clone()),
8090        }
8091        .unwrap_or_default();
8092        Signal::Throw(self.make_error(
8093            "ReferenceError",
8094            &format!("cannot access '{name}' before initialization"),
8095        ))
8096    }
8097
8098    fn throw_reference(&self, name: &str) -> Signal {
8099        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8100    }
8101
8102    // -- the instruction loop -----------------------------------------------
8103
8104    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8105    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8106    // measured at 16% of a tight arithmetic loop's total time.
8107    #[inline(always)]
8108    fn step(&mut self) -> JsResult<Step> {
8109        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8110        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8111        // borrow lives across the boundary; nothing is cloned.
8112        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8113        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8114        // write, and once more inside the handler), and each is a bounds check plus an
8115        // `Option` unwrap — on the one path every instruction takes.
8116        let Some((insn, next)) = ({
8117            let frame = self
8118                .frames
8119                .last_mut()
8120                .expect("step() is only called with a live frame");
8121            // Past the last instruction is a normal return: the compiler ends a function
8122            // with `return`, and a jump to the end of a block lands here.
8123            let insn = frame.insns().get(frame.pc).copied();
8124            match insn {
8125                None => None,
8126                Some(insn) => {
8127                    // A fused record stands for the next few instructions, so the next
8128                    // `pc` is its width ahead — the instructions it replaces are never
8129                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8130                    // an offset because the line table is keyed by bytes.
8131                    frame.at = insn.offset as usize;
8132                    frame.pc += insn.width();
8133                    Some((insn, frame.pc))
8134                }
8135            }
8136        }) else {
8137            return Ok(Step::Return(Value::Undefined));
8138        };
8139        self.check_memory()?;
8140        self.check_interrupt()?;
8141        if insn.fused == crate::insn::Fused::None {
8142            self.execute_instruction(insn.op, insn.a, insn.b, next)
8143        } else {
8144            self.execute_fused(insn)
8145        }
8146    }
8147
8148    /// Run a fused instruction: several bytecode instructions in one dispatch.
8149    ///
8150    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8151    /// it cannot throw and cannot allocate — and anything else falls back to the real
8152    /// instructions, in their real order, so an exception leaves the operand stack
8153    /// exactly as it would have been.
8154    #[inline]
8155    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8156        use crate::insn::Fused;
8157        let slot = insn.a as usize;
8158        match insn.fused {
8159            // `x = k`: `push k; put_loc x`.
8160            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8161            // `x += k`: `get_loc x; push k; add; put_loc x`.
8162            Fused::AddImmLoc => {
8163                let delta = insn.b as i32;
8164                match self.get_loc(slot) {
8165                    Value::Int(left) => {
8166                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8167                        // that built two `Value`s, called a function, and matched on them
8168                        // again to reach this same `checked_add`. It is the innermost
8169                        // operation of every accumulator in every program.
8170                        let answer = match left.checked_add(delta) {
8171                            Some(sum) => Value::Int(sum),
8172                            None => Value::Float(left as f64 + delta as f64),
8173                        };
8174                        self.put_loc(slot, answer);
8175                    }
8176                    other => {
8177                        self.push(other);
8178                        self.push(Value::Int(delta));
8179                        self.binary_add()?;
8180                        let value = self.pop();
8181                        self.put_loc(slot, value);
8182                    }
8183                }
8184            }
8185            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8186            Fused::AddAtomLoc => {
8187                let text = self.atom_wtf8(insn.b as usize);
8188                let right = self.string_wtf8(text);
8189                self.add_into_loc(slot, right)?;
8190            }
8191            Fused::AddLocLoc => {
8192                let source = (insn.a & 0xFFFF) as usize;
8193                let target = (insn.a >> 16) as usize;
8194                let right = self.get_loc(source);
8195                self.add_into_loc(target, right)?;
8196            }
8197            Fused::AddArgLoc => {
8198                let source = (insn.a & 0xFFFF) as usize;
8199                let target = (insn.a >> 16) as usize;
8200                let right = self.get_arg(source);
8201                self.add_into_loc(target, right)?;
8202            }
8203            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8204            Fused::PostIncLoc => match self.get_loc(slot) {
8205                Value::Int(left) => {
8206                    let answer = match left.checked_add(1) {
8207                        Some(sum) => Value::Int(sum),
8208                        None => Value::Float(left as f64 + 1.0),
8209                    };
8210                    self.put_loc(slot, answer);
8211                }
8212                other => {
8213                    self.push(other);
8214                    let raw = self.pop();
8215                    let (old, updated) = self.advance_numeric(raw, true)?;
8216                    self.push(old);
8217                    self.push(updated);
8218                    let value = self.pop();
8219                    self.put_loc(slot, value);
8220                    self.pop();
8221                }
8222            },
8223            // `if (!(x < arg)) goto target`: a loop header.
8224            //
8225            // The comparison is computed rather than replayed on the operand stack. That
8226            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8227            // that throws: the effects happen in the same order, and a handler truncates
8228            // the stack down to its marker, so the intermediate values are unobservable.
8229            Fused::LtLocArgJump => {
8230                let loc = (insn.a >> 16) as usize;
8231                let arg = (insn.a & 0xFFFF) as usize;
8232                let left = self.get_loc(loc);
8233                let right = self.get_arg(arg);
8234                let taken = match (&left, &right) {
8235                    (Value::Int(left), Value::Int(right)) => !(left < right),
8236                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8237                };
8238                if taken {
8239                    self.frame_mut().pc = insn.b as usize;
8240                }
8241            }
8242            // `i < k` in a loop header, where `k` is an integer literal.
8243            Fused::LtLocImmJump => {
8244                let left = self.get_loc(insn.a as usize);
8245                let right = Value::Int(insn.imm as i32);
8246                let taken = match &left {
8247                    Value::Int(left) => !(*left < insn.imm as i32),
8248                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8249                };
8250                if taken {
8251                    self.frame_mut().pc = insn.b as usize;
8252                }
8253            }
8254            Fused::None => unreachable!("only called for a fused record"),
8255        }
8256        Ok(Step::Continue)
8257    }
8258
8259    /// Run records that cannot call script, cannot throw and cannot change frames.
8260    ///
8261    /// Returns `Some(value)` when the function ran off the end of its instructions (a
8262    /// normal return), and `None` when it stopped in front of an instruction the slow path
8263    /// has to handle — `pc` is written back either way, so `step` resumes at the right
8264    /// place.
8265    ///
8266    /// **The invariant is the whole point.** Every arm here is restricted to work that
8267    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8268    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8269    /// that the memory limit has to see. An opcode whose operands turn out to need any of
8270    /// that **stops the loop** instead of trying, so the slow path gets the instruction
8271    /// untouched and with its operands still on the stack. That is why the fallback is a
8272    /// `break` and not a duplicated slow arm: a second implementation of the same
8273    /// semantics is how a wrong answer gets in with no test noticing.
8274    ///
8275    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8276    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8277    fn run_fast(&mut self) -> JsResult<Option<Value>> {
8278        use crate::insn::Fused;
8279        // The outer loop exists only so a `Call` can come back through here: once a
8280        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8281        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8282        // frame. Re-entering re-reads both from whichever frame is now on top. Every
8283        // other exit from the inner loop returns, so this costs one loop per call.
8284        'outer: loop {
8285            // One reference-count bump per *slow* instruction (a call, an allocation, a
8286            // property access), never one per instruction — that distinction is worth
8287            // two orders of magnitude and was measured as such.
8288            let (code, mut pc) = {
8289                let frame = self.frame();
8290                (frame.code.clone(), frame.pc)
8291            };
8292            let insns = &code.insns;
8293            loop {
8294                let Some(insn) = insns.get(pc).copied() else {
8295                    self.frame_mut().pc = pc;
8296                    return Ok(Some(Value::Undefined));
8297                };
8298                match insn.fused {
8299                    // `x = k`
8300                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8301                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8302                    // object — stops the loop so `binary_add` can decide.
8303                    Fused::AddImmLoc => {
8304                        let slot = insn.a as usize;
8305                        let delta = insn.b as i32;
8306                        let Value::Int(left) = self.get_loc(slot) else {
8307                            return Ok(self.stop(pc));
8308                        };
8309                        let sum = match left.checked_add(delta) {
8310                            Some(sum) => Value::Int(sum),
8311                            None => Value::Float(left as f64 + delta as f64),
8312                        };
8313                        self.put_loc(slot, sum);
8314                    }
8315                    // `x += "literal"` / `x += y`: the operand is a string, so the append
8316                    // either allocates one or grows one. Both are the slow path's business;
8317                    // the fusion's job is only to make the *slot* the sole owner, which is what
8318                    // `execute_fused` needs and what `get_loc` alone destroys.
8319                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8320                        return Ok(self.stop(pc));
8321                    }
8322                    // `x++` on an integer, old value dropped.
8323                    Fused::PostIncLoc => {
8324                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8325                        // value is read in place and overwritten in place, so the reference
8326                        // count it held is released by the same assignment that stores the
8327                        // new one. `get_loc` plus `put_loc` did two borrows, two table
8328                        // lookups and a clone, and this arm is the whole body of a counting
8329                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8330                        let slot = insn.a as usize;
8331                        let frame = self.frames.last_mut().expect("a frame is live");
8332                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8333                        let target = if cell < 0 {
8334                            frame.locals.get_mut(slot)
8335                        } else {
8336                            None
8337                        };
8338                        let Some(target) = target else {
8339                            return Ok(self.stop(pc));
8340                        };
8341                        let Value::Int(left) = *target else {
8342                            return Ok(self.stop(pc));
8343                        };
8344                        *target = match left.checked_add(1) {
8345                            Some(sum) => Value::Int(sum),
8346                            None => Value::Float(left as f64 + 1.0),
8347                        };
8348                    }
8349                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
8350                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8351                    // bound stayed small integers.
8352                    Fused::LtLocArgJump => {
8353                        let loc = (insn.a >> 16) as usize;
8354                        let arg = (insn.a & 0xFFFF) as usize;
8355                        // One borrow for both slots: this arm *is* the whole loop of a
8356                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
8357                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
8358                        // `dispatch:empty-loop`.
8359                        let (left, right) = {
8360                            let frame = self.frame();
8361                            (frame.read_loc(loc), frame.read_arg(arg))
8362                        };
8363                        // Heavily measured: the bound is very often a `Float` even when the
8364                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8365                        // `JSON.parse` or a division is one — so requiring both sides to be
8366                        // `Int` sent every iteration of those loops down the slow path. The
8367                        // comparison below is the same one `relational` makes for two numbers.
8368                        if !is_number(&left) || !is_number(&right) {
8369                            return Ok(self.stop(pc));
8370                        }
8371                        // `if_false` branches on the comparison being false, which is **not**
8372                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8373                        // `>=` is also false and would keep it running forever. Clippy wants the
8374                        // negation folded; that would be a wrong answer.
8375                        let ordered = left.to_number() < right.to_number();
8376                        let take_branch = !ordered;
8377                        if take_branch {
8378                            pc = insn.b as usize;
8379                            continue;
8380                        }
8381                    }
8382                    // The same header with a literal bound: `if (!(x < k)) goto target`.
8383                    // The bound is an immediate, so only the counter needs a type test.
8384                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
8385                    Fused::LtLocImmJump => {
8386                        let left = self.get_loc(insn.a as usize);
8387                        if !is_number(&left) {
8388                            return Ok(self.stop(pc));
8389                        }
8390                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8391                        if take_branch {
8392                            pc = insn.b as usize;
8393                            continue;
8394                        }
8395                    }
8396                    Fused::None => match insn.op {
8397                        // -- branches ---------------------------------------------------
8398                        // A jump is an assignment now, because the target is an instruction
8399                        // index. No arithmetic, no resolution table.
8400                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8401                            let target = insn.a as usize;
8402                            // A **back-edge** is a loop, and it is the only place an
8403                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
8404                            // to a jump to itself and never leaves this loop, so the
8405                            // per-instruction checks in `step` never run. That is exactly the
8406                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
8407                            // nothing to a `for(;;){}` until it did, which is what
8408                            // `tests/c/embed.c` is for.
8409                            //
8410                            // Polling here rather than on every instruction in this loop is
8411                            // also the reference's choice (`OP_goto` calls
8412                            // `js_poll_interrupts`), and it costs one compare per branch
8413                            // instead of one decrement per instruction.
8414                            if target <= pc {
8415                                self.frame_mut().pc = target;
8416                                self.check_memory()?;
8417                                self.check_interrupt()?;
8418                            }
8419                            pc = target;
8420                            continue;
8421                        }
8422                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8423                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8424                            let taken = self.pop().to_boolean();
8425                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8426                            if taken == want {
8427                                pc = insn.a as usize;
8428                                continue;
8429                            }
8430                        }
8431                        // -- slot access -------------------------------------------------
8432                        // A load's slot is already an operand (see `insn::implicit_operand`);
8433                        // a captured one goes through its cell, which runs no script.
8434                        Opcode::GetLoc
8435                        | Opcode::GetLoc8
8436                        | Opcode::GetLoc0
8437                        | Opcode::GetLoc1
8438                        | Opcode::GetLoc2
8439                        | Opcode::GetLoc3 => {
8440                            let value = self.get_loc(insn.a as usize);
8441                            self.push(value);
8442                        }
8443                        Opcode::PutLoc
8444                        | Opcode::PutLoc8
8445                        | Opcode::PutLoc0
8446                        | Opcode::PutLoc1
8447                        | Opcode::PutLoc2
8448                        | Opcode::PutLoc3 => {
8449                            let value = self.pop();
8450                            self.put_loc(insn.a as usize, value);
8451                        }
8452                        Opcode::GetArg
8453                        | Opcode::GetArg0
8454                        | Opcode::GetArg1
8455                        | Opcode::GetArg2
8456                        | Opcode::GetArg3 => {
8457                            let value = self.get_arg(insn.a as usize);
8458                            self.push(value);
8459                        }
8460                        Opcode::PutArg
8461                        | Opcode::PutArg0
8462                        | Opcode::PutArg1
8463                        | Opcode::PutArg2
8464                        | Opcode::PutArg3 => {
8465                            let value = self.pop();
8466                            self.put_arg(insn.a as usize, value);
8467                        }
8468                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
8469                        // for why a non-hole own element is exactly the slow path's answer.
8470                        // The two operands are *peeked*, so a miss leaves the stack as the
8471                        // slow path expects to find it.
8472                        Opcode::GetArrayEl => {
8473                            // One lookup, not two. The guard used `if …is_some()` and the arm
8474                            // then called it again to get the value — two `peek`s, two
8475                            // `array_get`s and two `Value` clones for one element.
8476                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
8477                            // double call was the first version of the `get_field` fast path.
8478                            let Some(value) = self.fast_array_get() else {
8479                                return Ok(self.stop(pc));
8480                            };
8481                            // `a[i]` consumes both operands and leaves the element in their
8482                            // place: one `truncate` and one write, no `pop`/`push` pair.
8483                            let frame = self.frame_mut();
8484                            frame.stack.truncate(frame.stack.len() - 2);
8485                            frame.stack.push(value);
8486                        }
8487                        // `a[i] = v` on a dense array with an integer index: see
8488                        // `fast_array_set` for why the whole store is one step.
8489                        Opcode::PutArrayEl if self.fast_array_set() => {}
8490                        // `o.x` resolved from the inline cache without leaving the loop.
8491                        //
8492                        // The cache is keyed by `(receiver identity, atom, site)` and a
8493                        // monomorphic read re-validates the same chain every iteration, so
8494                        // each one used to cost a `stop(pc)` — a write of `pc` into the
8495                        // frame, a return out of this loop, a re-dispatch through `step` and
8496                        // a re-entry. `property:monomorphic` spent 18% in
8497                        // `read_field_cached` and 21% in `push`, both across that boundary.
8498                        //
8499                        // The site is `pc + width`, which is exactly the `next` the slow arm
8500                        // passes — the two must agree or every fast lookup misses and
8501                        // re-records the same entry forever.
8502                        //
8503                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8504                        // slow arm finds the receiver where it expects it.
8505                        // `name` resolved from the global-variable cache inside the loop.
8506                        //
8507                        // Same shape as `get_field` above and for the same reason: `get_var`
8508                        // was not in the fast loop, so reading a global — which `fib` does
8509                        // once per recursive call, for its own name — cost a `stop(pc)`, a
8510                        // return out of the loop, a `step` re-dispatch and a re-entry, before
8511                        // `get_global` even started its `scopes_are_plain` checks.
8512                        //
8513                        // Everything here is exactly `get_global`'s first branch: not lexical,
8514                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
8515                        // and lets the slow arm decide.
8516                        Opcode::GetVar => {
8517                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8518                                return Ok(self.stop(pc));
8519                            };
8520                            self.push(value);
8521                        }
8522                        Opcode::GetField | Opcode::GetField2 => {
8523                            let Some(value) =
8524                                self.fast_field_get(insn.a as usize, pc + insn.width())
8525                            else {
8526                                return Ok(self.stop(pc));
8527                            };
8528                            if insn.op == Opcode::GetField2 {
8529                                // `get_field2` keeps the receiver for the `call_method` that
8530                                // follows.
8531                                self.push(value);
8532                            } else {
8533                                // `get_field` replaces the receiver, so this is one store over
8534                                // the top slot rather than a `pop` and a `push`: the length
8535                                // never changes, so neither `Vec` arm has a capacity check or a
8536                                // drop to run beyond the one the overwrite itself does.
8537                                let frame = self.frame_mut();
8538                                match frame.stack.last_mut() {
8539                                    Some(slot) => *slot = value,
8540                                    None => return Ok(self.stop(pc)),
8541                                }
8542                            }
8543                        }
8544                        // -- constants ---------------------------------------------------
8545                        Opcode::PushMinus1
8546                        | Opcode::Push0
8547                        | Opcode::Push1
8548                        | Opcode::Push2
8549                        | Opcode::Push3
8550                        | Opcode::Push4
8551                        | Opcode::Push5
8552                        | Opcode::Push6
8553                        | Opcode::Push7
8554                        | Opcode::PushI8
8555                        | Opcode::PushI16
8556                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8557                        // -- stack shuffling ---------------------------------------------
8558                        Opcode::Drop => {
8559                            self.pop();
8560                        }
8561                        // -- arithmetic on two integers ----------------------------------
8562                        //
8563                        // The operands are *looked at* before they are popped, so a non-integer
8564                        // pair leaves the stack exactly as the slow path expects to find it.
8565                        Opcode::Add if self.numeric_pair() => {
8566                            let right = self.pop();
8567                            let left = self.pop();
8568                            // Exactly [`add_numbers`], which is what the slow arm reaches.
8569                            let answer = match (&left, &right) {
8570                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8571                                    Some(sum) => Value::Int(sum),
8572                                    None => Value::Float(*a as f64 + *b as f64),
8573                                },
8574                                _ => Value::Float(left.to_number() + right.to_number()),
8575                            };
8576                            self.push(answer);
8577                        }
8578                        Opcode::Sub
8579                        | Opcode::And
8580                        | Opcode::Or
8581                        | Opcode::Xor
8582                        | Opcode::Shl
8583                        | Opcode::Sar
8584                        | Opcode::Shr
8585                            if self.numeric_pair() =>
8586                        {
8587                            let right = self.pop();
8588                            let left = self.pop();
8589                            let answer =
8590                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
8591                            self.push(answer);
8592                        }
8593                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8594                            if self.numeric_pair() =>
8595                        {
8596                            let right = self.pop();
8597                            let left = self.pop();
8598                            let answer = self
8599                                .relational(insn.op, left, right)
8600                                .expect("numbers cannot throw");
8601                            self.push(answer);
8602                        }
8603                        // -- calls -------------------------------------------------------
8604                        //
8605                        // A plain call: `callee(arg0, …, argN) -> result`.
8606                        //
8607                        // This arm exists because of one measurement. `call:recursion` had
8608                        // **20.4% of its profile in `execute_instruction`** — the *slow*
8609                        // executor — and `fib`'s recursive call is the only thing in that
8610                        // function which is not a fast arm. Every call therefore left this
8611                        // loop via `stop()`, went through `step()`'s dispatch and
8612                        // `execute_instruction`'s match over every opcode, and came back here
8613                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8614                        //
8615                        // Two things make it safe to do here rather than only in the slow path:
8616                        //
8617                        // * the caller's `pc` is stored *before* the call, which is what
8618                        //   `step` does too — so when the callee returns, the caller resumes
8619                        //   after the call and not at it;
8620                        // * `check_memory` runs, because `step` calls it once per instruction
8621                        //   and a call allocates a frame, its locals and its cells. Skipping
8622                        //   the checkpoint here would let a `--memory-limit` script overshoot
8623                        //   by one call per instruction.
8624                        Opcode::Call
8625                        | Opcode::Call0
8626                        | Opcode::Call1
8627                        | Opcode::Call2
8628                        | Opcode::Call3 => {
8629                            let argc = self.argc_operand(insn.op, insn.a);
8630                            let next = pc + insn.width();
8631                            {
8632                                let frame = self
8633                                    .frames
8634                                    .last_mut()
8635                                    .expect("run_fast() is only called with a live frame");
8636                                // `at` is what a stack trace reports for this frame, so a throw
8637                                // inside the callee has to see the call site and not whatever
8638                                // the last `stop()` left there.
8639                                frame.at = insn.offset as usize;
8640                                frame.pc = next;
8641                            }
8642                            self.check_memory()?;
8643                            self.check_interrupt()?;
8644                            let args = self.pop_n(argc);
8645                            let callee = self.pop();
8646                            // A plain call has no receiver; the callee decides what to do with
8647                            // `undefined` (a sloppy function substitutes the global object).
8648                            if let Some(result) =
8649                                self.call_or_push(callee, Value::Undefined, args)?
8650                            {
8651                                // Native, host, generator, async, bound — no frame was pushed,
8652                                // so this loop is still describing the right function. `pc`
8653                                // is advanced by the loop tail like every other arm; only the
8654                                // frame's copy had to be written here, and it already was.
8655                                self.push(result);
8656                            } else {
8657                                // A bytecode callee: its frame is on top now, and `insns` and
8658                                // `pc` both belong to the caller. Start over on the new frame.
8659                                continue 'outer;
8660                            }
8661                        }
8662                        // -- return ------------------------------------------------------
8663                        Opcode::Return => {
8664                            let value = self.pop();
8665                            self.frame_mut().pc = pc + insn.width();
8666                            return Ok(Some(value));
8667                        }
8668                        Opcode::ReturnUndef => {
8669                            self.frame_mut().pc = pc + insn.width();
8670                            return Ok(Some(Value::Undefined));
8671                        }
8672                        // Everything else needs the slow path.
8673                        _ => return Ok(self.stop(pc)),
8674                    },
8675                }
8676                pc += insn.width();
8677            }
8678        }
8679    }
8680
8681    /// Whether the top two operand-stack values are both numbers.
8682    ///
8683    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8684    /// cannot run script, so the arm may not throw and may not change frames.
8685    fn numeric_pair(&self) -> bool {
8686        is_number(&self.peek(0)) && is_number(&self.peek(1))
8687    }
8688
8689    /// `a[i]` for a dense array and an integer index, without the string round trip.
8690    ///
8691    /// The slow path answers this by turning `i` into a string (`propkey` →
8692    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8693    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8694    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8695    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8696    /// without even the cheap `Int` formatting.
8697    ///
8698    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8699    /// unambiguously the one the slow path would give:
8700    ///
8701    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8702    ///   `2^32-1` is the length, not an index),
8703    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8704    ///   typed array or an ordinary object, all of which have their own rules),
8705    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8706    ///   starts walking the prototype chain, and `a[i]` on a hole must find
8707    ///   `Array.prototype[i]` if it exists rather than `undefined`.
8708    ///
8709    /// The last condition is the one that makes this safe rather than merely fast: an own
8710    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8711    /// `get_var` answered from the global-variable cache, or `None`.
8712    ///
8713    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8714    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8715    /// records nothing — the slow arm is about to walk the chain and record it.
8716    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8717        let frame = self.frame();
8718        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8719        // "Lexical" is presence in the realm's table, not the closure var's flag: a
8720        // `GlobalRef` forwarded through a nested function has its flags cleared.
8721        if self.realm.globals.contains_key(name) {
8722            return None;
8723        }
8724        if !self.scopes_are_plain() {
8725            return None;
8726        }
8727        let object = &self.realm.global;
8728        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8729        let cached = self.global_cache[site].as_ref()?;
8730        if !object.upgrades_to(&cached.object) {
8731            return None;
8732        }
8733        object.data_property_at(cached.index, name)
8734    }
8735
8736    /// `o.x` answered entirely from the inline cache, or `None`.
8737    ///
8738    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8739    /// about to do exactly that and recording it twice would rebuild the chain for every
8740    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8741    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8742    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8743        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8744        // an object receiver is a reference-count bump that the answer never needs.
8745        let frame = self.frame();
8746        let object = frame.stack.last()?;
8747        let Value::Object(target) = object else {
8748            return None;
8749        };
8750        // A proxy traps the lookup, so no cache entry ever describes it.
8751        if target.proxy_state().is_some() {
8752            return None;
8753        }
8754        let key = frame.code.atom_keys.get(atom)?;
8755        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8756        if cached.key != *key {
8757            return None;
8758        }
8759        Self::cached_hit(target, cached)
8760    }
8761
8762    fn fast_array_get(&self) -> Option<Value> {
8763        let Value::Int(index) = self.peek(0) else {
8764            return None;
8765        };
8766        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8767        // set for an `i32`.
8768        if index < 0 {
8769            return None;
8770        }
8771        let Value::Object(object) = self.peek(1) else {
8772            return None;
8773        };
8774        match object.array_get(index as usize) {
8775            Some(value) if !matches!(value, Value::Hole) => Some(value),
8776            _ => None,
8777        }
8778    }
8779
8780    /// `a[i] = v` on a dense array with an integer index, as one store.
8781    ///
8782    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8783    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8784    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8785    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8786    /// reference at the time it was measured (14.7x).
8787    ///
8788    /// Every condition here is one the slow path would also have to satisfy before
8789    /// storing into the element vector:
8790    ///
8791    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8792    ///   accepts as an index;
8793    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8794    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8795    ///   one inside a recorded descriptor, reports `false` and the caller stops.
8796    ///
8797    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8798    /// writes the own element too once `array_set` says it did.
8799    fn fast_array_set(&mut self) -> bool {
8800        // Every test runs *before* anything is popped: a refusal has to leave the stack
8801        // exactly as the slow path expects to find it. Popping first and reporting the
8802        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8803        // then ran the slow path with nothing to write.
8804        let Value::Int(index) = self.peek(1) else {
8805            return false;
8806        };
8807        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8808        if index < 0 {
8809            return false;
8810        }
8811        // Only a real array: a typed array's elements live in its buffer, a string-like
8812        // object has no element vector, and `array_set` on either does nothing.
8813        let Value::Object(object) = self.peek(2) else {
8814            return false;
8815        };
8816        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
8817            return false;
8818        }
8819        // A non-extensible array reports `false` here, but the *slow* path has to decide
8820        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
8821        // that with the key and the stack still intact.
8822        if !object.is_extensible() {
8823            return false;
8824        }
8825        // Inside the logical length, so the store cannot change `length`. Combined with
8826        // extensibility above, the only growth left for `array_set` is filling a hole in
8827        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
8828        // shape this fast path exists for. A store past the length would grow the array,
8829        // and whether that is allowed is the slow path's question.
8830        if index as usize >= object.array_length().unwrap_or(0) {
8831            return false;
8832        }
8833        // The bound `array_set` refuses past. Checking it here keeps that arm from having
8834        // to report a failure after the operands are gone.
8835        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
8836            return false;
8837        }
8838        let value = self.pop();
8839        self.pop();
8840        self.pop();
8841        object.array_store(self.heap, index as usize, value)
8842    }
8843
8844    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
8845    fn stop(&mut self, pc: usize) -> Option<Value> {
8846        self.frame_mut().pc = pc;
8847        None
8848    }
8849
8850    fn push(&mut self, value: Value) {
8851        self.frame_mut().stack.push(value);
8852    }
8853
8854    fn pop(&mut self) -> Value {
8855        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
8856    }
8857
8858    fn pop_n(&mut self, count: usize) -> Vec<Value> {
8859        let frame = self.frame_mut();
8860        let start = frame.stack.len().saturating_sub(count);
8861        frame.stack.split_off(start)
8862    }
8863
8864    fn peek(&self, back: usize) -> Value {
8865        let frame = self.frame();
8866        frame
8867            .stack
8868            .get(frame.stack.len().wrapping_sub(1 + back))
8869            .cloned()
8870            .unwrap_or(Value::Undefined)
8871    }
8872
8873    #[allow(clippy::too_many_lines)]
8874    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
8875        use Opcode::*;
8876        match op {
8877            // -- constants and stack shuffling -----------------------------
8878            Nop => {}
8879            PushMinus1 => self.push(Value::Int(-1)),
8880            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
8881                let value = match op {
8882                    Push0 => 0,
8883                    Push1 => 1,
8884                    Push2 => 2,
8885                    Push3 => 3,
8886                    Push4 => 4,
8887                    Push5 => 5,
8888                    Push6 => 6,
8889                    _ => 7,
8890                };
8891                self.push(Value::Int(value));
8892            }
8893            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
8894            PushBigintI32 => {
8895                // The immediate form of a `BigInt` literal; the reference has the same
8896                // split between this and a constant-pool entry.
8897                let value = crate::bigint::BigInt::from_i64(a as i64);
8898                self.push(self.bigint(value));
8899            }
8900            PushTrue => self.push(Value::Bool(true)),
8901            PushFalse => self.push(Value::Bool(false)),
8902            PushEmptyString => self.push(self.string("")),
8903            Undefined => self.push(Value::Undefined),
8904            Null => self.push(Value::Null),
8905            Object => {
8906                let proto = self.realm.object_proto.clone();
8907                self.push(Value::Object(self.new_object(Some(proto))));
8908            }
8909            PushThis => {
8910                let this = self.frame().this.clone();
8911                self.push(this);
8912            }
8913            PushConst | PushConst8 => {
8914                let value = self.constant(a as usize)?;
8915                self.push(value);
8916            }
8917            PushAtomValue => {
8918                let text = self.atom_wtf8(a as usize);
8919                self.push(self.string_wtf8(text));
8920            }
8921            Dup => {
8922                let value = self.peek(0);
8923                self.push(value);
8924            }
8925            Dup2 => {
8926                // `a b -> a b a b`
8927                let b = self.peek(0);
8928                let a = self.peek(1);
8929                self.push(a);
8930                self.push(b);
8931            }
8932            Dup3 => {
8933                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
8934                // prototype and key while reading the current value through them.
8935                let c = self.peek(0);
8936                let b = self.peek(1);
8937                let a = self.peek(2);
8938                self.push(a);
8939                self.push(b);
8940                self.push(c);
8941            }
8942            Swap => {
8943                // `a b -> b a`
8944                let bottom = self.pop();
8945                let top = self.pop();
8946                self.push(bottom);
8947                self.push(top);
8948            }
8949            Perm3 => {
8950                // `a b c -> b a c`, the reference's reordering for a spread method
8951                // call: `obj func array` becomes the `func this array` that `apply`
8952                // takes.
8953                let c = self.pop();
8954                let b = self.pop();
8955                let a = self.pop();
8956                self.push(b);
8957                self.push(a);
8958                self.push(c);
8959            }
8960            Dup1 => {
8961                let value = self.peek(1);
8962                self.push(value);
8963            }
8964            Drop => {
8965                self.pop();
8966            }
8967            Nip => {
8968                // `a b -> b`
8969                let top = self.pop();
8970                self.pop();
8971                self.push(top);
8972            }
8973            Perm4 => {
8974                // `obj prop a b -> a obj prop b`, the reference's reordering for a
8975                // postfix update of a computed element: it puts the *old* value
8976                // underneath the receiver and key so `put_array_el` can consume them
8977                // and leave the old value as the expression's result.
8978                let d = self.pop();
8979                let c = self.pop();
8980                let b = self.pop();
8981                let a = self.pop();
8982                self.push(c);
8983                self.push(a);
8984                self.push(b);
8985                self.push(d);
8986            }
8987            Insert2 => {
8988                // `obj a -> a obj a`
8989                let value = self.pop();
8990                let object = self.pop();
8991                self.push(value.clone());
8992                self.push(object);
8993                self.push(value);
8994            }
8995            Insert3 => {
8996                // `obj prop a -> a obj prop a`
8997                let value = self.pop();
8998                let key = self.pop();
8999                let object = self.pop();
9000                self.push(value.clone());
9001                self.push(object);
9002                self.push(key);
9003                self.push(value);
9004            }
9005            Insert4 => {
9006                // `this obj prop a -> a this obj prop a`
9007                //
9008                // `put_super_value` consumes all four and yields nothing, so the copy
9009                // underneath is what leaves the assignment an expression value.
9010                let value = self.pop();
9011                let key = self.pop();
9012                let object = self.pop();
9013                let receiver = self.pop();
9014                self.push(value.clone());
9015                self.push(receiver);
9016                self.push(object);
9017                self.push(key);
9018                self.push(value);
9019            }
9020            Swap2 => {
9021                // `a b c d -> c d a b`
9022                let d = self.pop();
9023                let c = self.pop();
9024                let b = self.pop();
9025                let a = self.pop();
9026                self.push(c);
9027                self.push(d);
9028                self.push(a);
9029                self.push(b);
9030            }
9031            Rot3l => {
9032                // `x a b -> a b x`
9033                let b = self.pop();
9034                let a = self.pop();
9035                let x = self.pop();
9036                self.push(a);
9037                self.push(b);
9038                self.push(x);
9039            }
9040            Rot3r => {
9041                // `a b c -> c a b`
9042                let c = self.pop();
9043                let b = self.pop();
9044                let a_value = self.pop();
9045                self.push(c);
9046                self.push(a_value);
9047                self.push(b);
9048            }
9049
9050            Rest => {
9051                // `...rest` in a parameter list: the arguments from index `a` on, as a
9052                // real array. It takes nothing off the stack — the arguments are in the
9053                // frame, not on it.
9054                let frame = self.frame();
9055                let from = a as usize;
9056                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9057                let array = self.new_array(collected);
9058                self.push(Value::Object(array));
9059            }
9060
9061            // -- slots ------------------------------------------------------
9062            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9063                let slot = self.slot_operand(op, a);
9064                let value = self.get_loc(slot);
9065                self.push(value);
9066            }
9067            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9068                let slot = self.slot_operand(op, a);
9069                let value = self.pop();
9070                self.put_loc(slot, value);
9071            }
9072            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9073                let slot = self.slot_operand(op, a);
9074                let value = self.pop();
9075                self.put_loc(slot, value.clone());
9076                self.push(value);
9077            }
9078            // The `_check` forms are the temporal dead zone: they throw when the
9079            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9080            // *reads*, so only the two writes may pop — mishandling that quietly
9081            // consumes the value the caller pushed just before.
9082            GetLocCheck => {
9083                let slot = self.slot_operand(op, a);
9084                let value = self.get_loc(slot);
9085                if matches!(value, Value::Uninitialized) {
9086                    return Err(self.dead_zone(slot, VarSlot::Loc));
9087                }
9088                self.push(value);
9089            }
9090            PutLocCheck | SetLocCheck => {
9091                let slot = self.slot_operand(op, a);
9092                let value = self.pop();
9093                if matches!(value, Value::Uninitialized) {
9094                    return Err(self.dead_zone(slot, VarSlot::Loc));
9095                }
9096                // The initialiser goes through `put_loc`, not this, so any store that
9097                // reaches here is a later assignment — which a `const` refuses.
9098                if self.is_read_only(slot, VarSlot::Loc) {
9099                    return Err(self.read_only(slot, VarSlot::Loc));
9100                }
9101                if op == SetLocCheck {
9102                    self.put_loc(slot, value.clone());
9103                    self.push(value);
9104                } else {
9105                    self.put_loc(slot, value);
9106                }
9107            }
9108            PutLocCheckInit => {
9109                // The one store that *initialises* a lexical slot: `this` in a derived
9110                // constructor, which only exists after `super()` has run. A second
9111                // initialisation is the error the reference reports as
9112                // "'this' can be initialized only once".
9113                let slot = self.slot_operand(op, a);
9114                let value = self.pop();
9115                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9116                    return Err(Signal::Throw(self.make_error(
9117                        "ReferenceError",
9118                        "'this' can be initialized only once",
9119                    )));
9120                }
9121                self.put_loc(slot, value);
9122            }
9123            CheckCtor => {
9124                // A class constructor may only run under `new`, which is what makes
9125                // `class A {}; A()` a TypeError.
9126                if matches!(self.frame().new_target, Value::Undefined) {
9127                    return Err(Signal::Throw(self.make_error(
9128                        "TypeError",
9129                        "class constructors must be invoked with 'new'",
9130                    )));
9131                }
9132            }
9133            InitCtor => {
9134                // The body a derived class gets when it declares no constructor:
9135                // forward every argument to the parent constructor, keeping `new.target`.
9136                if matches!(self.frame().new_target, Value::Undefined) {
9137                    return Err(Signal::Throw(self.make_error(
9138                        "TypeError",
9139                        "class constructors must be invoked with 'new'",
9140                    )));
9141                }
9142                let Some(callee) = self.current_callee() else {
9143                    return Err(Signal::Throw(
9144                        self.make_error("TypeError", "no constructor to inherit from"),
9145                    ));
9146                };
9147                let parent = callee.proto().map_or(Value::Null, Value::Object);
9148                let new_target = self.frame().new_target.clone();
9149                let args = self.frame().passed().to_vec();
9150                let result = self.construct(parent, new_target, args)?;
9151                self.push(result);
9152            }
9153            SetLocUninitialized => {
9154                let slot = self.slot_operand(op, a);
9155                self.put_loc(slot, Value::Uninitialized);
9156            }
9157            CloseLoc => {
9158                // "Close" a binding: give it a *fresh* cell holding the current
9159                // value. Closures created before this point keep the old cell and the
9160                // ones created after see the new one, which is what makes every
9161                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9162                // a block-scoped binding when the block ends.
9163                //
9164                // Clearing the slot instead (which this used to do) broke both: a
9165                // closure over a captured block variable read `undefined`, and a loop
9166                // terminated after one iteration.
9167                let slot = self.slot_operand(op, a);
9168                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9169                if index >= 0 {
9170                    let current = self.frame().cells[index as usize].get();
9171                    let fresh = self.new_cell(current);
9172                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9173                        *cell = fresh;
9174                    }
9175                }
9176            }
9177            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9178                let slot = self.slot_operand(op, a);
9179                let value = self.get_arg(slot);
9180                self.push(value);
9181            }
9182            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9183                let slot = self.slot_operand(op, a);
9184                let value = self.pop();
9185                self.put_arg(slot, value);
9186            }
9187            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9188                let slot = self.slot_operand(op, a);
9189                let value = self.pop();
9190                self.put_arg(slot, value.clone());
9191                self.push(value);
9192            }
9193
9194            // -- closure variables ------------------------------------------
9195            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9196                let slot = self.slot_operand(op, a);
9197                // A name a direct `eval` created shadows the binding the compiler chose.
9198                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9199                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9200                // and only a runtime lookup can know that.
9201                if let Some(cell) = self.eval_created_local(slot) {
9202                    self.push(cell.get());
9203                    return self.step();
9204                }
9205                let value = self.cell_value(slot)?;
9206                self.push(value);
9207            }
9208            GetVarRefCheck => {
9209                let slot = self.slot_operand(op, a);
9210                let value = self.cell_value(slot)?;
9211                if matches!(value, Value::Uninitialized) {
9212                    return Err(self.dead_zone(slot, VarSlot::Closure));
9213                }
9214                self.push(value);
9215            }
9216            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9217                let slot = self.slot_operand(op, a);
9218                let value = self.pop();
9219                if let Some(cell) = self.eval_created_local(slot) {
9220                    cell.set(value);
9221                    return self.step();
9222                }
9223                // Same rule as `PutLocCheck`: a checked store to a captured binding
9224                // refuses a `const` once its initialiser has run.
9225                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9226                    return Err(self.read_only(slot, VarSlot::Closure));
9227                }
9228                self.set_cell(slot, value)?;
9229            }
9230            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9231                let slot = self.slot_operand(op, a);
9232                let value = self.pop();
9233                if let Some(cell) = self.eval_created_local(slot) {
9234                    cell.set(value.clone());
9235                    self.push(value);
9236                    return self.step();
9237                }
9238                self.set_cell(slot, value.clone())?;
9239                self.push(value);
9240            }
9241
9242            // -- globals ----------------------------------------------------
9243            GetVar => {
9244                let value = self.get_global(a as usize)?;
9245                self.push(value);
9246            }
9247            GetVarUndef => {
9248                let value = self
9249                    .get_global(a as usize)
9250                    .or_else(|_| Ok(Value::Undefined))?;
9251                self.push(value);
9252            }
9253            DeleteVar => {
9254                // `delete name` for a name that is not a declared binding. A lexical
9255                // global lives in the reference table and cannot be deleted; anything
9256                // reachable only as a property of the global object is *implicit* —
9257                // `x = 1` with no declaration — and goes away if it is configurable,
9258                // which is what `delete` on an implicit global answers.
9259                let name = self.atom_text(a as usize);
9260                let global = self.realm.global.clone();
9261                let deleted = if self.realm.globals.contains_key(&name) {
9262                    false
9263                } else if global.own_property(&name).is_some() {
9264                    self.delete_property(&global, &name)?
9265                } else {
9266                    true
9267                };
9268                self.push(Value::Bool(deleted));
9269            }
9270            PutVar => {
9271                let value = self.pop();
9272                self.put_global(a as usize, value)?;
9273            }
9274            PutVarInit => {
9275                let slot = a as usize;
9276                let value = self.pop();
9277                self.init_global(slot, value)?;
9278            }
9279
9280            // -- arithmetic -------------------------------------------------
9281            Add => self.binary_add()?,
9282            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9283                let raw_right = self.pop();
9284                let raw_left = self.pop();
9285                // BigInt arithmetic is a separate path, and not only for the type of the
9286                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9287                // rather than a silent conversion.
9288                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9289                    let left = self.primitive_of(raw_left)?;
9290                    let right = self.primitive_of(raw_right)?;
9291                    let value = self.bigint_arithmetic(op, left, right)?;
9292                    self.push(value);
9293                } else {
9294                    let right = self.numeric(raw_right)?;
9295                    let left = self.numeric(raw_left)?;
9296                    self.push(arithmetic(op, left, right)?);
9297                }
9298            }
9299            Neg => {
9300                let raw = self.pop();
9301                match raw {
9302                    // A bigint negates exactly, however wide it is.
9303                    Value::BigInt(big) => {
9304                        let negated = big.negate();
9305                        self.push(self.bigint(negated));
9306                    }
9307                    other => {
9308                        let value = self.numeric(other)?;
9309                        self.push(negate(value));
9310                    }
9311                }
9312            }
9313            Plus => {
9314                let value = self.pop();
9315                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9316                // unary plus is defined to produce a *number*, which a bigint cannot
9317                // become without loss. It used to fall through to `NaN`.
9318                if matches!(value, Value::BigInt(_)) {
9319                    return Err(self.type_error("cannot convert bigint to number"));
9320                }
9321                let numeric = self.numeric_of(value)?;
9322                self.push(numeric);
9323            }
9324            Inc => {
9325                let raw = self.pop();
9326                let (_, updated) = self.advance_numeric(raw, true)?;
9327                self.push(updated);
9328            }
9329            Dec => {
9330                let raw = self.pop();
9331                let (_, updated) = self.advance_numeric(raw, false)?;
9332                self.push(updated);
9333            }
9334            PostInc | PostDec => {
9335                // `x -> x x+1`: the *new* value ends up on top, so the store the
9336                // compiler emits right after (`put_var`) writes the incremented
9337                // one, while the old value stays underneath for the expression's
9338                // own result. Getting this backwards makes `i++` a no-op, which
9339                // turns `while (i < 3)` into an infinite loop.
9340                let raw = self.pop();
9341                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9342                self.push(old);
9343                self.push(updated);
9344            }
9345            Not => {
9346                let raw = self.pop();
9347                match raw {
9348                    // `~x` on a bigint is `-x - 1`, exact at any width.
9349                    Value::BigInt(big) => {
9350                        let inverted = big.bitnot();
9351                        self.push(self.bigint(inverted));
9352                    }
9353                    other => {
9354                        let value = self.numeric(other)?;
9355                        self.push(Value::Int(!value.to_int32()));
9356                    }
9357                }
9358            }
9359            Lnot => {
9360                let value = self.pop();
9361                self.push(Value::Bool(!value.to_boolean()));
9362            }
9363
9364            // -- comparison -------------------------------------------------
9365            Lt | Lte | Gt | Gte => {
9366                let right = self.pop();
9367                let left = self.pop();
9368                let answer = self.relational(op, left, right)?;
9369                self.push(answer);
9370            }
9371            Eq | Neq => {
9372                let right = self.pop();
9373                let left = self.pop();
9374                let equal = self.abstract_equals(left, right)?;
9375                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9376            }
9377            StrictEq => {
9378                let right = self.pop();
9379                let left = self.pop();
9380                self.push(Value::Bool(left.strict_equals(&right)));
9381            }
9382            StrictNeq => {
9383                let right = self.pop();
9384                let left = self.pop();
9385                self.push(Value::Bool(!left.strict_equals(&right)));
9386            }
9387            IsUndefined => {
9388                // `=== undefined`, which is what a destructuring default tests. It is
9389                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9390                let value = self.pop();
9391                self.push(Value::Bool(matches!(value, Value::Undefined)));
9392            }
9393            IsUndefinedOrNull => {
9394                let value = self.pop();
9395                self.push(Value::Bool(value.is_nullish()));
9396            }
9397            Typeof => {
9398                let value = self.pop();
9399                self.push(self.string(value.type_of()));
9400            }
9401            ToObject => {
9402                // A destructuring *object* pattern starts here, which is why
9403                // `var {} = null` throws. Only `undefined` and `null` are refused; a
9404                // primitive is boxed.
9405                let value = self.pop();
9406                let object = self.object_from(&value)?;
9407                self.push(Value::Object(object));
9408            }
9409            Instanceof => {
9410                let constructor = self.pop();
9411                let object = self.pop();
9412                let answer = self.instance_of(&object, &constructor)?;
9413                self.push(Value::Bool(answer));
9414            }
9415            In => {
9416                let object = self.pop();
9417                let key = self.pop();
9418                let answer = self.has_property(&key, &object)?;
9419                self.push(Value::Bool(answer));
9420            }
9421
9422            // -- control flow -----------------------------------------------
9423            Goto | Goto8 | Goto16 => {
9424                self.frame_mut().pc = a as usize;
9425            }
9426            IfTrue | IfTrue8 => {
9427                let value = self.pop();
9428                if value.to_boolean() {
9429                    self.frame_mut().pc = a as usize;
9430                }
9431            }
9432            IfFalse | IfFalse8 => {
9433                let value = self.pop();
9434                if !value.to_boolean() {
9435                    self.frame_mut().pc = a as usize;
9436                }
9437            }
9438            Catch => {
9439                // Pushes the handler target onto the value stack; `unwind` finds it.
9440                self.push(Value::CatchOffset(a));
9441            }
9442            Gosub => {
9443                self.push(Value::ReturnAddress(next as u32));
9444                self.frame_mut().pc = a as usize;
9445            }
9446            Ret => {
9447                let value = self.pop();
9448                match value {
9449                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9450                    _ => {
9451                        return Err(Signal::Throw(
9452                            self.make_error("InternalError", "invalid return address"),
9453                        ));
9454                    }
9455                }
9456            }
9457            NipCatch => {
9458                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9459                // including the marker, keeping the top value.
9460                let top = self.pop();
9461                loop {
9462                    match self.pop() {
9463                        Value::CatchOffset(_) | Value::Undefined => break,
9464                        _ => {}
9465                    }
9466                    if self.frame().stack.is_empty() {
9467                        break;
9468                    }
9469                }
9470                self.push(top);
9471            }
9472            Throw => {
9473                let value = self.pop();
9474                return Err(Signal::Throw(value));
9475            }
9476            ThrowError => {
9477                let name = self.atom_text(a as usize);
9478                let (class, message) = match b {
9479                    0 => ("TypeError", format!("'{name}' is read-only")),
9480                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9481                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
9482                    // `delete super.x` is a syntax-level mistake the reference reports
9483                    // with this wording, not a property-access failure.
9484                    3 => (
9485                        "ReferenceError",
9486                        "unsupported reference to 'super'".to_string(),
9487                    ),
9488                    4 => (
9489                        "TypeError",
9490                        "iterator does not have a throw method".to_string(),
9491                    ),
9492                    5 => (
9493                        "ReferenceError",
9494                        "invalid assignment left-hand side".to_string(),
9495                    ),
9496                    _ => ("TypeError", format!("invalid operation on '{name}'")),
9497                };
9498                return Err(Signal::Throw(self.make_error(class, &message)));
9499            }
9500            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9501            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9502            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9503            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9504            Await => return Ok(Step::Suspend(SuspendKind::Await)),
9505            ReturnAsync => {
9506                // The reference's `return_async` returns `undefined` and lets the resume
9507                // machinery pick the real value off `sp[-1]`, which is how it tells a
9508                // completion from a suspension. Carrying the value explicitly says the
9509                // same thing without the implicit stack slot.
9510                let value = self.pop();
9511                return Ok(Step::Return(value));
9512            }
9513            Return => {
9514                let value = self.pop();
9515                return Ok(Step::Return(value));
9516            }
9517            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9518
9519            // -- calls ------------------------------------------------------
9520            Call | Call0 | Call1 | Call2 | Call3 => {
9521                let argc = self.argc_operand(op, a);
9522                let args = self.pop_n(argc);
9523                let callee = self.pop();
9524                // A plain call has no receiver; the callee decides what to do with
9525                // `undefined` (a sloppy function substitutes the global object).
9526                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9527                    self.push(result);
9528                }
9529            }
9530            CallConstructor => {
9531                // `constructor this_obj args… -> object`. The duplicated
9532                // constructor is `new.target`; this milestone does not expose it,
9533                // so the extra copy is simply consumed here.
9534                let argc = a as usize;
9535                let args = self.pop_n(argc);
9536                let new_target = self.pop();
9537                let callee = self.pop();
9538                let result = self.construct(callee, new_target, args)?;
9539                self.push(result);
9540            }
9541            CallMethod => {
9542                let argc = a as usize;
9543                let args = self.pop_n(argc);
9544                let callee = self.pop();
9545                let this = self.pop();
9546                if let Some(result) = self.call_or_push(callee, this, args)? {
9547                    self.push(result);
9548                }
9549            }
9550            Apply => {
9551                // `func this array -> result`, the spread-call form: the compiler
9552                // builds one array of arguments, and all that is left here is to
9553                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9554                let array = self.pop();
9555                let this = self.pop();
9556                let callee = self.pop();
9557                let args = self.array_like_to_args(&array)?;
9558                if a & 1 != 0 {
9559                    let result = self.construct(callee, this, args)?;
9560                    self.push(result);
9561                } else if let Some(result) = self.call_or_push(callee, this, args)? {
9562                    self.push(result);
9563                }
9564            }
9565            TailCall | TailCallMethod => {
9566                // `tail_call` is `call` whose result is returned immediately — the
9567                // reference jumps straight to `done` instead of storing the value and
9568                // running on. The callee still gets its own frame, so deep tail
9569                // recursion hits the stack limit exactly like plain recursion does;
9570                // marking this frame lets the return path unwind without needing
9571                // instructions after the call.
9572                let argc = if op == TailCallMethod {
9573                    a as usize
9574                } else {
9575                    self.argc_operand(op, a)
9576                };
9577                let args = self.pop_n(argc);
9578                let callee = self.pop();
9579                let this = if op == TailCallMethod {
9580                    self.pop()
9581                } else {
9582                    Value::Undefined
9583                };
9584                if let Value::Object(function) = &callee
9585                    && let Some((code, env)) = bytecode_of(function)
9586                {
9587                    // A generator or async body is not run here at all: calling it only
9588                    // *creates* the generator/coroutine, so it must not inherit this
9589                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
9590                    // onto `f`'s frame, and the first `yield`/`await` then reported
9591                    // "a generator body ran as an ordinary call".
9592                    if code.code.kind.is_generator() || code.code.kind.is_async() {
9593                        let value = self.call_value(callee, this, args)?;
9594                        return Ok(Step::Return(value));
9595                    }
9596                    self.frame_mut().tail = true;
9597                    self.push_frame(code, env, this, args, callee)?;
9598                    return Ok(Step::Continue);
9599                }
9600                // A native callee has no frame to reuse, so its value is simply
9601                // returned.
9602                let value = self.call_value(callee, this, args)?;
9603                return Ok(Step::Return(value));
9604            }
9605
9606            // -- objects ----------------------------------------------------
9607            SpecialObject => {
9608                let value = self.special_object(a)?;
9609                self.push(value);
9610            }
9611            PrivateSymbol => {
9612                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9613                // symbol each time it is evaluated, which is why the compiler evaluates it
9614                // once (at class definition) and stores it in a class-scope binding.
9615                let name = self.atom_text(a as usize);
9616                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9617                self.push(Value::Symbol(symbol));
9618            }
9619            GetPrivateField => {
9620                // `obj symbol -> value`. A missing private field is a TypeError, which is what
9621                // makes `#x` inaccessible on any object not built by this class.
9622                let symbol = self.pop();
9623                let object = self.pop();
9624                let value = self.read_private_field(&object, &symbol)?;
9625                self.push(value);
9626            }
9627            PutPrivateField => {
9628                // `obj value symbol ->`, and the store is a plain assignment to a property the
9629                // class already created, so there is no setter to consult.
9630                let symbol = self.pop();
9631                let value = self.pop();
9632                let object = self.pop();
9633                self.write_private_field(&object, &symbol, value)?;
9634            }
9635            DefinePrivateField => {
9636                // `obj symbol value -> obj`: a field initialiser creates the property, and
9637                // redefining one is a TypeError ("already exists").
9638                let value = self.pop();
9639                let symbol = self.pop();
9640                let object = self.pop();
9641                self.define_private_field(&object, &symbol, value)?;
9642                self.push(object);
9643            }
9644            PrivateIn => {
9645                // `obj key -> bool`: `#x in o`. The second operand decides which question is
9646                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9647                // is a field, so this is an own-property test; a *function* is a method or
9648                // accessor, so this is a brand check.
9649                let key = self.pop();
9650                let object = self.pop();
9651                let Some(target) = object.as_object() else {
9652                    return Err(Signal::Throw(
9653                        self.make_error("TypeError", "invalid 'in' operand"),
9654                    ));
9655                };
9656                let present = match &key {
9657                    Value::Object(_) => self.check_brand(target, &key)?,
9658                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9659                };
9660                self.push(Value::Bool(present));
9661            }
9662            AddBrand => {
9663                // `obj home ->`: create the class brand on `home` if it has none, then give
9664                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9665                // class definition: only the prototype's copy of the symbol is wanted.
9666                let home = self.pop();
9667                let object = self.pop();
9668                self.add_brand(&object, &home)?;
9669            }
9670            CheckBrand => {
9671                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9672                // Both stay, because the caller needs them — `nip` halves a read into its
9673                // value and `call_method` uses the pair as receiver and callee.
9674                let function = self.peek(0);
9675                let object = self.peek(1);
9676                let Some(target) = object.as_object() else {
9677                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9678                };
9679                if !self.check_brand(target, &function)? {
9680                    return Err(Signal::Throw(
9681                        self.make_error("TypeError", "invalid brand on object"),
9682                    ));
9683                }
9684            }
9685            GetLength => {
9686                // `get_length` is the `.length` read; an array and a string answer
9687                // from their own length, anything else from the property.
9688                let target = self.pop();
9689                let value = match &target {
9690                    Value::Object(object) => match object.array_length() {
9691                        Some(length) => crate::object::length_value(length),
9692                        None => self.read_field(&target, "length")?,
9693                    },
9694                    Value::String(text) => Value::Int(text.utf16_len() as i32),
9695                    _ => self.read_field(&target, "length")?,
9696                };
9697                self.push(value);
9698            }
9699            GetField | GetField2 => {
9700                let object = self.pop();
9701                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9702                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9703                // just below is what lets the borrow outlive the `&mut self` the lookup
9704                // needs — one refcount bump instead of a key clone plus its drop, on the
9705                // hottest property path there is: every `o.x` and every `o.m()` receiver.
9706                let code = self.frame().code.clone();
9707                let key = &code.atom_keys[a as usize];
9708                let value = self.read_field_cached(&object, key, next)?;
9709                if op == GetField2 {
9710                    self.push(object);
9711                }
9712                self.push(value);
9713            }
9714            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9715                let key = self.pop();
9716                let object = self.pop();
9717                let key = self.propkey(&key)?;
9718                let value = self.read_field_key(&object, &key)?;
9719                if matches!(op, GetArrayEl2 | GetArrayEl3) {
9720                    self.push(object);
9721                }
9722                if op == GetArrayEl3 {
9723                    // The key goes back in its *value* form, which the compiler stores
9724                    // into the target of a destructuring assignment.
9725                    self.push(match &key {
9726                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9727                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
9728                    });
9729                }
9730                self.push(value);
9731            }
9732            PutField => {
9733                let value = self.pop();
9734                let object = self.pop();
9735                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9736                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9737                // only reads. `this.value = …` is the write half of the hottest loop in
9738                // `property:method-call`, and `own_property_key` was 4.8% of the case.
9739                let code = self.frame().code.clone();
9740                let key = &code.atom_keys[a as usize];
9741                self.write_field_key(&object, key, value)?;
9742            }
9743            PutArrayEl => {
9744                let value = self.pop();
9745                let key = self.pop();
9746                let object = self.pop();
9747                let key = self.propkey(&key)?;
9748                self.write_field_key(&object, &key, value)?;
9749            }
9750            DefineField => {
9751                let value = self.pop();
9752                let object = self.pop();
9753                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9754                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9755                // three U+FFFD — a property under a different name from the one
9756                // `o["\uD800"]` reads.
9757                let code = self.frame().code.clone();
9758                let key = code.atom_keys[a as usize].clone();
9759                // No naming here. `{m: function(){}}` is named by the *compiler*, which
9760                // emits `set_name` — and only where `NamedEvaluation` applies, so
9761                // `{m: (0, function(){})}` stays anonymous. Naming every function that
9762                // reaches a property definition got that case wrong, and the compiler is
9763                // the only place that can tell the two apart.
9764                if let Some(target) = object.as_object() {
9765                    // Only an *array* stores into the element vector. A numeric key
9766                    // on an ordinary object is an ordinary property, which is what
9767                    // makes `{1: 'a'}` iterate as a key rather than disappear.
9768                    let stored = target.is_array()
9769                        && key.as_str().and_then(array_index).is_some_and(|index| {
9770                            target.array_set(self.heap, index as usize, value.clone())
9771                        });
9772                    if !stored {
9773                        target.define_data_key(&key, value);
9774                    }
9775                }
9776                self.push(object);
9777            }
9778            DefineArrayEl => {
9779                // `obj key value -> obj key`. The *value* form of the key is what goes
9780                // back on the stack — the compiler stores it into the pattern's binding —
9781                // so the symbol is not stringified on the way through.
9782                let value = self.pop();
9783                let key_value = self.pop();
9784                let object = self.peek(0);
9785                let key = self.propkey(&key_value)?;
9786                self.write_field_key(&object, &key, value)?;
9787                self.push(key_value);
9788            }
9789            SetHomeObject => {
9790                // `obj func -> obj func`: records the object a method was defined on so
9791                // `super` inside it resolves against that object's prototype.
9792                let function = self.peek(0);
9793                let home = self.peek(1);
9794                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9795                    function.set_home_object(Some(home.clone()));
9796                }
9797            }
9798            Regexp => {
9799                // `pattern flags -> regexp`. A literal compiles here rather than through the
9800                // constructor, which is both what the reference's dedicated opcode is for
9801                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9802                let flags = self.pop();
9803                let pattern = self.pop();
9804                let pattern = self.to_js_string(&pattern)?;
9805                let flags = self.to_js_string(&flags)?;
9806                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9807                self.push(Value::Object(object));
9808            }
9809            UsingDisposeInit => {
9810                // The error state a disposal accumulates into. Uninitialised means "no
9811                // failure yet"; anything else is the exception being propagated.
9812                self.push(Value::Uninitialized);
9813            }
9814            UsingCheck => {
9815                // `value -> value, method`: validate and snapshot the disposer now, so a
9816                // later change to `Symbol.dispose` cannot change what gets called, and so a
9817                // value that is not disposable fails before the body runs.
9818                let value = self.pop();
9819                let method = self.using_method_for(&value, a as u8 == 1)?;
9820                self.push(value);
9821                self.push(method);
9822            }
9823            UsingDispose => {
9824                // `error_state -> error_state'`: dispose the variable at `slot` — its value
9825                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
9826                // the pending error.
9827                let slot = self.slot_operand(op, a);
9828                let error_state = self.pop();
9829                let merged = self.using_dispose_once(slot, error_state)?;
9830                self.push(merged);
9831            }
9832            UsingDisposeMerge => {
9833                let new_error = self.pop();
9834                let error_state = self.pop();
9835                let merged = self.merge_dispose_error(new_error, error_state);
9836                self.push(merged);
9837            }
9838            UsingDisposeEnd => {
9839                // A disposal that failed replaces the block's normal completion, so the
9840                // error state becomes a real throw here rather than at the call site.
9841                let error_state = self.pop();
9842                if !matches!(error_state, Value::Uninitialized) {
9843                    return Err(Signal::Throw(error_state));
9844                }
9845            }
9846            UsingDisposeAsync => {
9847                // `await using` needs a promise to await and this runtime has no
9848                // `Promise` builtin, so the disposer is called synchronously and its result
9849                // discarded. That is correct for a disposer that returns nothing and is
9850                // reported as a gap rather than silently skipped.
9851                let slot = self.slot_operand(op, a);
9852                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
9853                self.push(error_state);
9854            }
9855            GetSuper => {
9856                // `obj -> obj's prototype`: the starting point of a `super` lookup.
9857                let object = self.pop();
9858                let proto = match &object {
9859                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
9860                    _ => Value::Null,
9861                };
9862                self.push(proto);
9863            }
9864            GetSuperValue => {
9865                // `receiver proto key -> value`, searching from `proto` but reporting to
9866                // `receiver`, which is what `super.g` must do for a getter to see `this`.
9867                //
9868                // Three values in, one out: the receiver is *consumed*, not left under the
9869                // result. Leaving it there was invisible for `super.x` in `return` or
9870                // statement position (the result is what gets popped) and corrupted the
9871                // frame everywhere else — `print(super.x)` left the class where the call
9872                // opcode looks for the receiver and called the class itself.
9873                let key = self.pop();
9874                let proto = self.pop();
9875                let receiver = self.pop();
9876                let value = self.super_read(&receiver, &proto, &key)?;
9877                self.push(value);
9878            }
9879            PutSuperValue => {
9880                // `receiver proto key value ->`: a store that starts at `proto` but
9881                // assigns to `receiver`.
9882                let value = self.pop();
9883                let key = self.pop();
9884                let proto = self.pop();
9885                let receiver = self.pop();
9886                self.super_write(&receiver, &proto, &key, value)?;
9887            }
9888            DefineClass => {
9889                // `parent ctor -> ctor proto`: the constructor becomes the class and a
9890                // fresh prototype object lands on top for the methods to go on.
9891                let name = self.atom_text(a as usize);
9892                let (ctor, proto) = self.define_class(&name, b)?;
9893                self.push(ctor);
9894                self.push(Value::Object(proto));
9895            }
9896            DefineClassComputed => {
9897                // `parent ctor key -> ctor proto key`: the computed name stays put so
9898                // `define_field`-style consumers can still read it.
9899                let key = self.pop();
9900                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9901                let (ctor, proto) = self.define_class(&name, b)?;
9902                self.push(ctor);
9903                self.push(Value::Object(proto));
9904                self.push(key);
9905            }
9906            DefineMethod => {
9907                let function = self.pop();
9908                let object = self.pop();
9909                // The exact key, like `define_field`: a quoted method key may hold an
9910                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
9911                // that `o["\uD800"]` finds.
9912                let code = self.frame().code.clone();
9913                let key = code.atom_keys[a as usize].clone();
9914                // A method's `[[HomeObject]]` is the object it was defined on, which is
9915                // what `super` inside it resolves against.
9916                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9917                    function.set_home_object(Some(object.clone()));
9918                }
9919                if let Some(text) = key.as_wtf8() {
9920                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
9921                } else {
9922                    self.set_function_name(
9923                        &function,
9924                        &key_with_accessor_prefix(&key.to_string(), b),
9925                    );
9926                }
9927                if let Some(array) = object.as_object() {
9928                    define_function_property(array, &key, function, b);
9929                }
9930                self.push(object);
9931            }
9932            DefineMethodComputed => {
9933                let function = self.pop();
9934                let key = self.pop();
9935                let object = self.pop();
9936                let key = self.propkey(&key)?;
9937                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
9938                // the name: `super` inside a computed method resolves through it. Without
9939                // this, `class B extends A { [k]() { return super.m() } }` read the
9940                // home object as null and threw.
9941                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9942                    function.set_home_object(Some(object.clone()));
9943                }
9944                match key.as_wtf8() {
9945                    Some(text) => {
9946                        let name = accessor_prefixed(text, a);
9947                        self.set_function_name_wtf8(&function, &name);
9948                    }
9949                    None => self.set_function_name(
9950                        &function,
9951                        &key_with_accessor_prefix(&key.to_string(), a),
9952                    ),
9953                }
9954                if let Some(array) = object.as_object() {
9955                    define_function_property(array, &key, function, a);
9956                }
9957                self.push(object);
9958            }
9959            SetProto => {
9960                let proto = self.pop();
9961                let object = self.pop();
9962                if let Some(target) = object.as_object() {
9963                    target.set_proto(proto.as_object().cloned());
9964                }
9965                self.push(object);
9966            }
9967            CopyDataProperties => {
9968                let exclusion = self.pop();
9969                let source = self.pop();
9970                let target = self.peek(0);
9971                self.copy_properties(&target, &source, &exclusion)?;
9972                self.push(source);
9973                self.push(exclusion);
9974            }
9975            ToPropkey => {
9976                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
9977                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
9978                // ordinary `"Symbol(b)"` property.
9979                let value = self.pop();
9980                let key = match self.propkey(&value)? {
9981                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
9982                    PropertyKey::String(text) => self.string_wtf8(text),
9983                };
9984                self.push(key);
9985            }
9986            SetName => {
9987                let function = self.peek(0);
9988                let name = self.atom_wtf8(a as usize);
9989                self.set_function_name_wtf8(&function, &name);
9990            }
9991            SetNameComputed => {
9992                let key = self.peek(1);
9993                let function = self.peek(0);
9994                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9995                self.set_function_name(&function, &name);
9996            }
9997
9998            // -- arrays -----------------------------------------------------
9999            ArrayFrom => {
10000                let count = a as usize;
10001                let elements = self.pop_n(count);
10002                let array = self.new_array(elements);
10003                self.push(Value::Object(array));
10004            }
10005            Append => {
10006                // `array index iterable -> array new_index`
10007                let iterable = self.pop();
10008                self.pop();
10009                let array = self.peek(0);
10010                let added = self.append_enumerate(&array, &iterable)?;
10011                self.push(Value::Int(added));
10012            }
10013
10014            // -- iteration --------------------------------------------------
10015            ForInStart => {
10016                let value = self.pop();
10017                let record = self.for_in_record(&value)?;
10018                self.push(Value::Object(record));
10019            }
10020            ForInNext => {
10021                // `record -> record key done`. The flag is *done*, not "found":
10022                // the compiler tests it with `if_false` to jump back into the body,
10023                // so reporting `true` while keys remain would end the loop at once.
10024                let record = self.peek(0);
10025                match self.for_in_advance(&record)? {
10026                    Some(key) => {
10027                        let text = self.string(key);
10028                        self.push(text);
10029                        self.push(Value::Bool(false));
10030                    }
10031                    None => {
10032                        self.push(Value::Undefined);
10033                        self.push(Value::Bool(true));
10034                    }
10035                }
10036            }
10037            ForOfStart => {
10038                let value = self.pop();
10039                let iterator = self.get_iterator(&value)?;
10040                self.push(iterator.object);
10041                self.push(iterator.next);
10042                self.push(Value::CatchOffset(0));
10043            }
10044            ForOfNext => {
10045                // `iter next catch_offset -> iter next catch_offset value done`.
10046                //
10047                // The operand is how many values sit *above* the iterator triple: a
10048                // destructuring rest element keeps its target array and running index
10049                // there while draining the iterator, so the triple is not at the top.
10050                let extra = a as usize;
10051                let iterator_slot = 2 + extra;
10052                // An exhausted iterator is replaced by `undefined` (see below), so a
10053                // second step must not call `next` again — `Array.from` and a
10054                // destructuring pattern both keep stepping past the end.
10055                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10056                    (Value::Undefined, true)
10057                } else {
10058                    let iterator = Iterator {
10059                        object: self.peek(iterator_slot),
10060                        next: self.peek(1 + extra),
10061                    };
10062                    self.iterator_step(&iterator)?
10063                };
10064                if done {
10065                    // The result's `value` is meaningless once the iterator is done:
10066                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10067                    // rather than binding the generator's return value.
10068                    let top = self.frame().stack.len() - 1 - iterator_slot;
10069                    self.frame_mut().stack[top] = Value::Undefined;
10070                    self.push(Value::Undefined);
10071                    self.push(Value::Bool(true));
10072                } else {
10073                    self.push(value);
10074                    self.push(Value::Bool(false));
10075                }
10076            }
10077            IteratorNext => {
10078                // `iter next catch val -> iter next catch val'`: replace the argument with
10079                // the result of `next(val)`. The triple below stays put, which is why the
10080                // three instructions of the `yield*` loop all address the stack the same way.
10081                let value = self.pop();
10082                let object = self.peek(2);
10083                let next = self.peek(1);
10084                let result = self.call_value(next, object, vec![value])?;
10085                self.push(result);
10086            }
10087            IteratorCall => {
10088                // `iter next catch val -> iter next catch val' flag`.
10089                //
10090                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10091                // The flag is `true` when the method was missing, which is how the
10092                // caller learns that the inner iterator cannot take part in the
10093                // unwinding.
10094                let value = self.pop();
10095                let object = self.peek(2);
10096                let key = if a & 1 != 0 { "throw" } else { "return" };
10097                let method = self.read_field(&object, key)?;
10098                if matches!(method, Value::Undefined | Value::Null) {
10099                    self.push(value);
10100                    self.push(Value::Bool(true));
10101                } else {
10102                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10103                    let result = self.call_value(method, object, argument)?;
10104                    self.push(result);
10105                    self.push(Value::Bool(false));
10106                }
10107            }
10108            IteratorCheckObject => {
10109                if !matches!(self.peek(0), Value::Object(_)) {
10110                    return Err(Signal::Throw(
10111                        self.make_error("TypeError", "iterator must return an object"),
10112                    ));
10113                }
10114            }
10115            IteratorClose => {
10116                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10117                // calling the iterator's `return` so it can release whatever it holds.
10118                //
10119                // The catch offset goes first, so an exception from `return` is not caught
10120                // by the loop being abandoned. This used to pop the three operands and call
10121                // nothing at all, which made `break` out of a `for of` invisible to an
10122                // iterator with a `return` method.
10123                self.pop();
10124                self.pop();
10125                let iterator = self.pop();
10126                if !matches!(iterator, Value::Undefined) {
10127                    let method = self.read_field(&iterator, "return")?;
10128                    if !matches!(method, Value::Undefined | Value::Null) {
10129                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10130                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10131                        if !matches!(result, Value::Object(_)) {
10132                            return Err(Signal::Throw(
10133                                self.make_error("TypeError", "iterator must return an object"),
10134                            ));
10135                        }
10136                    }
10137                }
10138            }
10139            Import => {
10140                // `import(specifier)`: the options slot is on top and is not read yet.
10141                let _options = self.pop();
10142                let specifier = self.pop();
10143                let promise = self.dynamic_import(specifier)?;
10144                self.push(promise);
10145            }
10146            ForAwaitOfStart => {
10147                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10148                // `Symbol.iterator` fallback.
10149                let value = self.pop();
10150                let iterator = self.get_async_iterator(&value)?;
10151                self.push(iterator.object);
10152                self.push(iterator.next);
10153                self.push(Value::CatchOffset(0));
10154            }
10155            ForAwaitOfNext => {
10156                // `for await` steps the iterator and leaves the *result* wrapped in a
10157                // promise, so the `await` the compiler emits right after this can suspend
10158                // on it. Unwrapping happens in `iterator_get_value_done`.
10159                let extra = a as usize;
10160                let iterator_slot = 2 + extra;
10161                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10162                    Value::Undefined
10163                } else {
10164                    let iterator = Iterator {
10165                        object: self.peek(iterator_slot),
10166                        next: self.peek(1 + extra),
10167                    };
10168                    let next = iterator.next.clone();
10169                    self.call_value(next, iterator.object, Vec::new())?
10170                };
10171                let promise = self.promise_resolve_value(result)?;
10172                self.push(promise);
10173            }
10174            IteratorGetValueDone => {
10175                // `result -> value done`. A missing result object means the iterator was
10176                // already exhausted, which the loop treats as `done`.
10177                let result = self.pop();
10178                let done = match &result {
10179                    Value::Object(object) => self
10180                        .get_property(object, "done")?
10181                        .is_some_and(|value| value.to_boolean()),
10182                    _ => true,
10183                };
10184                if done {
10185                    // Clear the iterator object so the `iterator_close` the loop emits on
10186                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10187                    // on normal completion, and this is where a normal completion is
10188                    // recognised — the same trick `for_of_next` uses, which also replaces
10189                    // the slot with `undefined`.
10190                    //
10191                    // The layout is fixed because only `for await` emits this opcode:
10192                    // `iter next catch [result]`, so the iterator is three below the top.
10193                    let depth = self.frame().stack.len();
10194                    if depth >= 3 {
10195                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10196                    }
10197                    self.push(Value::Undefined);
10198                    self.push(Value::Bool(true));
10199                } else {
10200                    let Value::Object(object) = &result else {
10201                        self.push(Value::Undefined);
10202                        self.push(Value::Bool(true));
10203                        return Ok(Step::Continue);
10204                    };
10205                    let value = self
10206                        .get_property(object, "value")?
10207                        .unwrap_or(Value::Undefined);
10208                    self.push(value);
10209                    self.push(Value::Bool(false));
10210                }
10211            }
10212
10213            Delete => {
10214                // `delete obj[key]`, where the key was just pushed. Deleting an array
10215                // index leaves a *hole* rather than closing the gap, and a
10216                // non-configurable property answers `false` and stays.
10217                let key = self.pop();
10218                let target = self.pop();
10219                let key = self.propkey(&key)?;
10220                let text_label = key.as_str().unwrap_or("").to_string();
10221                let deleted = match &target {
10222                    Value::Object(object) => {
10223                        let object = object.clone();
10224                        self.delete_property_key(&object, &key)?
10225                    }
10226                    // A string's `length` and its index properties are
10227                    // non-configurable, so deleting one answers `false`.
10228                    Value::String(text) => {
10229                        !(text_label == "length"
10230                            || array_index(&text_label)
10231                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10232                    }
10233                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10234                    // object to delete from, and only a *boxable* primitive has one.
10235                    Value::Undefined | Value::Null => {
10236                        return Err(Signal::Throw(
10237                            self.make_error("TypeError", "cannot convert to object"),
10238                        ));
10239                    }
10240                    // Any other primitive has no own properties; deleting nothing
10241                    // succeeds.
10242                    _ => true,
10243                };
10244                self.push(Value::Bool(deleted));
10245            }
10246
10247            // -- exceptions and bookkeeping ---------------------------------
10248            Fclosure | Fclosure8 => {
10249                let value = self.closure(a as usize)?;
10250                self.push(value);
10251            }
10252
10253            other => {
10254                let name = other.info().name;
10255                return Err(Signal::Throw(self.make_error(
10256                    "InternalError",
10257                    &format!("{name} is not implemented yet"),
10258                )));
10259            }
10260        }
10261        Ok(Step::Continue)
10262    }
10263
10264    // -- operand helpers ----------------------------------------------------
10265
10266    /// The slot index an operand names, taking short forms into account.
10267    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10268        use Opcode::*;
10269        match op {
10270            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10271            | SetVarRef0 => 0,
10272            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10273            | SetVarRef1 => 1,
10274            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10275            | SetVarRef2 => 2,
10276            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10277            | SetVarRef3 => 3,
10278            _ => a as usize,
10279        }
10280    }
10281
10282    /// The argument count of a call, taking `call0`…`call3` into account.
10283    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10284        use Opcode::*;
10285        match op {
10286            Call0 => 0,
10287            Call1 => 1,
10288            Call2 => 2,
10289            Call3 => 3,
10290            _ => a as usize,
10291        }
10292    }
10293
10294    /// The atom's name as a property key.
10295    ///
10296    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10297    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10298    /// `String::clone` was a heap allocation and a copy — per property access.
10299    /// The atom at `index`, as a property key.
10300    ///
10301    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10302    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10303    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10304    /// 5.3% of `property:monomorphic`.
10305    /// The atom's text, exactly — including an unpaired surrogate.
10306    ///
10307    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10308    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10309    /// `atom_text` below is for the other kind of use, where the atom is a key in the
10310    /// engine's own tables.
10311    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10312        self.frame()
10313            .code
10314            .code
10315            .atoms
10316            .get(index)
10317            .map(|atom| match atom {
10318                Atom::Str(text) => text.clone(),
10319                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10320                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10321                Atom::Null => crate::value::Wtf8::new(String::new()),
10322            })
10323            .unwrap_or_default()
10324    }
10325
10326    fn atom_text(&self, index: usize) -> String {
10327        self.frame()
10328            .code
10329            .code
10330            .atoms
10331            .get(index)
10332            .map(|atom| match atom {
10333                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10334                // compare it to an identifier, and a surrogate-bearing name is reachable
10335                // through `atom_wtf8` where it matters.
10336                Atom::Str(text) => text.to_string_lossy().into_owned(),
10337                Atom::Index(value) => value.to_string(),
10338                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10339                // `throw_error`, `delete super.x`) never read it.
10340                Atom::Null => String::new(),
10341            })
10342            .unwrap_or_default()
10343    }
10344
10345    fn constant(&mut self, index: usize) -> JsResult<Value> {
10346        let constant = self.frame().code.code.cpool.get(index).cloned();
10347        Ok(match &constant {
10348            Some(Constant::Number(number)) => Value::Float(*number),
10349            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10350            Some(Constant::BigInt { digits, radix }) => {
10351                match crate::bigint::BigInt::from_radix(digits, *radix) {
10352                    Some(big) => self.bigint(big),
10353                    // A literal the parser accepted is always parseable; a failure here
10354                    // would be a compiler bug, so it reads as an `InternalError`.
10355                    None => {
10356                        return Err(Signal::Throw(
10357                            self.make_error("InternalError", "unparseable bigint literal"),
10358                        ));
10359                    }
10360                }
10361            }
10362            Some(Constant::Function(_)) => {
10363                return Err(Signal::Throw(
10364                    self.make_error("InternalError", "a bare function constant"),
10365                ));
10366            }
10367            // A tagged template's call site: a frozen array of the cooked chunks with a
10368            // frozen `raw` array beside it, which is what `String.raw` reads back.
10369            Some(Constant::Template { cooked, raw }) => {
10370                let cooked_values: Vec<Value> = cooked
10371                    .iter()
10372                    .map(|chunk| match chunk {
10373                        Some(text) => self.string_wtf8(text.clone()),
10374                        None => Value::Undefined,
10375                    })
10376                    .collect();
10377                let raw_values: Vec<Value> =
10378                    raw.iter().map(|text| self.string(text.clone())).collect();
10379                let raw_array = self.new_array(raw_values);
10380                raw_array.set_extensible(false);
10381                let template = self.new_array(cooked_values);
10382                template.define(
10383                    "raw",
10384                    Property::with_attributes(Value::Object(raw_array), false, false),
10385                );
10386                template.set_extensible(false);
10387                Value::Object(template)
10388            }
10389            _ => Value::Undefined,
10390        })
10391    }
10392
10393    /// The reference cell a closure-variable slot names.
10394    ///
10395    /// Two kinds of binding share this addressing: a genuine closure variable
10396    /// (captured from an enclosing function) lives in this frame's environment,
10397    /// while a *declared global* lives in the realm so that a script, a function
10398    /// declaration and their uses all see one binding. A plain `Global` — an
10399    /// undeclared name that may be satisfied by the global object — has no cell at
10400    /// all, which is how `typeof x` still works for a name that does not exist.
10401    /// The reference cell a closure-variable slot names.
10402    ///
10403    /// The environment is resolved once, when the closure is built, and this is
10404    /// just the lookup afterwards. A *declared global* is in there too, pointing at
10405    /// the realm's cell, so a script, a hoisted function declaration and their uses
10406    /// all share one binding. A plain `Global` — a name the script never declared —
10407    /// is read and written through `get_var`/`put_var` by name instead, which is
10408    /// what lets the global object satisfy it.
10409    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10410        self.frame().env.cells.get(slot).cloned()
10411    }
10412
10413    /// Whether `slot` refers to a global binding through the reference table.
10414    ///
10415    /// A global's cell in the closure environment only exists so the slot has
10416    /// something to point at; the binding itself lives on the global object (a `var`)
10417    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10418    /// be routed, not performed on the placeholder.
10419    fn is_global_slot(&self, slot: usize) -> bool {
10420        self.frame()
10421            .code
10422            .code
10423            .closure_vars
10424            .get(slot)
10425            .is_some_and(|c| {
10426                // A module's declarations and imports are *not* globals: their cells are
10427                // the module environment's, filled by the host, so the placeholder routing
10428                // must not apply to them.
10429                matches!(
10430                    c.closure_type,
10431                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10432                )
10433            })
10434    }
10435
10436    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10437        if self.is_global_slot(slot) {
10438            return self.get_global(slot);
10439        }
10440        Ok(self
10441            .var_ref_cell(slot)
10442            .map(|cell| cell.get())
10443            .unwrap_or(Value::Undefined))
10444    }
10445
10446    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10447        // A function declaration is hoisted by storing into a global reference before
10448        // the body runs, so this path is also what puts it on the global object.
10449        if self.is_global_slot(slot) {
10450            return self.put_global(slot, value);
10451        }
10452        if let Some(cell) = self.var_ref_cell(slot) {
10453            cell.set(value);
10454        }
10455        Ok(())
10456    }
10457
10458    // -- closures -----------------------------------------------------------
10459
10460    /// Build the closure for the function constant `index`.
10461    ///
10462    /// Every entry in the child's closure table names where its binding lives in
10463    /// *this* frame: a local or argument slot that was marked captured, or a cell
10464    /// this frame is itself holding. That is how a variable three functions deep
10465    /// stays one binding.
10466    fn closure(&mut self, index: usize) -> JsResult<Value> {
10467        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10468        else {
10469            return Err(Signal::Throw(
10470                self.make_error("InternalError", "fclosure of a non-function"),
10471            ));
10472        };
10473        let mut cells = Vec::with_capacity(function.closure_vars.len());
10474        for closure_var in &function.closure_vars {
10475            let cell = match closure_var.closure_type {
10476                ClosureType::Arg => {
10477                    let slot = closure_var.var_idx as usize;
10478                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10479                }
10480                ClosureType::Local => {
10481                    let slot = closure_var.var_idx as usize;
10482                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10483                }
10484                ClosureType::Ref | ClosureType::GlobalRef => {
10485                    // A `Ref` names a cell in this frame's own closure table; a
10486                    // `GlobalRef` also starts there, then resolves by name below.
10487                    let slot = closure_var.var_idx as usize;
10488                    if let Some(cell) = self.frame().env.cells.get(slot) {
10489                        cells.push(cell.clone());
10490                        continue;
10491                    }
10492                    -1
10493                }
10494                _ => -1,
10495            };
10496            if cell >= 0 {
10497                let cell = self.frame().cells[cell as usize].clone();
10498                cells.push(cell);
10499                continue;
10500            }
10501            // A global: the cell is created on demand and shared through the realm,
10502            // so every function sees one binding.
10503            let name = closure_var.name.clone();
10504            let cell = match self.realm.globals.get(&name) {
10505                Some(cell) => cell.clone(),
10506                None => {
10507                    let cell = self.new_cell(Value::Undefined);
10508                    self.realm.globals.insert(name.clone(), cell.clone());
10509                    cell
10510                }
10511            };
10512            cells.push(cell);
10513        }
10514        let name = function.name.clone();
10515        // `.length` is the arity before any default or rest parameter, not the number
10516        // of slots a pattern parameter needs.
10517        let length = function.defined_args;
10518        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10519        // function and an arrow function do not. A *method* also does not, but that is not
10520        // known here — the method is marked when the `[[HomeObject]]` is attached (see
10521        // `set_home_object`), which is the moment it becomes a method.
10522        let function_kind = function.kind;
10523        let constructible =
10524            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10525        let code = Gc::new(self.heap, CompiledCode::new(*function));
10526        // A closure built inside an `eval` inherits the eval's view of the enclosing
10527        // bindings, so it can still read them once the eval has returned.
10528        let eval_scope = self
10529            .active_eval_scope
10530            .clone()
10531            .or_else(|| self.frame().env.eval_scope.clone());
10532        // A closure sees the variables a direct `eval` declared in the frame it was
10533        // created in — the ones declared before *and after* it, so the same object is
10534        // shared; only the phase bounds which of them are visible.
10535        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10536        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10537        let env = Gc::new(
10538            self.heap,
10539            ClosureEnv {
10540                cells,
10541                eval_scope,
10542                local_vars,
10543                local_phase,
10544            },
10545        );
10546        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10547        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10548        // the only thing that carries `Symbol.toStringTag`, so without it
10549        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10550        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10551        let proto = match function_kind {
10552            js_compile::bytecode::FunctionKind::AsyncGenerator => self
10553                .realm
10554                .async_generator_function_proto
10555                .clone()
10556                .or_else(|| self.realm.function_proto.clone().into()),
10557            js_compile::bytecode::FunctionKind::Generator => self
10558                .realm
10559                .generator_function_proto
10560                .clone()
10561                .or_else(|| self.realm.function_proto.clone().into()),
10562            js_compile::bytecode::FunctionKind::Async => self
10563                .realm
10564                .async_function_proto
10565                .clone()
10566                .or_else(|| self.realm.function_proto.clone().into()),
10567            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10568        };
10569        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10570        object.set_constructible(constructible);
10571        object.define(
10572            "length",
10573            Property::name_or_length(Value::Int(length as i32)),
10574        );
10575        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10576        // that checks the own-property descriptor fails if the property is missing.
10577        object.define("name", Property::name_or_length(self.string(name)));
10578        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10579        // when `[[Construct]]` is created, so a generator, an async function and an arrow
10580        // function have none of their own. Installing it unconditionally gave
10581        // `Array.fromAsync` (an async function) an own `prototype` property, which
10582        // `builtin.js` checks for absence.
10583        if constructible {
10584            self.install_function_prototype(&object);
10585        }
10586        Ok(Value::Object(object))
10587    }
10588
10589    // -- conversions used by the operators ----------------------------------
10590
10591    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10592        // `+x` is `ToNumber`, which for a string parses it and for an object runs
10593        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10594        // string, which then behaves differently in every later comparison.
10595        match value {
10596            Value::Int(_) | Value::Float(_) => Ok(value),
10597            other => Ok(Value::Float(self.to_js_number(&other)?)),
10598        }
10599    }
10600
10601    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10602    ///
10603    /// Returns the *converted* old value and the new one, because the two callers need
10604    /// different halves: `++x` yields the new value, while `x++` yields the old one and
10605    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10606    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10607    /// boolean.
10608    ///
10609    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10610    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10611    /// a bigint algorithm then ran exactly once.
10612    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10613        if let Value::BigInt(big) = &value {
10614            let one = crate::bigint::BigInt::from_i64(1);
10615            let next = if up { big.add(&one) } else { big.sub(&one) };
10616            return Ok((value, self.bigint(next)));
10617        }
10618        let old = self.numeric(value)?;
10619        let new = if up {
10620            increment(old.clone())
10621        } else {
10622            decrement(old.clone())
10623        };
10624        Ok((old, new))
10625    }
10626
10627    fn numeric(&mut self, value: Value) -> JsResult<Value> {
10628        // `ToNumber` on an object runs `ToPrimitive` first, which is how
10629        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10630        // heard at all. Reading the object's own tag instead (`other.to_number()`)
10631        // turned the whole operand into `NaN` and swallowed the exception.
10632        match value {
10633            Value::Int(_) | Value::Float(_) => Ok(value),
10634            other => Ok(Value::Float(self.to_js_number(&other)?)),
10635        }
10636    }
10637
10638    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10639    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10640        match value {
10641            Value::BigInt(big) => Ok((**big).clone()),
10642            // The reference words this the same way for every operator, so a failing
10643            // script reads identically; the operator itself adds nothing a caller can use.
10644            _ => Err(Signal::Throw(
10645                self.make_error("TypeError", "cannot convert bigint to number"),
10646            )),
10647        }
10648    }
10649
10650    /// Arithmetic where at least one operand is a `BigInt`.
10651    ///
10652    /// The two numeric types never mix, so a bigint paired with anything else is an error
10653    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10654    /// that the relational operators handle it separately.
10655    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10656        use Opcode::*;
10657        let a = self.bigint_operand(&left)?;
10658        let b = self.bigint_operand(&right)?;
10659        let result = match op {
10660            Add => a.add(&b),
10661            Sub => a.sub(&b),
10662            Mul => a.mul(&b),
10663            Div | Mod => {
10664                let Some((quotient, remainder)) = a.div_rem(&b) else {
10665                    return Err(Signal::Throw(
10666                        self.make_error("RangeError", "division by zero"),
10667                    ));
10668                };
10669                if op == Div { quotient } else { remainder }
10670            }
10671            Pow => {
10672                let Some(value) = a.pow(&b) else {
10673                    return Err(Signal::Throw(self.make_error(
10674                        "RangeError",
10675                        "BigInt exponent must be non-negative and not absurdly large",
10676                    )));
10677                };
10678                value
10679            }
10680            And => a.bitand(&b),
10681            Or => a.bitor(&b),
10682            Xor => a.bitxor(&b),
10683            Shl | Sar => {
10684                // A shift count is a `BigInt` here, and both directions are exact; a
10685                // negative count would be the other direction, which the spec forbids.
10686                let Some(count) = b.to_i64() else {
10687                    return Err(Signal::Throw(
10688                        self.make_error("RangeError", "BigInt shift count is too large"),
10689                    ));
10690                };
10691                if count < 0 {
10692                    return Err(Signal::Throw(self.make_error(
10693                        "RangeError",
10694                        "BigInt shift count must be non-negative",
10695                    )));
10696                }
10697                if op == Shl {
10698                    a.shl(count as u64)
10699                } else {
10700                    a.shr(count as u64)
10701                }
10702            }
10703            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10704            _ => {
10705                return Err(Signal::Throw(self.make_error(
10706                    "TypeError",
10707                    "BigInts have no unsigned right shift, use >> instead",
10708                )));
10709            }
10710        };
10711        Ok(self.bigint(result))
10712    }
10713
10714    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10715    ///
10716    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10717    /// is on the mathematical values, and nothing is rounded first.
10718    /// `<`, `<=`, `>`, `>=`.
10719    ///
10720    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10721    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10722    /// It is a `?`-returning function for exactly that reason: an object operand can run
10723    /// script, and script can throw. The old version compared `to_number` of the raw
10724    /// values, which answered `false` for every object instead of calling `valueOf` —
10725    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10726    /// never ran.
10727    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10728        // The hot arm first: `i < n` with both sides already integers. No conversion, no
10729        // call, nothing that can throw.
10730        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10731            let ordering = Some(left.cmp(right));
10732            return Ok(ordering_answer(op, ordering));
10733        }
10734        // Anything that can run script has to be converted first, in this order.
10735        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10736        {
10737            (
10738                self.to_primitive(left, Hint::Number)?,
10739                self.to_primitive(right, Hint::Number)?,
10740            )
10741        } else {
10742            (left, right)
10743        };
10744        let ordering = match (&left, &right) {
10745            // The loop condition `i < n` is integer against integer, and it runs once
10746            // per iteration of every loop in every program. Without this arm it took the
10747            // `to_number` path twice, which is a `match` plus a conversion each.
10748            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10749            (Value::String(a), Value::String(b)) => {
10750                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10751            }
10752            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10753            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10754            // is true even though `2.5` has no bigint form.
10755            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10756                let b = other.to_number();
10757                if b.is_nan() {
10758                    None
10759                } else {
10760                    compare_bigint_and_f64(a, b)
10761                }
10762            }
10763            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10764                let a = other.to_number();
10765                if a.is_nan() {
10766                    None
10767                } else {
10768                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10769                }
10770            }
10771            _ => left.to_number().partial_cmp(&right.to_number()),
10772        };
10773        Ok(ordering_answer(op, ordering))
10774    }
10775
10776    fn binary_add(&mut self) -> JsResult<()> {
10777        let right = self.pop();
10778        let left = self.pop();
10779        // Two integers add without any of the machinery below: no `ToPrimitive` (an
10780        // `Int` is already primitive), no string check, no bigint check, no allocation.
10781        // `x += 1` in a loop is the single most common instruction sequence in real
10782        // script, and it used to walk every one of those checks before reaching the
10783        // same `checked_add`.
10784        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10785            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10786            return Ok(());
10787        }
10788        let left = self.primitive_of(left)?;
10789        let right = self.primitive_of(right)?;
10790        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10791        // that check comes before the bigint one: `"" + 1n` is a string, not a
10792        // mixed-type error.
10793        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10794            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10795            // `TypeError`, the one place a symbol and a string do not mix.
10796            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10797            // between a copy and a rope from their lengths, and a rope is what turns
10798            // `text += "abc"` in a loop from quadratic into linear.
10799            if let (Value::String(left), Value::String(right)) = (&left, &right) {
10800                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10801                // reports as `InternalError: string too long`.
10802                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10803                    return Err(Signal::Throw(
10804                        self.make_error("InternalError", "string too long"),
10805                    ));
10806                };
10807                self.push(Value::String(Gc::new(self.heap, joined)));
10808                return Ok(());
10809            }
10810            // At least one operand was not a string, so `ToString` it. This rejects a
10811            // symbol, which is the one place a symbol and a string do not mix.
10812            let left = self.checked_to_wtf8(&left)?;
10813            let right = self.checked_to_wtf8(&right)?;
10814            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
10815            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
10816            let text = left.concat(&right);
10817            self.push(self.string_wtf8(text));
10818            return Ok(());
10819        }
10820        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
10821        // not a conversion.
10822        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
10823            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
10824            self.push(value);
10825            return Ok(());
10826        }
10827        let left = self.numeric(left)?;
10828        let right = self.numeric(right)?;
10829        self.push(add_numbers(left, right));
10830        Ok(())
10831    }
10832
10833    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
10834        self.to_primitive(value, Hint::Default)
10835    }
10836
10837    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
10838    ///
10839    /// The order depends on the hint: the "number" order tries `valueOf` first and
10840    /// `toString` second, the "string" order the other way round, and the default
10841    /// hint uses the number order. A result that is still an object is a `TypeError`,
10842    /// because no built-in `valueOf`/`toString` returns one.
10843    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
10844        let Value::Object(object) = &value else {
10845            return Ok(value);
10846        };
10847        // A Date overrides the default hint to mean "string", which is what
10848        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
10849        // this, `"" + new Date()` would print the milliseconds, not the date.
10850        let hint = if hint == Hint::Default && is_date_object(self, object) {
10851            Hint::String
10852        } else {
10853            hint
10854        };
10855        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
10856        // handed the hint as a string. This is the hook a Date uses for its default hint
10857        // and a script uses to take over conversion entirely.
10858        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
10859        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
10860            if !function.is_callable() {
10861                return Err(self.type_error("Symbol.toPrimitive is not a function"));
10862            }
10863            let hint = match hint {
10864                Hint::String => "string",
10865                Hint::Number => "number",
10866                Hint::Default => "default",
10867            };
10868            let hint = self.string(hint);
10869            let result = self.call_value(
10870                Value::Object(function),
10871                Value::Object(object.clone()),
10872                vec![hint],
10873            )?;
10874            if matches!(result, Value::Object(_)) {
10875                return Err(self.type_error("cannot convert object to primitive value"));
10876            }
10877            return Ok(result);
10878        }
10879        let order: [&str; 2] = match hint {
10880            Hint::String => ["toString", "valueOf"],
10881            Hint::Number | Hint::Default => ["valueOf", "toString"],
10882        };
10883        let receiver = object.clone();
10884        for method in order {
10885            if let Some(function) = self.get_property(&receiver, method)?
10886                && matches!(&function, Value::Object(object) if object.is_callable())
10887            {
10888                let result =
10889                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
10890                if !matches!(result, Value::Object(_)) {
10891                    return Ok(result);
10892                }
10893            }
10894        }
10895        Err(self.type_error("cannot convert object to primitive value"))
10896    }
10897
10898    /// `ToString` with the object case going through `ToPrimitive`.
10899    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
10900        if matches!(value, Value::Object(_)) {
10901            let primitive = self.to_primitive(value.clone(), Hint::String)?;
10902            return Ok(primitive.to_js_string());
10903        }
10904        Ok(value.to_js_string())
10905    }
10906
10907    /// `ToString` that keeps the string's code units instead of flattening them.
10908    ///
10909    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
10910    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
10911    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10912        if matches!(value, Value::Symbol(_)) {
10913            return Err(Signal::Throw(
10914                self.make_error("TypeError", "cannot convert symbol to string"),
10915            ));
10916        }
10917        // An object runs `ToPrimitive` first, which may itself produce a symbol.
10918        let value = self.to_primitive(value.clone(), Hint::String)?;
10919        match value {
10920            Value::Symbol(_) => Err(Signal::Throw(
10921                self.make_error("TypeError", "cannot convert symbol to string"),
10922            )),
10923            Value::String(text) => Ok(text.wtf8().clone()),
10924            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
10925        }
10926    }
10927
10928    /// `ToNumber` with the object case going through `ToPrimitive`.
10929    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
10930        let value = if matches!(value, Value::Object(_)) {
10931            self.to_primitive(value.clone(), Hint::Number)?
10932        } else {
10933            value.clone()
10934        };
10935        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
10936        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
10937        // `NaN` to stay total, and the operators check for the bigint themselves — but
10938        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
10939        // refuse, and answering `NaN` made them silently wrong instead.
10940        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
10941        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
10942        match value {
10943            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
10944            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
10945            other => Ok(other.to_number()),
10946        }
10947    }
10948
10949    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
10950    /// [`ElementType::write`].
10951    ///
10952    /// This is separated from the write because both conversions are observable script —
10953    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
10954    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
10955    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
10956    /// setters, and a plain `a[i] = v`.
10957    pub(crate) fn element_value(
10958        &mut self,
10959        element: crate::builtins::typedarray::ElementType,
10960        value: Value,
10961    ) -> JsResult<Value> {
10962        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
10963        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
10964        let primitive = match &value {
10965            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
10966            _ => value,
10967        };
10968        if element.is_bigint() {
10969            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
10970            Ok(Value::BigInt(Gc::new(self.heap, big)))
10971        } else {
10972            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
10973            Ok(Value::Float(self.to_js_number(&primitive)?))
10974        }
10975    }
10976
10977    /// `ToPropertyKey`: what a computed member access uses as its key.
10978    ///
10979    /// A symbol is returned as itself, never stringified — that is what keeps
10980    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
10981    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
10982        match value {
10983            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
10984            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
10985            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
10986            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
10987            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10988                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
10989                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
10990                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
10991                    other.to_js_string(),
10992                ))),
10993            },
10994            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
10995        }
10996    }
10997
10998    /// `ToPropertyKey` for the callers that can only use a string key.
10999    ///
11000    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
11001    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
11002    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
11003    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
11004    /// program continues with a value nobody asked for.
11005    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11006        use crate::value::Wtf8;
11007        Ok(match value {
11008            // A string key keeps its code units. Going through a lossy `String` would make
11009            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
11010            Value::String(text) => text.wtf8().clone(),
11011            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
11012            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
11013            // falling back to its `ToString` would print `[object Object]`.
11014            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11015                Value::String(text) => text.wtf8().clone(),
11016                other => Wtf8::new(other.to_js_string()),
11017            },
11018            other => Wtf8::new(other.to_js_string()),
11019        })
11020    }
11021
11022    // -- object operations used by instructions -----------------------------
11023
11024    /// Read `object[key]`, returning `undefined` when the property is missing.
11025    ///
11026    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
11027    /// primitive (looking through its prototype) as well as an object — which is what
11028    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
11029    /// argument needs too.
11030    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
11031        self.read_field_key(object, &PropertyKey::from(key))
11032    }
11033
11034    /// [`Interp::read_field`] with a key that may be a symbol.
11035    ///
11036    /// A symbol key never reaches the string shortcuts: a string's `length` and its
11037    /// indices are string properties, and a symbol named `length` is a different
11038    /// property that a string primitive cannot have.
11039    /// [`Interp::read_field_key`], with an inline cache in front of it.
11040    ///
11041    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11042    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11043    /// without this the engine walked the chain and compared ~40 property names on each
11044    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11045    ///
11046    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11047    /// missing property. Those answers depend on running code or on state the guard below
11048    /// does not cover, and a wrong answer here is far more expensive than a lookup.
11049    ///
11050    /// A hit is re-validated against the *whole* walked chain, not just the level that
11051    /// answered: the receiver and every prototype down to that level must still be the same
11052    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11053    /// property-table *lengths* — which is what catches a property appearing on an
11054    /// intermediate prototype and shadowing the cached one.
11055    pub fn read_field_cached(
11056        &mut self,
11057        object: &Value,
11058        key: &PropertyKey,
11059        slot: usize,
11060    ) -> JsResult<Value> {
11061        let index = Self::field_cache_slot(object, key, slot);
11062        let Value::Object(target) = object else {
11063            return self.read_field_key(object, key);
11064        };
11065        if target.proxy_state().is_some() {
11066            return self.read_field_key(object, key);
11067        }
11068        if let Some(cached) = &self.field_cache[index]
11069            && cached.key == *key
11070            && let Some(value) = Self::cached_hit(target, cached)
11071        {
11072            return Ok(value);
11073        }
11074        let value = self.read_field_key(object, key)?;
11075        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11076        Ok(value)
11077    }
11078
11079    /// Whether a cache entry still describes this lookup, and if so the value.
11080    ///
11081    /// The guard is the whole point of the entry: identity plus property-table length for
11082    /// every level walked. Re-checked per level rather than once at the receiving end,
11083    /// because a shadowing property can appear anywhere along the chain.
11084    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11085        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11086        // starts with: a clone is a reference-count bump and a drop, and for
11087        // `property:monomorphic` every single hit takes only this arm.
11088        let (weak, len) = cached.chain[0].as_ref()?;
11089        if !target.upgrades_to(weak) {
11090            return None;
11091        }
11092        if cached.level == 0 {
11093            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11094            return target.cached_property_at(cached.index, &cached.key, *len);
11095        }
11096        if target.props_len() != *len {
11097            return None;
11098        }
11099        let mut level = 1;
11100        let mut current = target.proto()?;
11101        loop {
11102            let (weak, len) = cached.chain[level].as_ref()?;
11103            if !current.upgrades_to(weak) || current.props_len() != *len {
11104                return None;
11105            }
11106            if level == cached.level as usize {
11107                // The level that answered: the value is only reusable while the key is
11108                // still there and still a plain data property.
11109                return current.cached_data_property(cached.index, &cached.key);
11110            }
11111            current = current.proto()?;
11112            level += 1;
11113        }
11114    }
11115
11116    /// Build a cache entry for a lookup that just went through the slow path.
11117    ///
11118    /// Records the chain only when the answer came from a plain data property at a level
11119    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11120    /// costs the next lookup the walk it would have cost anyway.
11121    fn record_field_lookup(
11122        target: &Gc<JsObject>,
11123        key: &PropertyKey,
11124        _value: Value,
11125    ) -> Option<FieldCache> {
11126        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11127            [None, None, None];
11128        let mut current = target.clone();
11129        for level in 0..MAX_CACHED_CHAIN {
11130            chain[level] = Some((current.downgrade(), current.props_len()));
11131            if let Some((found, _)) = current.own_property_index(key) {
11132                // `own_property_index` declines an accessor and a hole, which is exactly
11133                // the set that must not be cached.
11134                return Some(FieldCache {
11135                    key: key.clone(),
11136                    index: found,
11137                    level: level as u8,
11138                    chain,
11139                });
11140            }
11141            current = current.proto()?;
11142        }
11143        None
11144    }
11145
11146    /// Which cache slot a lookup uses.
11147    ///
11148    /// Mixes the object's address, the name and the site, so that two properties of one
11149    /// object, and one property of two objects, land in different slots — which is what lets
11150    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11151    /// other iteration.
11152    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11153        let mut hash = match object {
11154            Value::Object(object) => object.address(),
11155            _ => 0,
11156        };
11157        hash = hash
11158            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11159            .rotate_left(17)
11160            .wrapping_add(key.hash_code());
11161        hash = hash.wrapping_add(site.wrapping_mul(31));
11162        // The table is a power of two, so the low bits are the slot.
11163        hash & (FIELD_CACHE_SLOTS - 1)
11164    }
11165
11166    /// Read `key` from `object`, without the inline cache.
11167    ///
11168    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11169    /// prototype chain, while the cached form answers an own data property from memory.
11170    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11171        let text = key.as_str().unwrap_or("");
11172        let Value::Object(object) = object else {
11173            // Reading a property of `undefined`/`null` is the classic TypeError.
11174            if object.is_nullish() {
11175                return Err(Signal::Throw(self.make_error(
11176                    "TypeError",
11177                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11178                )));
11179            }
11180            // A string has `length` and index access without being boxed.
11181            if let Value::String(value) = object {
11182                if text == "length" {
11183                    return Ok(Value::Int(value.utf16_len() as i32));
11184                }
11185                if let Some(index) = array_index(text) {
11186                    return Ok(match value.wtf8().unit_at(index as usize) {
11187                        Some(unit) => self.string_wtf8(unit),
11188                        None => Value::Undefined,
11189                    });
11190                }
11191            }
11192            // A property of a primitive is looked up on its prototype: this is what
11193            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11194            let prototype = match object {
11195                Value::String(_) => self.realm.string_proto.clone(),
11196                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11197                Value::Bool(_) => self.realm.boolean_proto.clone(),
11198                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11199                // `sym.description` reads through the prototype, not off the symbol.
11200                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11201                // …and a bigint's on `BigInt.prototype`, which is how
11202                // `(255n).toString(16)` reaches its method.
11203                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11204                _ => None,
11205            };
11206            if let Some(prototype) = prototype
11207                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11208            {
11209                return Ok(value);
11210            }
11211            return Ok(Value::Undefined);
11212        };
11213        Ok(self
11214            .get_property_key(object, key)?
11215            .unwrap_or(Value::Undefined))
11216    }
11217
11218    /// The `#name` a private symbol stands for, for error messages.
11219    ///
11220    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11221    /// was made from.
11222    fn private_name(symbol: &Value) -> Option<String> {
11223        match symbol {
11224            Value::Symbol(symbol) if symbol.is_private() => Some(
11225                symbol
11226                    .description()
11227                    .map(|text| text.to_string())
11228                    .unwrap_or_default(),
11229            ),
11230            _ => None,
11231        }
11232    }
11233
11234    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11235    ///
11236    /// Every private-field opcode takes the symbol the class stored in its own scope; a
11237    /// non-symbol here would be a compiler bug, and the reference guards it with
11238    /// `JS_ThrowTypeErrorNotASymbol`.
11239    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11240        match symbol {
11241            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11242            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11243        }
11244    }
11245
11246    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11247    ///
11248    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11249    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11250    /// would hit if the parser did not reject it first.
11251    fn define_private_field(
11252        &mut self,
11253        object: &Value,
11254        symbol: &Value,
11255        value: Value,
11256    ) -> JsResult<()> {
11257        let key = self.private_key(symbol)?;
11258        let Some(target) = object.as_object() else {
11259            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11260        };
11261        if !target.is_extensible() {
11262            return Err(Signal::Throw(
11263                self.make_error("TypeError", "object is not extensible"),
11264            ));
11265        }
11266        if target.own_property_key(&key).is_some() {
11267            let name = Self::private_name(symbol).unwrap_or_default();
11268            return Err(Signal::Throw(self.make_error(
11269                "TypeError",
11270                &format!("private class field '{name}' already exists"),
11271            )));
11272        }
11273        target.define_data_key(&key, value);
11274        Ok(())
11275    }
11276
11277    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11278    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11279        let key = self.private_key(symbol)?;
11280        let Some(target) = object.as_object() else {
11281            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11282        };
11283        match target.own_property_key(&key) {
11284            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11285            None => {
11286                let name = Self::private_name(symbol).unwrap_or_default();
11287                Err(Signal::Throw(self.make_error(
11288                    "TypeError",
11289                    &format!("private class field '{name}' does not exist"),
11290                )))
11291            }
11292        }
11293    }
11294
11295    /// `JS_SetPrivateField`: the store half of the same rule.
11296    fn write_private_field(
11297        &mut self,
11298        object: &Value,
11299        symbol: &Value,
11300        value: Value,
11301    ) -> JsResult<()> {
11302        let key = self.private_key(symbol)?;
11303        let Some(target) = object.as_object() else {
11304            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11305        };
11306        if target.write_value_key(&key, value) {
11307            return Ok(());
11308        }
11309        let name = Self::private_name(symbol).unwrap_or_default();
11310        Err(Signal::Throw(self.make_error(
11311            "TypeError",
11312            &format!("private class field '{name}' does not exist"),
11313        )))
11314    }
11315
11316    /// The `in` half: does `object` have this private field?
11317    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11318    ///
11319    /// The symbol is created once per class — the first `add_brand` on a given home object
11320    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11321    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11322    /// emit for the *instance* brand passes null because all it wants is the symbol.
11323    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11324        let Some(home_object) = home.as_object() else {
11325            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11326        };
11327        let symbol = match home_object.private_brand() {
11328            Some(symbol) => symbol,
11329            None => {
11330                let symbol = Gc::new(
11331                    self.heap,
11332                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11333                );
11334                home_object.set_private_brand(symbol.clone());
11335                symbol
11336            }
11337        };
11338        let Some(target) = object.as_object() else {
11339            // Not an object: nothing to brand. The reference does the same, and `undefined`
11340            // here would otherwise turn a field initialiser into a TypeError.
11341            return Ok(());
11342        };
11343        if !target.is_extensible() {
11344            return Err(Signal::Throw(
11345                self.make_error("TypeError", "object is not extensible"),
11346            ));
11347        }
11348        if target.carries_brand(&symbol) {
11349            return Err(Signal::Throw(
11350                self.make_error("TypeError", "private method is already present"),
11351            ));
11352        }
11353        target.add_brand(symbol);
11354        Ok(())
11355    }
11356
11357    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11358    ///
11359    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11360    /// decides whether to throw.
11361    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11362        let Some(function) = function.as_object() else {
11363            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11364        };
11365        let Some(home) = function.home_object() else {
11366            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11367        };
11368        let Some(brand) = home.private_brand() else {
11369            return Err(Signal::Throw(
11370                self.make_error("TypeError", "expecting <brand> private field"),
11371            ));
11372        };
11373        Ok(object.carries_brand(&brand))
11374    }
11375
11376    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11377        let Value::Object(object) = object else {
11378            return Err(Signal::Throw(self.make_error(
11379                "TypeError",
11380                &format!("cannot set property '{key}' of {}", object.to_js_string()),
11381            )));
11382        };
11383        // The write half of the property inline cache, in effect: an own, writable,
11384        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11385        // decide — no prototype walk (an own property shadows the chain before a setter
11386        // there could matter), no extensibility check (the object already has the key),
11387        // and no `[[DefineOwnProperty]]`.
11388        //
11389        // `this.value = …` inside a method is the whole write side of
11390        // `property:method-call`, and it was reaching `set_property_with_key` with its
11391        // proxy test, its typed-array test, its array-index test and finally a linear
11392        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11393        //
11394        // Every disqualifier is checked here: a proxy traps the set, an array index and
11395        // `length` live outside the property table, and a typed array's element is stored
11396        // through its view's element type.
11397        if object.proxy_state().is_none()
11398            && !object.is_array()
11399            && object.typed_array_element_type().is_none()
11400            && object.write_value_key(key, value.clone())
11401        {
11402            return Ok(());
11403        }
11404        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11405        let on_failure = if self.frame().code.code.strict {
11406            DeleteFailure::Throw
11407        } else {
11408            DeleteFailure::Ignore
11409        };
11410        self.set_property_with_key(object, key, value, on_failure)
11411    }
11412
11413    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11414    ///
11415    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11416    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11417    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11418    /// `Number.parseInt(sym)` — so those callers use this instead.
11419    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11420        if matches!(value, Value::Symbol(_)) {
11421            return Err(Signal::Throw(
11422                self.make_error("TypeError", "cannot convert symbol to string"),
11423            ));
11424        }
11425        // An object runs `ToPrimitive` first, which may itself produce a symbol —
11426        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11427        let value = self.to_primitive(value.clone(), Hint::String)?;
11428        if matches!(value, Value::Symbol(_)) {
11429            return Err(Signal::Throw(
11430                self.make_error("TypeError", "cannot convert symbol to string"),
11431            ));
11432        }
11433        Ok(value.to_js_string())
11434    }
11435
11436    /// `ToPropertyKey` for a builtin that takes a key argument.
11437    ///
11438    /// Fallible: a key whose `toString` throws has to propagate that error, both for
11439    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11440    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11441    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11442    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11443        self.propkey(value)
11444    }
11445
11446    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11447    ///
11448    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11449    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11450    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11451    /// `RangeError` — and why this cannot be a plain `ToNumber`.
11452    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11453        let number = match value {
11454            Value::Int(number) => *number as f64,
11455            Value::Float(number) => *number,
11456            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11457            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11458            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11459            // reference answers 0.
11460            Value::Null | Value::Bool(_) => value.to_number(),
11461            _ => {
11462                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11463                match primitive {
11464                    Value::Int(number) => number as f64,
11465                    Value::Float(number) => number,
11466                    other => {
11467                        // `ToString` then `ToNumber`, so a string length goes through the
11468                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
11469                        // `Value::to_number` on the string already implements exactly that.
11470                        let text = self.to_js_string(&other)?;
11471                        crate::value::string_to_number(&text)
11472                    }
11473                }
11474            }
11475        };
11476        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11477        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11478        // is a `RangeError`, not `0`.
11479        if !number.is_finite()
11480            || number.fract() != 0.0
11481            || !(0.0..=u32::MAX as f64).contains(&number)
11482        {
11483            return Err(self.range_error("invalid array length"));
11484        }
11485        Ok(number as u32)
11486    }
11487
11488    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11489    /// `Object.getOwnPropertySymbols` put in their result array.
11490    pub fn key_value(&self, key: &PropertyKey) -> Value {
11491        match key {
11492            PropertyKey::String(text) => self.string_wtf8(text.clone()),
11493            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11494        }
11495    }
11496
11497    /// Fill in a String exotic object: `_value`, `length` and the index properties.
11498    ///
11499    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11500    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11501    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11502    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11503    /// the two paths had drifted; this is the one both now use.
11504    ///
11505    /// The indices are *code units*, so an astral character occupies two of them — the
11506    /// same rule `s.length` and `s[i]` follow.
11507    /// Give an already-created object the internal slot that makes it a wrapper of
11508    /// `value`, so the primitive's prototype methods work on it.
11509    ///
11510    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11511    /// which are wrappers of their own type holding the empty value.
11512    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11513        self.internal_set(object, "_value", value);
11514    }
11515
11516    pub(crate) fn init_string_wrapper(
11517        &mut self,
11518        object: &Gc<JsObject>,
11519        text: &Gc<crate::value::JsString>,
11520    ) {
11521        object.define(
11522            "length",
11523            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11524        );
11525        for index in 0..text.utf16_len() {
11526            if let Some(unit) = text.wtf8().unit_at(index) {
11527                object.define(
11528                    &index.to_string(),
11529                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11530                    Property::with_attributes(self.string_wtf8(unit), false, true),
11531                );
11532            }
11533        }
11534        object.define_key(
11535            &self.internal_slot("_value"),
11536            Property::with_attributes(Value::String(text.clone()), false, false),
11537        );
11538    }
11539
11540    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11541    ///
11542    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11543    /// throws. The wrapper carries its primitive in `_value` — the same slot
11544    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11545    /// on a boxed value no constructor ever built.
11546    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11547        let (prototype, primitive) = match value {
11548            Value::Object(object) => return Ok(object.clone()),
11549            Value::String(text) => {
11550                let object = self.new_object(self.realm.string_proto.clone());
11551                self.init_string_wrapper(&object, text);
11552                return Ok(object);
11553            }
11554            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11555            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11556            // A symbol and a bigint box into wrappers whose methods live on
11557            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11558            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11559            // branch below instead produced an object with *no* prototype, so those
11560            // methods were unreachable on a box.
11561            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11562            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11563            Value::Undefined | Value::Null => {
11564                return Err(Signal::Throw(self.make_error(
11565                    "TypeError",
11566                    &format!("cannot convert {} to object", value.to_js_string()),
11567                )));
11568            }
11569            _ => (None, value.clone()),
11570        };
11571        let object = self.new_object(prototype);
11572        self.internal_set(&object, "_value", primitive);
11573        Ok(object)
11574    }
11575
11576    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11577    ///
11578    /// Split out for a reader that has to create the object *before* it knows what it wraps:
11579    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11580    /// written before its primitive, so the placeholder has to exist first and be filled in
11581    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11582    /// than a second in the deserialiser.
11583    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11584        let prototype = match value {
11585            Value::String(_) => self.realm.string_proto.clone(),
11586            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11587            Value::Bool(_) => self.realm.boolean_proto.clone(),
11588            Value::Symbol(_) => self.realm.symbol_proto.clone(),
11589            Value::BigInt(_) => self.realm.bigint_proto.clone(),
11590            _ => {
11591                return Err(Signal::Throw(self.make_error(
11592                    "TypeError",
11593                    &format!("cannot box {}", value.to_js_string()),
11594                )));
11595            }
11596        };
11597        object.set_proto(prototype);
11598        if let Value::String(text) = value {
11599            self.init_string_wrapper(object, text);
11600            return Ok(());
11601        }
11602        self.internal_set(object, "_value", value.clone());
11603        Ok(())
11604    }
11605
11606    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11607    ///
11608    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11609    /// through the `Symbol` function object, so the registry is reachable as a method rather
11610    /// than only from `builtins::symbol`.
11611    pub fn symbol_for(&mut self, key: &str) -> Value {
11612        if let Some(existing) = self.realm.symbol_registry.get(key) {
11613            return existing.clone();
11614        }
11615        let symbol = crate::builtins::symbol::symbol_value(
11616            self,
11617            crate::value::JsSymbol::registered(key.to_string()),
11618        );
11619        self.realm
11620            .symbol_registry
11621            .insert(key.to_string(), symbol.clone());
11622        symbol
11623    }
11624
11625    /// `a == b`, the coercing comparison.
11626    ///
11627    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11628    /// which is what makes `[] == ""` true: `[]` becomes `""` via
11629    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11630    /// because the conversion is allowed to call script code, so the two primitive
11631    /// operands are handed back to it.
11632    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11633        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11634            return Ok(left.loose_equals(&right));
11635        }
11636        // `null == undefined` holds even though neither is an object.
11637        if matches!(left, Value::Undefined | Value::Null)
11638            && matches!(right, Value::Undefined | Value::Null)
11639        {
11640            return Ok(true);
11641        }
11642        if matches!(left, Value::Undefined | Value::Null)
11643            || matches!(right, Value::Undefined | Value::Null)
11644        {
11645            return Ok(false);
11646        }
11647        // Two objects compare by identity. Only an object *against a primitive* is
11648        // converted, which is why `{} == {}` is false while `[] == ""` is true.
11649        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11650            return Ok(a.ptr_eq(b));
11651        }
11652        let left = self.to_primitive(left, Hint::Default)?;
11653        let right = self.to_primitive(right, Hint::Default)?;
11654        Ok(left.loose_equals(&right))
11655    }
11656
11657    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11658        let Value::Object(object) = object else {
11659            return Err(Signal::Throw(
11660                self.make_error("TypeError", "cannot use 'in' on a non-object"),
11661            ));
11662        };
11663        let key = self.propkey(key)?;
11664        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11665        // trap. One implementation, so an array's derived `length` and its inherited holes
11666        // cannot be right in one caller and wrong in another.
11667        self.has_own_or_inherited(object, &key)
11668    }
11669
11670    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11671    ///
11672    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11673    /// whole reason the operator is a hook rather than a prototype walk.
11674    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11675        if let Value::Object(function) = constructor {
11676            let key = self.realm.well_known_key(WellKnown::HasInstance);
11677            let method = self.get_property_key(function, &key)?;
11678            if let Some(method) = method
11679                && !matches!(method, Value::Undefined)
11680            {
11681                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11682                return Ok(answer.to_boolean());
11683            }
11684        }
11685        self.instance_of(object, constructor)
11686    }
11687
11688    /// `OrdinaryHasInstance`: the prototype walk on its own.
11689    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11690        self.instance_of(object, constructor)
11691    }
11692
11693    /// `IsArray`: an array, or a proxy whose target is one.
11694    ///
11695    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11696    /// makes `Array.isArray(new Proxy([], {}))` true.
11697    pub fn is_array_value(&self, value: &Value) -> bool {
11698        match value {
11699            Value::Object(object) => {
11700                if let Some(state) = object.proxy_state() {
11701                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11702                }
11703                object.is_array()
11704            }
11705            _ => false,
11706        }
11707    }
11708
11709    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11710    ///
11711    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11712    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11713    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11714    /// see [`Interp::enqueue_job_function`].
11715    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11716        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11717        // the handler is reported rather than lost — the same reason a `then` reaction needs a
11718        // promise to settle.
11719        let promise = self.new_promise();
11720        self.fulfill_promise(&promise, Value::Undefined);
11721        self.jobs.push_back(Job::Reaction {
11722            handler: Some(function),
11723            argument: Value::Undefined,
11724            rejected: false,
11725            promise,
11726        });
11727        Ok(())
11728    }
11729
11730    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11731        let Value::Object(target) = object else {
11732            return Ok(false);
11733        };
11734        let Value::Object(function) = constructor else {
11735            return Err(Signal::Throw(self.make_error(
11736                "TypeError",
11737                "right-hand side of 'instanceof' is not callable",
11738            )));
11739        };
11740        let prototype = self.get_property(function, "prototype")?;
11741        let Some(Value::Object(prototype)) = prototype else {
11742            return Ok(false);
11743        };
11744        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11745        // which is also what makes `proxyOfInstance instanceof C` work.
11746        let mut current = Some(target.clone());
11747        while let Some(object) = current {
11748            if object.ptr_eq(&prototype) {
11749                return Ok(true);
11750            }
11751            current = self.object_prototype_of(&object)?;
11752        }
11753        Ok(false)
11754    }
11755
11756    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11757    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11758        if let Some(proto) = self.proxy_get_prototype_of(object)? {
11759            return Ok(proto);
11760        }
11761        if let Some(exotic) = object.exotic()
11762            && let Some(proto) = exotic.get_prototype(self, object)?
11763        {
11764            return Ok(proto);
11765        }
11766        Ok(object.proto())
11767    }
11768
11769    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11770    pub fn object_set_prototype_of(
11771        &mut self,
11772        object: &Gc<JsObject>,
11773        proto: Option<Gc<JsObject>>,
11774    ) -> JsResult<bool> {
11775        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11776            return Ok(answer);
11777        }
11778        if let Some(exotic) = object.exotic()
11779            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11780        {
11781            return Ok(answer);
11782        }
11783        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11784        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11785        // inheriting from itself, which every later prototype walk then had to defend
11786        // against — and `Reflect.setPrototypeOf` reported success for an operation the
11787        // language says is impossible.
11788        if let Some(proto) = &proto {
11789            let mut current = Some(proto.clone());
11790            let mut guard = 0;
11791            while let Some(node) = current {
11792                if node.ptr_eq(object) {
11793                    return Err(Signal::Throw(
11794                        self.make_error("TypeError", "circular prototype chain"),
11795                    ));
11796                }
11797                guard += 1;
11798                if guard > 1000 {
11799                    break;
11800                }
11801                current = node.proto();
11802            }
11803        }
11804        object.set_proto(proto);
11805        Ok(true)
11806    }
11807
11808    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
11809    ///
11810    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
11811    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
11812    /// already one.
11813    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
11814        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
11815        // (§10.4.5.4 step 1.b.i) — the prototype chain is *not* consulted for a canonical
11816        // numeric index. That is observable: a view that has been resized out of bounds
11817        // has no indices, and `2 in view` must then be `false` even when
11818        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
11819        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
11820        // A proxy is excluded because it has no `[[ViewedArrayBuffer]]` slot of its own.
11821        if object.typed_array_parts().is_some()
11822            && object.proxy_state().is_none()
11823            && let Some(index) = key.as_str().and_then(array_index)
11824        {
11825            return Ok(object
11826                .typed_array_length()
11827                .is_some_and(|length| (index as usize) < length));
11828        }
11829        let mut current = Some(object.clone());
11830        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
11831        let mut guard = 0;
11832        while let Some(node) = current {
11833            guard += 1;
11834            if guard > 1000 {
11835                return Ok(false);
11836            }
11837            let own = self.object_get_own_property(&node, key)?;
11838            if own.is_some() {
11839                return Ok(true);
11840            }
11841            current = self.object_prototype_of(&node)?;
11842        }
11843        Ok(false)
11844    }
11845
11846    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
11847    ///
11848    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
11849    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
11850    /// boolean as well, and it needs the receiver to be the one the caller named.
11851    pub fn set_property_with_key_receiver(
11852        &mut self,
11853        object: &Gc<JsObject>,
11854        key: &PropertyKey,
11855        value: Value,
11856        receiver: Option<&Value>,
11857        on_failure: DeleteFailure,
11858    ) -> JsResult<bool> {
11859        let receiver = receiver
11860            .cloned()
11861            .unwrap_or_else(|| Value::Object(object.clone()));
11862        if object.proxy_state().is_some() {
11863            return match self.proxy_set(object, key, value, &receiver)? {
11864                Some(accepted) => Ok(accepted),
11865                None => Ok(true),
11866            };
11867        }
11868        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
11869        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
11870        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
11871        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
11872        if object.typed_array_element_type().is_some()
11873            && key.as_str().and_then(array_index).is_some()
11874        {
11875            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
11876            self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
11877            return Ok(true);
11878        }
11879        // An own accessor, or one found up the chain, receives the call with `receiver` as
11880        // `this` — which is the whole reason this variant exists.
11881        if let Some(setter) = self.lookup_setter(object, key)? {
11882            self.call_value(setter, receiver, vec![value])?;
11883            return Ok(true);
11884        }
11885        // Otherwise it is an ordinary create-or-write, which the plain path already does —
11886        // carrying the receiver comparison, which a typed array's element store can see.
11887        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
11888        self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
11889        Ok(true)
11890    }
11891
11892    /// The setter `key` resolves to, if it resolves to an accessor.
11893    fn lookup_setter(
11894        &mut self,
11895        object: &Gc<JsObject>,
11896        key: &PropertyKey,
11897    ) -> JsResult<Option<Value>> {
11898        let mut current = Some(object.clone());
11899        let mut guard = 0;
11900        while let Some(node) = current {
11901            guard += 1;
11902            if guard > 1000 {
11903                return Ok(None);
11904            }
11905            if let Some(property) = self.object_get_own_property(&node, key)? {
11906                if property.is_accessor() {
11907                    return Ok(property.setter);
11908                }
11909                // A data property stops the walk: the store writes here, not further up.
11910                return Ok(None);
11911            }
11912            current = self.object_prototype_of(&node)?;
11913        }
11914        Ok(None)
11915    }
11916
11917    /// `[[IsExtensible]]`, with the proxy trap when there is one.
11918    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11919        if let Some(answer) = self.proxy_is_extensible(object)? {
11920            return Ok(answer);
11921        }
11922        if let Some(exotic) = object.exotic()
11923            && let Some(answer) = exotic.is_extensible(self, object)?
11924        {
11925            return Ok(answer);
11926        }
11927        Ok(object.is_extensible())
11928    }
11929
11930    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
11931    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11932        if let Some(answer) = self.proxy_prevent_extensions(object)? {
11933            return Ok(answer);
11934        }
11935        if let Some(exotic) = object.exotic()
11936            && let Some(answer) = exotic.prevent_extensions(self, object)?
11937        {
11938            return Ok(answer);
11939        }
11940        object.set_extensible(false);
11941        Ok(true)
11942    }
11943
11944    fn copy_properties(
11945        &mut self,
11946        target: &Value,
11947        source: &Value,
11948        exclusion: &Value,
11949    ) -> JsResult<()> {
11950        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
11951        // does contribute: its index properties are own, enumerable and writable, which
11952        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
11953        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
11954        // is a no-op.
11955        let Some(target) = target.as_object() else {
11956            return Ok(());
11957        };
11958        let source_object = match source {
11959            Value::Object(object) => object.clone(),
11960            Value::String(text) => {
11961                // Untaken keys are the string's indices, which are code units.
11962                for index in 0..text.utf16_len() {
11963                    if let Some(unit) = text.wtf8().unit_at(index) {
11964                        target.define_data(&index.to_string(), self.string_wtf8(unit));
11965                    }
11966                }
11967                return Ok(());
11968            }
11969            _ => return Ok(()),
11970        };
11971        // An object *rest* element passes the keys already taken by the literal part as
11972        // an array of strings; a spread passes `null`, which excludes nothing. Only the
11973        // string keys of the exclusion array are meaningful, so an array is read by its
11974        // elements rather than by its own property names.
11975        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
11976        if let Value::Object(list) = exclusion
11977            && let Some(length) = list.array_length()
11978        {
11979            for index in 0..length {
11980                if let Some(value) = list.array_get(index) {
11981                    excluded.push(self.propkey_of(&value)?);
11982                }
11983            }
11984        }
11985        let source = &source_object;
11986        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
11987        // Reading the property table directly made every spread of a proxy empty.
11988        let keys = self.object_own_property_keys(source)?;
11989        for as_key in keys {
11990            if as_key.is_symbol() {
11991                // A spread copies string-keyed properties only.
11992                continue;
11993            }
11994            if excluded.contains(&crate::value::Wtf8::new(
11995                as_key.as_str().unwrap_or_default(),
11996            )) {
11997                continue;
11998            }
11999            let enumerable = self
12000                .object_get_own_property(source, &as_key)?
12001                .is_some_and(|property| property.enumerable);
12002            if !enumerable {
12003                continue;
12004            }
12005            let value = self
12006                .get_property_key(source, &as_key)?
12007                .unwrap_or(Value::Undefined);
12008            target.define_data_key(&as_key, value);
12009        }
12010        Ok(())
12011    }
12012
12013    // -- iteration ---------------------------------------------------------
12014
12015    /// One object's own keys in enumeration order: array indices ascending, then the
12016    /// rest in insertion order.
12017    ///
12018    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
12019    /// whether the key is enumerable, which the caller resolves per key because an
12020    /// array's elements are not in the same store as its named properties.
12021    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
12022        // An index can arrive twice, once from the array's element store and once from
12023        // its property map, so the numeric keys go through a map that keeps the
12024        // enumerable answer if either source gave one.
12025        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
12026        for (key, enumerable) in &own {
12027            if let Some(index) = key.as_str().and_then(array_index) {
12028                let entry = numeric.entry(index).or_insert(false);
12029                *entry = *entry || *enumerable;
12030            }
12031        }
12032        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12033            .into_iter()
12034            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12035            .collect();
12036        ordered.extend(
12037            own.into_iter()
12038                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12039        );
12040        ordered
12041    }
12042
12043    /// Build the key list a `for-in` loop walks.
12044    ///
12045    /// The order is the specification's: own properties before inherited ones, and
12046    /// within one object the integer-like keys in ascending numeric order ahead of the
12047    /// string keys in insertion order. A shadowed key only appears once, and a key that
12048    /// is a non-enumerable own property anywhere nearer is skipped entirely.
12049    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12050        let record = self.new_object(None);
12051        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12052        // A proxy supplies its own key list, and — the reason this is not just another
12053        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12054        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12055        // descriptor there.
12056        if let Value::Object(object) = value
12057            && object.proxy_state().is_some()
12058        {
12059            let own = self
12060                .proxy_own_keys(object)?
12061                .unwrap_or_else(|| object.own_property_keys());
12062            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12063            let mut numeric: Vec<u32> = Vec::new();
12064            let mut rest: Vec<PropertyKey> = Vec::new();
12065            for key in own {
12066                match key.as_str().and_then(array_index) {
12067                    Some(index) => numeric.push(index),
12068                    None => rest.push(key),
12069                }
12070            }
12071            numeric.sort_unstable();
12072            ordered.extend(
12073                numeric
12074                    .into_iter()
12075                    .map(|index| PropertyKey::from(index.to_string())),
12076            );
12077            ordered.extend(rest);
12078            for (index, key) in ordered.into_iter().enumerate() {
12079                record.define_data(&index.to_string(), self.key_value(&key));
12080            }
12081            record.define_data("__index", Value::Int(0));
12082            // The mark that makes `for_in_advance` re-ask the proxy per key.
12083            record.define_data("__proxy", Value::Object(object.clone()));
12084            return Ok(record);
12085        }
12086        if let Value::Object(object) = value {
12087            let mut chain = vec![object.clone()];
12088            chain.extend(object.chain());
12089            // Every own string key the walk has seen, enumerable or not. A
12090            // non-enumerable own property still hides a same-named enumerable one
12091            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12092            // keeps `x` out of the loop even when the prototype has one.
12093            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12094            for object in chain {
12095                let mut own: Vec<(crate::value::Wtf8, bool)> = object
12096                    .own_property_keys()
12097                    .iter()
12098                    .filter_map(|key| key.as_wtf8().cloned())
12099                    .map(|key| {
12100                        let enumerable = object
12101                            .own_property(&key.to_string_lossy())
12102                            .map(|property| property.enumerable)
12103                            .unwrap_or(false);
12104                        (key, enumerable)
12105                    })
12106                    .collect();
12107                if let Some(length) = object.array_length() {
12108                    own.retain(|(key, _)| key.as_str() != Some("length"));
12109                    for index in 0..length {
12110                        if object.array_get(index).is_some() {
12111                            own.push((crate::value::Wtf8::new(index.to_string()), true));
12112                        }
12113                    }
12114                }
12115                // Integer-like keys come first in ascending order, then the rest in
12116                // insertion order — and the ordering is *per object*, not for the chain
12117                // as a whole: one pass over every collected key lifted a prototype's
12118                // `"4"` above the target's own `x`/`y`, which is not the order
12119                // `for…in` reports.
12120                for (key, enumerable) in Self::order_own_keys(own) {
12121                    if visited.contains(&key) {
12122                        continue;
12123                    }
12124                    visited.push(key.clone());
12125                    if enumerable {
12126                        keys.push(key);
12127                    }
12128                }
12129            }
12130        }
12131        for (index, key) in keys.into_iter().enumerate() {
12132            record.define_data(&index.to_string(), self.string_wtf8(key));
12133        }
12134        record.define_data("__index", Value::Int(0));
12135        Ok(record)
12136    }
12137
12138    /// The next key of a `for…in` record, `None` when the loop is done.
12139    ///
12140    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12141    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12142    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12143    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12144    /// key the handler had already withdrawn.
12145    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12146        let Value::Object(record) = record else {
12147            return Ok(None);
12148        };
12149        let proxy = record
12150            .own_property("__proxy")
12151            .and_then(|property| property.value);
12152        loop {
12153            let index = record
12154                .own_property("__index")
12155                .and_then(|property| property.value)
12156                .map(|value| value.to_int32())
12157                .unwrap_or(0);
12158            let Some(candidate) = record
12159                .own_property(&index.to_string())
12160                .and_then(|property| property.value)
12161            else {
12162                return Ok(None);
12163            };
12164            record.define_data("__index", Value::Int(index + 1));
12165            let text = candidate.to_js_string();
12166            let Some(Value::Object(proxy)) = &proxy else {
12167                return Ok(Some(text));
12168            };
12169            // The candidate is already a key string here, so the lookup does not need a
12170            // second `ToPropertyKey` conversion.
12171            let key = PropertyKey::from(text.as_str());
12172            let live = match self.proxy_get_own_property(proxy, &key)? {
12173                Some(descriptor) => descriptor,
12174                // Not a proxy after all, or it lost its state: fall back to the target.
12175                None => proxy.own_property_key(&key),
12176            };
12177            if live.is_some_and(|property| property.enumerable) {
12178                return Ok(Some(text));
12179            }
12180            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12181            // next one.
12182        }
12183    }
12184
12185    /// The iterator for `for-of`: the object and its `next` method.
12186    ///
12187    /// An object that already carries a `next` method is used as it is — that is what
12188    /// `arr.values()` returns — and only arrays and strings get the built-in
12189    /// sequence iterator.
12190    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12191    ///
12192    /// Callers that must choose between the iterable and the array-like protocol — the
12193    /// typed-array constructor is the main one — need to ask *before* committing to one.
12194    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12195        let key = self.realm.well_known_key(WellKnown::Iterator);
12196        let method = self.read_field_key(value, &key)?;
12197        if matches!(method, Value::Undefined | Value::Null) {
12198            return Ok(false);
12199        }
12200        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12201            return Err(Signal::Throw(
12202                self.make_error("TypeError", "Symbol.iterator is not callable"),
12203            ));
12204        }
12205        Ok(true)
12206    }
12207
12208    /// Collect everything an iterable yields, closing it if the walk is abandoned.
12209    ///
12210    /// The cap is a guard against a generator that never ends: an unbounded collect would
12211    /// be an out-of-memory abort rather than a catchable error.
12212    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12213        const MAX_ITEMS: usize = 1 << 24;
12214        let iterator = self.get_iterator(value)?;
12215        let mut out = Vec::new();
12216        loop {
12217            let (element, done) = self.iterator_step(&iterator)?;
12218            if done {
12219                return Ok(out);
12220            }
12221            out.push(element);
12222            if out.len() > MAX_ITEMS {
12223                return Err(self.range_error("iterable is too long to collect"));
12224            }
12225        }
12226    }
12227
12228    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12229    ///
12230    /// A native constructor calls this once it has validated its arguments, which is the
12231    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12232    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12233    /// never reached. The prototype comes from `new.target` when it is an object, and from
12234    /// `default_proto` otherwise.
12235    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12236        let proto = self.ctor_prototype(default_proto)?;
12237        Ok(self.new_object(Some(proto)))
12238    }
12239
12240    /// An **array** whose prototype comes from `new.target`.
12241    ///
12242    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12243    /// instance from `new.target.prototype`, and building a plain array instead made every
12244    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12245    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12246        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12247        Ok(JsObject::array(self.heap, Some(proto), 0))
12248    }
12249
12250    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12251    ///
12252    /// The `Option` form is for the constructors that build their instance in a helper which
12253    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12254    /// from `await`'s internal promise, and only the first has a `new.target`.
12255    fn ctor_prototype_opt(
12256        &mut self,
12257        default_proto: Option<Gc<JsObject>>,
12258    ) -> JsResult<Option<Gc<JsObject>>> {
12259        let Some(target) = self.pending_new_target.clone() else {
12260            return Ok(default_proto);
12261        };
12262        let Some(target) = target.as_object().cloned() else {
12263            return Ok(default_proto);
12264        };
12265        match self.get_property(&target, "prototype")? {
12266            Some(Value::Object(proto)) => Ok(Some(proto)),
12267            _ => Ok(default_proto),
12268        }
12269    }
12270
12271    /// `new.target.prototype`, or `default_proto` when this is a plain call.
12272    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12273        let Some(target) = self.pending_new_target.clone() else {
12274            return Ok(default_proto);
12275        };
12276        let Some(target) = target.as_object().cloned() else {
12277            return Ok(default_proto);
12278        };
12279        match self.get_property(&target, "prototype")? {
12280            Some(Value::Object(proto)) => Ok(proto),
12281            _ => Ok(default_proto),
12282        }
12283    }
12284
12285    /// `CreateDataPropertyOrThrow(O, key, value)`.
12286    ///
12287    /// A *definition*, not an assignment. The difference is visible the moment the target
12288    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12289    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12290    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12291    /// refused (`configurable: false`).
12292    ///
12293    /// The fast path exists because this is called once per element by `map`, `filter`,
12294    /// `slice` and friends: a plain array with no custom element descriptors and a writable
12295    /// `length` can store straight into its element vector.
12296    pub fn create_data_property_or_throw(
12297        &mut self,
12298        object: &Gc<JsObject>,
12299        index: usize,
12300        value: Value,
12301    ) -> JsResult<()> {
12302        if object.is_array()
12303            && object.elements_writable()
12304            && !object.has_element_descriptors()
12305            && object.is_extensible()
12306            && object.array_set(self.heap, index, value.clone())
12307        {
12308            return Ok(());
12309        }
12310        let key = PropertyKey::from(index.to_string());
12311        let property = Property {
12312            value: Some(value),
12313            writable: true,
12314            enumerable: true,
12315            configurable: true,
12316            ..Property::default()
12317        };
12318        if self.object_define_own_property(object, &key, property)? {
12319            return Ok(());
12320        }
12321        Err(self.type_error("cannot create the property"))
12322    }
12323
12324    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12325    ///
12326    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12327    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12328    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12329    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12330    /// run user code and both can throw.
12331    pub fn species_constructor(
12332        &mut self,
12333        object: &Gc<JsObject>,
12334        default: Value,
12335    ) -> JsResult<Value> {
12336        let Some(constructor) = self.get_property(object, "constructor")? else {
12337            return Ok(default);
12338        };
12339        let constructor = match constructor {
12340            Value::Undefined => return Ok(default),
12341            Value::Object(constructor) => constructor,
12342            _ => return Err(self.type_error("constructor is not an object")),
12343        };
12344        let key = self.realm.well_known_key(WellKnown::Species);
12345        let species = self.get_property_key(&constructor, &key)?;
12346        match species {
12347            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12348            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12349            Some(_) => Err(self.type_error("species is not a constructor")),
12350        }
12351    }
12352
12353    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12354    ///
12355    /// The result is an array of `length` holes whose prototype comes from
12356    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12357    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12358    /// is why the `IsArray` check is the first step and not an optimisation.
12359    pub fn array_species_create(
12360        &mut self,
12361        original: &Value,
12362        length: usize,
12363    ) -> JsResult<Gc<JsObject>> {
12364        let Some(object) = original.as_object().cloned() else {
12365            return Ok(self.new_array_of_length(length));
12366        };
12367        if !object.is_array() {
12368            return Ok(self.new_array_of_length(length));
12369        }
12370        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12371        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12372        let Some(constructor) = self.get_property(&object, "constructor")? else {
12373            return Ok(self.new_array_of_length(length));
12374        };
12375        let species = match constructor {
12376            Value::Undefined => return Ok(self.new_array_of_length(length)),
12377            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12378                return Ok(self.new_array_of_length(length));
12379            }
12380            Value::Object(constructor) => {
12381                let key = self.realm.well_known_key(WellKnown::Species);
12382                match self.get_property_key(&constructor, &key)? {
12383                    None | Some(Value::Undefined) | Some(Value::Null) => {
12384                        return Ok(self.new_array_of_length(length));
12385                    }
12386                    Some(species) => species,
12387                }
12388            }
12389            _ => return Ok(self.new_array_of_length(length)),
12390        };
12391        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12392        // that is merely callable is the `create-species-non-ctor` case.
12393        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12394            return Err(self.type_error("species is not a constructor"));
12395        }
12396        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12397        let Some(created) = created.as_object().cloned() else {
12398            return Err(self.type_error("species constructor did not answer an object"));
12399        };
12400        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12401        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12402        // object, and `create-species-with-non-writable-property` asserts exactly that.
12403        // The length is set for the array case; the generic case is the caller's
12404        // `Set(A, "length", …)`.
12405        if created.is_array() {
12406            created.array_set_length(self.heap, length);
12407        }
12408        Ok(created)
12409    }
12410
12411    /// Whether `object` is this realm's `%Array%`.
12412    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12413        self.realm
12414            .array_constructor
12415            .as_ref()
12416            .is_some_and(|array| array.ptr_eq(object))
12417    }
12418
12419    /// A fresh `length`-hole array with the intrinsic prototype.
12420    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12421        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12422        array.array_set_length(self.heap, length);
12423        array
12424    }
12425
12426    /// Whether this call is a construction, i.e. `new.target` is defined.
12427    ///
12428    /// A native constructor receives `this = undefined` (it builds its own instance), so it
12429    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12430    /// The native function currently executing, if any.
12431    pub fn current_native(&self) -> Option<Gc<JsObject>> {
12432        self.current_native.clone()
12433    }
12434
12435    /// Whether this call is a construction, i.e. `new.target` is defined.
12436    pub fn is_constructing(&self) -> bool {
12437        self.pending_new_target.is_some()
12438    }
12439
12440    /// The `TypeError` a constructor too primitive to have a wrapper raises.
12441    ///
12442    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12443    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12444    /// happens inside the native function, which is why the trace carries an
12445    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12446    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12447    /// constructor`, and an unnamed one reports the leading space of `" is not a
12448    /// constructor"` because the reference formats the empty name as it is.
12449    ///
12450    /// It is also the answer for a `new.target` that cannot be named at all — not a
12451    /// function, or a throwing `name` getter — where the reference falls back to the bare
12452    /// `not a constructor`.
12453    pub fn not_a_constructor_error(&mut self) -> Signal {
12454        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12455        self.not_a_constructor_error_for(target)
12456    }
12457
12458    /// The same `TypeError` for an explicit target, for the callers that check
12459    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12460    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12461        let target = match target {
12462            Value::Object(target) if target.is_callable() => target,
12463            _ => return self.type_error("not a constructor"),
12464        };
12465        let name = match self.get_property(&target, "name") {
12466            Ok(Some(value)) => value.to_js_string(),
12467            _ => return self.type_error("not a constructor"),
12468        };
12469        self.type_error(format!("{name} is not a constructor"))
12470    }
12471
12472    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12473    ///
12474    /// True whenever `new.target` is not the callee itself, or when it has no usable
12475    /// `prototype` — the cases where reading the property is observable at all.
12476    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12477        match &self.pending_new_target {
12478            Some(Value::Object(target)) => !target.ptr_eq(callee),
12479            Some(_) => true,
12480            None => false,
12481        }
12482    }
12483
12484    /// The symbol key for one of the engine's own hidden slots.
12485    ///
12486    /// Cached on the realm, so every object of a kind shares one key and a slot can be
12487    /// read back by name.
12488    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12489        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12490            return PropertyKey::Symbol(symbol.clone());
12491        }
12492        let symbol = Gc::new(
12493            self.heap,
12494            crate::value::JsSymbol::new(Some(name.to_string())),
12495        );
12496        self.realm
12497            .internal_slots
12498            .borrow_mut()
12499            .insert(name, Value::Symbol(symbol.clone()));
12500        PropertyKey::Symbol(symbol)
12501    }
12502
12503    /// Read a hidden slot, or `None` when the object has none of that name.
12504    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12505        let slots = self.realm.internal_slots.borrow();
12506        let Value::Symbol(symbol) = slots.get(name)? else {
12507            return None;
12508        };
12509        object
12510            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12511            .and_then(|property| property.value)
12512    }
12513
12514    /// Define a hidden slot.
12515    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12516        let key = self.internal_slot(name);
12517        object.define_key(&key, Property::with_attributes(value, false, false));
12518    }
12519
12520    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12521    ///
12522    /// The method is looked up on the value (through its prototype), called with no
12523    /// arguments, and its result becomes the iterator. A generator gets here through
12524    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12525    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12526    ///
12527    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12528    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12529    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12530    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12531    /// does, and a user-defined iterable works without a special case.
12532    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12533    /// `Symbol.iterator`.
12534    ///
12535    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12536    /// iterable is legal there, and each value it produces is simply already settled by
12537    /// the time the `await` around it runs.
12538    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12539        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12540        let method = self.read_field_key(value, &async_key)?;
12541        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12542        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12543        // is *present but not callable* is a TypeError — it does not mean "try the other
12544        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12545        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12546        // guard is there to catch.
12547        let absent = matches!(method, Value::Undefined | Value::Null);
12548        if !absent {
12549            let Value::Object(object) = &method else {
12550                return Err(Signal::Throw(
12551                    self.make_error("TypeError", "value is not iterable"),
12552                ));
12553            };
12554            if !object.is_callable() {
12555                return Err(Signal::Throw(
12556                    self.make_error("TypeError", "value is not iterable"),
12557                ));
12558            }
12559        }
12560        if absent {
12561            return self.get_iterator(value);
12562        }
12563        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12564        if !matches!(iterator, Value::Object(_)) {
12565            return Err(Signal::Throw(
12566                self.make_error("TypeError", "iterator is not an object"),
12567            ));
12568        }
12569        let next = self.read_field(&iterator, "next")?;
12570        Ok(Iterator {
12571            object: iterator,
12572            next,
12573        })
12574    }
12575
12576    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12577        let key = self.realm.well_known_key(WellKnown::Iterator);
12578        let method = self.read_field_key(value, &key)?;
12579        let Value::Object(function) = &method else {
12580            return Err(Signal::Throw(self.make_error(
12581                "TypeError",
12582                &format!("{} is not iterable", value.to_js_string()),
12583            )));
12584        };
12585        if !function.is_callable() {
12586            return Err(Signal::Throw(self.make_error(
12587                "TypeError",
12588                &format!("{} is not iterable", value.to_js_string()),
12589            )));
12590        }
12591        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12592        // The spec requires an object here; a primitive iterator has no `next` to call
12593        // and would fail one step later with a confusing message.
12594        if !matches!(iterator, Value::Object(_)) {
12595            return Err(Signal::Throw(
12596                self.make_error("TypeError", "iterator is not an object"),
12597            ));
12598        }
12599        let next = self.read_field(&iterator, "next")?;
12600        Ok(Iterator {
12601            object: iterator,
12602            next,
12603        })
12604    }
12605
12606    /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
12607    /// not iterable.
12608    ///
12609    /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
12610    /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
12611    /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
12612    /// was `[]`.
12613    pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
12614        let key = self.realm.well_known_key(WellKnown::Iterator);
12615        let method = self.read_field_key(value, &key)?;
12616        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12617            return Ok(None);
12618        }
12619        let iterator = self.get_iterator(value)?;
12620        let mut out = Vec::new();
12621        loop {
12622            let (element, done) = self.iterator_step(&iterator)?;
12623            if done {
12624                return Ok(Some(out));
12625            }
12626            out.push(element);
12627        }
12628    }
12629
12630    /// One step of an internal iterator: the value and whether it is exhausted.
12631    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12632        // A real iterator (`next` is a function) answers with a result object.
12633        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12634            let result =
12635                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12636            let Some(result) = result.as_object().cloned() else {
12637                return Err(self.type_error("iterator result is not an object"));
12638            };
12639            let done = self
12640                .get_property(&result, "done")?
12641                .is_some_and(|value| value.to_boolean());
12642            let value = self
12643                .get_property(&result, "value")?
12644                .unwrap_or(Value::Undefined);
12645            return Ok((value, done));
12646        }
12647        // An iterator whose `next` is not callable is treated as exhausted, which is
12648        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12649        // that are not iterable at all.
12650        Ok((Value::Undefined, true))
12651    }
12652
12653    /// `[...iterable]`: append everything the iterator yields, and answer the next
12654    /// index.
12655    ///
12656    /// This goes through the same iterator machinery `for-of` uses rather than copying
12657    /// an array's elements, because a spread source is any iterable: a string spreads
12658    /// into its characters and an array iterator spreads into its results. Handling
12659    /// only arrays made `[..."ab"]` come out empty with no error at all.
12660    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12661        let Some(target) = array.as_object().cloned() else {
12662            return Ok(0);
12663        };
12664        let start = target.array_length().unwrap_or(0);
12665        let mut added = 0;
12666        let iterator = self.get_iterator(iterable)?;
12667        loop {
12668            let (value, done) = self.iterator_step(&iterator)?;
12669            if done {
12670                break;
12671            }
12672            target.array_set(self.heap, start + added, value);
12673            added += 1;
12674        }
12675        Ok((start + added) as i32)
12676    }
12677
12678    /// How an uncaught exception is reported.
12679    ///
12680    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12681    /// with `ToString` — `js_std_dump_error` is three lines that end in
12682    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12683    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12684    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12685    ///
12686    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12687    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12688    /// `toString`"; it does call it, but only for objects of a class it does not know how
12689    /// to walk, and never for errors, arrays or plain objects.
12690    ///
12691    /// A printer that fails must not take the reporter down with it, so that case falls
12692    /// back to the `ToString` rendering.
12693    pub fn describe_exception(&mut self, value: &Value) -> String {
12694        match crate::print::sprint(self, value) {
12695            Ok(text) => text,
12696            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12697        }
12698    }
12699
12700    /// The file name of whatever is running, innermost frame first.
12701    ///
12702    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12703    /// innermost frame's file name, without distinguishing a module body from a plain
12704    /// script. `import()` uses it as the base for a relative specifier, which is why
12705    /// `import('./x.js')` inside a script resolves next to the script and not next to the
12706    /// process's working directory.
12707    pub fn script_or_module_name(&self) -> Option<String> {
12708        self.script_or_module_name_at(0)
12709    }
12710
12711    /// [`Interp::script_or_module_name`] `level` frames further out.
12712    ///
12713    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12714    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12715    /// frame without a file name is skipped rather than counted, because a native call
12716    /// pushes no frame of its own and so cannot be a level.
12717    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12718        self.frames
12719            .iter()
12720            .rev()
12721            .filter_map(|frame| frame.code.code.filename.clone())
12722            .nth(level)
12723    }
12724
12725    /// The current call stack, formatted the way `qjs` prints `error.stack`.
12726    ///
12727    /// One `    at name (file:line:col)` line per active frame, innermost first. The
12728    /// position is the one recorded for the instruction each frame is stopped on, which
12729    /// is why the compiler builds a pc-to-position table per function: without it a
12730    /// trace could only name the function, not the line inside it.
12731    ///
12732    /// A frame whose code has no positions prints just `(file)`, matching the
12733    /// reference's output for stripped bytecode.
12734    pub fn stack_trace(&self) -> String {
12735        self.stack_trace_skipping(0)
12736    }
12737
12738    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12739    fn stack_trace_skipping(&self, skip: usize) -> String {
12740        // One ordered list, innermost first, so `skip` counts the same thing whether the
12741        // frames it leaves out are native or bytecode. Indices rather than references: a
12742        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12743        let depth = self.frames.len();
12744        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12745        // A native entered while `at` bytecode frames were live was called *from* the
12746        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12747        // entered at the current depth are therefore innermost of all.
12748        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12749            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12750                if *at == wanted {
12751                    order.push((true, index));
12752                }
12753            }
12754        };
12755        push_natives(&mut order, depth);
12756        for index in (0..depth).rev() {
12757            order.push((false, index));
12758            push_natives(&mut order, index);
12759        }
12760        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12761        // barrier. Natives entered at exactly the barrier depth are the eval entry point
12762        // itself (`evalScript (native)`), and the reference leaves those out too.
12763        if let Some(barrier) = self.trace_barriers.last().copied() {
12764            order.retain(|(is_native, index)| match is_native {
12765                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12766                false => *index >= barrier,
12767            });
12768        }
12769
12770        let mut out = String::new();
12771        for (is_native, index) in order.into_iter().skip(skip) {
12772            match is_native {
12773                true => {
12774                    out.push_str("    at ");
12775                    let (native, _) = &self.native_frames[index];
12776                    let name = native
12777                        .own_property("name")
12778                        .and_then(|property| property.value)
12779                        .map(|value| value.to_js_string())
12780                        .unwrap_or_default();
12781                    out.push_str(&name);
12782                    out.push_str(" (native)\n");
12783                }
12784                false => {
12785                    let frame = &self.frames[index];
12786                    let code = &frame.code.code;
12787                    let file = code.filename.as_deref().unwrap_or("<input>");
12788                    // The name comes from the function *object*, not from the compiled code:
12789                    // an anonymous function expression is named by the property it is stored
12790                    // in (`{valueOf: function(){}}`), which only the object knows.
12791                    let bound_name = match &frame.callee {
12792                        Value::Object(object) => {
12793                            object
12794                                .own_property("name")
12795                                .and_then(|property| match property.value {
12796                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
12797                                        Some(text.to_string_lossy().into_owned())
12798                                    }
12799                                    _ => None,
12800                                })
12801                        }
12802                        _ => None,
12803                    };
12804                    // No callee object means the body was entered by the host, so the
12805                    // name has to come from the compiled code. Two cases differ:
12806                    //
12807                    // * an *unnamed* function of any kind — the reference reads the
12808                    //   `name` property, finds it empty, and prints `<anonymous>`;
12809                    // * a *module* body, which has no `name` property at all: the
12810                    //   reference builds that function object with `js_closure2` and
12811                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
12812                    //   so a trace reaching it also prints `<anonymous>` — while a
12813                    //   *script* body prints `<eval>`, its `name`.
12814                    let unnamed = code.name.is_empty() || code.module.is_some();
12815                    out.push_str("    at ");
12816                    match bound_name.as_deref() {
12817                        Some(name) => out.push_str(name),
12818                        None if unnamed => out.push_str("<anonymous>"),
12819                        None => out.push_str(&code.name),
12820                    }
12821                    match code.position_at(frame.at as u32) {
12822                        Some((line, column)) => {
12823                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
12824                        }
12825                        None => out.push_str(&format!(" ({file})\n")),
12826                    }
12827                }
12828            }
12829        }
12830        out
12831    }
12832
12833    /// Give an anonymous function the name of the property it is stored in.
12834    ///
12835    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
12836    /// enumerable and not configurable, and a function that already has a real name
12837    /// keeps it.
12838    ///
12839    /// "Already named" means a *non-empty* name: every function object is created with
12840    /// a `name` of `""` so the property exists on all of them, and treating that empty
12841    /// string as a name left every anonymous function nameless — which is how a stack
12842    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
12843    /// `SetFunctionName`, for a name that came from source text.
12844    fn set_function_name(&mut self, function: &Value, name: &str) {
12845        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
12846    }
12847
12848    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
12849    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
12850    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
12851        let Value::Object(object) = function else {
12852            return;
12853        };
12854        // `SetFunctionName` applies to *functions* and classes only, and only when they are
12855        // anonymous. Without the callability guard, `{value: someObject}` renamed
12856        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
12857        // on the right-hand side of a property. That is how a `zipKeyed` result object
12858        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
12859        // has no `NamedEvaluation` at all.
12860        if !object.is_callable() {
12861            return;
12862        }
12863        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
12864            && !existing.wtf8().is_empty()
12865        {
12866            return;
12867        }
12868        let text = self.string_wtf8(name.clone());
12869        object.define("name", Property::name_or_length(text));
12870    }
12871
12872    // -- global declarations -----------------------------------------------
12873
12874    /// Declare a global binding, creating its reference cell.
12875    /// Declare a `var` or function global, whose home is the global object.
12876    ///
12877    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
12878    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
12879    /// such as `print`, or a redeclaration — is left alone.
12880    pub fn declare_var_global(&mut self, name: &str) {
12881        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
12882        // global object is exactly the leak `typeof my_var === "undefined"` after
12883        // `eval("var my_var=2")` rules out.
12884        if let Some(scope) = self.eval_scope.as_mut() {
12885            scope.entry(name.to_string()).or_insert(Value::Undefined);
12886            return;
12887        }
12888        // A sloppy direct eval declares into its *caller's* variable environment. Doing
12889        // this on the global object instead made `eval("var c = 1")` inside a parameter
12890        // list overwrite a global `c`, and made two calls to the same function share one
12891        // binding.
12892        if let Some(cell) = self.declare_eval_local(name) {
12893            cell.set(Value::Undefined);
12894            return;
12895        }
12896        let global = self.realm.global.clone();
12897        if global.own_property(name).is_some() {
12898            return;
12899        }
12900        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
12901        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
12902        // whole point of that trick and what lets `Object.defineProperty` reshape it
12903        // afterwards. `eval_scope` is `Some` while an eval is running.
12904        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
12905        global.define(
12906            name,
12907            Property {
12908                value: Some(Value::Undefined),
12909                writable: true,
12910                enumerable: true,
12911                configurable: from_eval,
12912                ..Property::default()
12913            },
12914        );
12915    }
12916
12917    /// Declare a *lexical* global binding, which starts in its dead zone.
12918    ///
12919    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
12920    /// global object and is created when its initialiser runs.
12921    pub fn declare_global(&mut self, name: &str, is_const: bool) {
12922        if is_const {
12923            self.realm.lexical_consts.insert(name.to_string());
12924        }
12925        if !self.realm.globals.contains_key(name) {
12926            // `Uninitialized` rather than `Undefined`: the binding exists but is not
12927            // readable until its initialiser runs, and that is what `let x` before
12928            // `x = 1` has to observe.
12929            let cell = self.new_cell(Value::Uninitialized);
12930            self.realm.globals.insert(name.to_string(), cell);
12931            self.realm.declared.push(name.to_string());
12932        }
12933    }
12934}
12935
12936/// The bytecode and environment of a function object, if it is a bytecode function.
12937///
12938/// Extracted before a call so no borrow of the object is held across it.
12939fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
12940    function.with(|data| match &data.kind {
12941        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
12942        _ => None,
12943    })
12944}
12945
12946/// A native call target, extracted before the call so no borrow is held.
12947enum NativeCall {
12948    Native(NativeFn),
12949    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
12950    /// not hold that object's `RefCell` borrow.
12951    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
12952    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
12953    Bound {
12954        target: Value,
12955        this: Value,
12956        leading: Vec<Value>,
12957    },
12958    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
12959    Revoker(crate::object::ProxyRef),
12960    /// A promise's `resolve`.
12961    PromiseResolve(Gc<JsObject>),
12962    /// A promise's `reject`.
12963    PromiseReject(Gc<JsObject>),
12964    /// The executor `NewPromiseCapability(C)` hands a user constructor.
12965    CapabilityExecutor {
12966        state: Gc<JsObject>,
12967    },
12968    /// One leg of a `then` that settles through a user capability.
12969    ThenShim {
12970        handler: Option<Value>,
12971        resolve: Value,
12972        reject: Value,
12973        fulfilled: bool,
12974    },
12975    /// One continuation of an `await`.
12976    AwaitResume {
12977        coroutine: Gc<JsObject>,
12978        promise: Gc<JsObject>,
12979        kind: ResumeKind,
12980    },
12981    /// One element of a `Promise` combinator settling.
12982    CombinatorSettle {
12983        state: Gc<JsObject>,
12984        index: usize,
12985        fulfilled: bool,
12986    },
12987    /// One of `Promise.prototype.finally`'s two shims.
12988    FinallyShim {
12989        callback: Option<Value>,
12990        fulfilled: bool,
12991        constructor: Value,
12992    },
12993    /// Settle a promise with a fixed outcome.
12994    SettlePromise {
12995        promise: Gc<JsObject>,
12996        value: Value,
12997        rejected: bool,
12998    },
12999    /// Continue an async generator after its `await` settled.
13000    GeneratorResume {
13001        generator: Gc<JsObject>,
13002        promise: Gc<JsObject>,
13003        kind: ResumeKind,
13004    },
13005    /// Read a module namespace's binding out of its cell.
13006    ModuleBinding(Gc<Cell>),
13007    /// Finish a completed async generator's `return(v)` once `v` has settled.
13008    CompletedReturn {
13009        generator: Gc<JsObject>,
13010        promise: Gc<JsObject>,
13011        rejected: bool,
13012    },
13013    /// Answer a pending async-generator method with `{value, done}`.
13014    YieldResult {
13015        generator: Gc<JsObject>,
13016        promise: Gc<JsObject>,
13017        done: bool,
13018    },
13019    /// One step of `AsyncDisposableStack.disposeAsync`.
13020    DisposeStep {
13021        remaining: Gc<JsObject>,
13022        promise: Gc<JsObject>,
13023        error: Value,
13024        rejected: bool,
13025    },
13026}
13027
13028/// What a store does when the object refuses the write.
13029#[derive(Clone, Copy, PartialEq, Eq)]
13030pub enum DeleteFailure {
13031    /// Raise a `TypeError`, which is what strict mode and every built-in does.
13032    Throw,
13033    /// Ignore the write, which is what a sloppy-mode assignment does.
13034    Ignore,
13035}
13036
13037/// Whether `object` is a `Date` instance, by the class tag it carries.
13038///
13039/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13040/// builtins module depending on the interpreter's conversion order.
13041fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13042    interp
13043        .internal_get(object, "_class")
13044        .is_some_and(|value| value.to_js_string() == "Date")
13045}
13046
13047/// Which type `ToPrimitive` prefers when it converts an object.
13048#[derive(Clone, Copy, PartialEq, Eq)]
13049pub enum Hint {
13050    /// The default hint, which behaves like [`Hint::Number`].
13051    Default,
13052    /// `Number(obj)` and the arithmetic operators.
13053    Number,
13054    /// `String(obj)` and `ToPropertyKey`.
13055    String,
13056}
13057
13058/// Which table a binding slot indexes, for the messages that name it.
13059#[derive(Clone, Copy)]
13060enum VarSlot {
13061    Loc,
13062    Closure,
13063}
13064
13065/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13066fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13067    Ok(this)
13068}
13069
13070/// An internal iterator: the sequence plus a cursor.
13071pub(crate) struct Iterator {
13072    pub(crate) object: Value,
13073    pub(crate) next: Value,
13074}
13075
13076/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13077/// and plain `a` for a method.
13078///
13079/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13080/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13081/// reads `at get a (file:1:2)`.
13082/// The same prefixing, for a name that may hold an unpaired surrogate.
13083fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13084    let prefix = match flags & 3 {
13085        1 => "get ",
13086        2 => "set ",
13087        _ => return key.clone(),
13088    };
13089    let mut units: Vec<u16> = prefix.encode_utf16().collect();
13090    units.extend_from_slice(&key.to_units());
13091    crate::value::Wtf8::from_units(&units)
13092}
13093
13094fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13095    match flags & 3 {
13096        1 => format!("get {key}"),
13097        2 => format!("set {key}"),
13098        _ => key.to_string(),
13099    }
13100}
13101
13102/// Define a method or accessor property, per the `define_method` flag byte.
13103///
13104/// The low two bits pick value/getter/setter and bit 2 marks the property
13105/// enumerable.
13106///
13107/// A getter and a setter arrive as two separate `define_method` instructions, and the
13108/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13109/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13110/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13111/// `JS_DefineProperty`, which leaves the other half alone.
13112fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13113    let enumerable = flags & 4 != 0;
13114    let kind = flags & 3;
13115    let existing = object.own_property_key(key);
13116    let property = match kind {
13117        1 => Property {
13118            getter: Some(function),
13119            // The setter half, if this literal already defined one.
13120            setter: existing
13121                .filter(Property::is_accessor)
13122                .and_then(|p| p.setter),
13123            enumerable,
13124            configurable: true,
13125            ..Property::default()
13126        },
13127        2 => Property {
13128            getter: existing
13129                .filter(Property::is_accessor)
13130                .and_then(|p| p.getter),
13131            setter: Some(function),
13132            enumerable,
13133            configurable: true,
13134            ..Property::default()
13135        },
13136        _ => Property {
13137            value: Some(function),
13138            writable: true,
13139            enumerable,
13140            configurable: true,
13141            ..Property::default()
13142        },
13143    };
13144    object.define_key(key, property);
13145}
13146
13147// ---------------------------------------------------------------------------
13148// Operand decoding
13149// ---------------------------------------------------------------------------
13150
13151/// How `print` renders a value: the reference's `JS_PrintValue`.
13152///
13153/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13154/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13155/// The format is reproduced closely because the test suite compares output text:
13156///
13157/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13158/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13159/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13160/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13161///   end print as `<N empty item(s)>`;
13162/// * a string is quoted inside a container but raw at the top level, which is why
13163///   `print("x")` and `print(["x"])` differ.
13164pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13165    // A string argument is printed raw: `js_print` converts it with `ToString`
13166    // instead of dumping it, and the quoting only appears inside a container.
13167    if let Value::String(text) = value {
13168        return text.to_string_lossy().into_owned();
13169    }
13170    let mut printer = Printer {
13171        interp,
13172        out: String::new(),
13173        stack: Vec::new(),
13174    };
13175    printer.value(value, 0);
13176    printer.out
13177}
13178
13179/// The internal class name an object carries, when it has one.
13180fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13181    interp
13182        .internal_get(object, "_class")
13183        .map(|value| value.to_js_string())
13184}
13185
13186/// A string property, looked up the way `GetProperty` does: own first, then the
13187/// prototype chain. Needed because the print formatter holds the interpreter
13188/// immutably and so cannot run getters.
13189fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13190    let mut current = Some(object.clone());
13191    // Bounded, because a prototype cycle would otherwise loop forever.
13192    for _ in 0..100 {
13193        let node = current?;
13194        if let Some(property) = node.own_property(name)
13195            && let Some(value) = property.value
13196        {
13197            return Some(value.to_js_string());
13198        }
13199        current = node.with(|data| data.proto.clone());
13200    }
13201    None
13202}
13203
13204/// The `JS_PrintValue` state: output, and the objects currently being printed.
13205struct Printer<'a, 'rt> {
13206    /// Kept for the class-name lookups that typed arrays and `Date` will need.
13207    #[allow(dead_code)]
13208    interp: &'a Interp<'rt>,
13209    out: String,
13210    stack: Vec<Gc<JsObject>>,
13211}
13212
13213impl Printer<'_, '_> {
13214    /// Depth past which a container is summarised by its class name.
13215    const MAX_DEPTH: usize = 2;
13216
13217    fn value(&mut self, value: &Value, level: usize) {
13218        match value {
13219            Value::Undefined
13220            | Value::Uninitialized
13221            | Value::Hole
13222            | Value::CatchOffset(_)
13223            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13224            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13225            // The printer writes a bigint the way the language spells one, so a dump is
13226            // unambiguous about which kind of number it is showing.
13227            Value::BigInt(big) => {
13228                self.out.push_str(&big.to_decimal_string());
13229                self.out.push('n');
13230            }
13231            Value::Null => self.out.push_str("null"),
13232            Value::Bool(true) => self.out.push_str("true"),
13233            Value::Bool(false) => self.out.push_str("false"),
13234            Value::Int(number) => self.out.push_str(&number.to_string()),
13235            Value::Float(number) => {
13236                self.out
13237                    .push_str(&crate::value::number_to_string_for_print(*number));
13238            }
13239            Value::String(text) => self.print_string(&text.to_string_lossy()),
13240            Value::Object(object) => self.object(object, level),
13241        }
13242    }
13243
13244    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13245        // A cycle is reported rather than followed; the index is where the object
13246        // already sits in the print stack, which is what the reference shows.
13247        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13248            self.out.push_str(&format!("[circular {index}]"));
13249            return;
13250        }
13251        if object.is_callable() {
13252            let name = object
13253                .own_property("name")
13254                .and_then(|property| property.value)
13255                .map(|value| value.to_js_string())
13256                .unwrap_or_default();
13257            if name.is_empty() {
13258                self.out.push_str("[Function (anonymous)]");
13259            } else {
13260                self.out.push_str(&format!("[Function {name}]"));
13261            }
13262            return;
13263        }
13264        if level >= Self::MAX_DEPTH {
13265            let class = if object.is_array() { "Array" } else { "Object" };
13266            self.out.push_str(&format!("[{class}]"));
13267            return;
13268        }
13269        // `Date` and `Error` print as themselves rather than as bags of properties:
13270        // the ISO string, and `Name: message` followed by the trace.
13271        if let Some(class) = class_of(self.interp, object) {
13272            if class == "Date" {
13273                self.date(object);
13274                return;
13275            }
13276            if class == "Error" {
13277                self.error(object);
13278                return;
13279            }
13280        }
13281        self.stack.push(object.clone());
13282        if object.is_array() {
13283            self.array(object, level);
13284        } else {
13285            self.plain_object(object, level);
13286        }
13287        self.stack.pop();
13288    }
13289
13290    /// A Date prints as its ISO string; an invalid one falls through to the plain
13291    /// object form, the way the reference falls back when `toISOString` throws.
13292    fn date(&mut self, object: &Gc<JsObject>) {
13293        let value = self
13294            .interp
13295            .internal_get(object, "_date_value")
13296            .map(|value| value.to_number());
13297        match value.and_then(crate::builtins::date::iso_string) {
13298            Some(text) => self.out.push_str(&text),
13299            None => self.plain_object(object, 0),
13300        }
13301    }
13302
13303    /// `Name: message`, then the trace with its trailing newline removed.
13304    fn error(&mut self, object: &Gc<JsObject>) {
13305        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13306        self.out.push_str(&name);
13307        if let Some(message) = inherited(object, "message")
13308            && !message.is_empty()
13309        {
13310            self.out.push_str(": ");
13311            self.out.push_str(&message);
13312        }
13313        if let Some(stack) = inherited(object, "stack") {
13314            self.out.push('\n');
13315            self.out.push_str(stack.trim_end_matches('\n'));
13316        }
13317    }
13318
13319    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13320        let elements = object.array_elements().unwrap_or_default();
13321        self.out.push_str("[ ");
13322        // An interior hole means the array is "sparse": the reference prints those
13323        // as `index: value` pairs and says nothing about the holes themselves, while
13324        // a hole run at the end becomes a single `<N empty items>` note.
13325        let last_present = elements
13326            .iter()
13327            .rposition(|value| !matches!(value, Value::Hole));
13328        let has_interior_hole = match last_present {
13329            Some(last) => elements[..last]
13330                .iter()
13331                .any(|value| matches!(value, Value::Hole)),
13332            None => false,
13333        };
13334        let mut first = true;
13335        if has_interior_hole {
13336            let mut index = 0;
13337            while index < elements.len() {
13338                let value = &elements[index];
13339                if matches!(value, Value::Hole) {
13340                    index += 1;
13341                    continue;
13342                }
13343                if !first {
13344                    self.out.push_str(", ");
13345                }
13346                first = false;
13347                self.out.push_str(&format!("{index}: "));
13348                self.value(value, level + 1);
13349                index += 1;
13350            }
13351        } else {
13352            for (index, value) in elements.iter().enumerate() {
13353                if matches!(value, Value::Hole) {
13354                    continue;
13355                }
13356                if !first {
13357                    self.out.push_str(", ");
13358                }
13359                first = false;
13360                let _ = index;
13361                self.value(value, level + 1);
13362            }
13363            if let Some(last) = last_present {
13364                let trailing = elements.len() - last - 1;
13365                if trailing > 0 {
13366                    if !first {
13367                        self.out.push_str(", ");
13368                    }
13369                    self.out.push_str(&format!(
13370                        "<{trailing} empty item{}>",
13371                        if trailing > 1 { "s" } else { "" }
13372                    ));
13373                }
13374            } else if !elements.is_empty() {
13375                let count = elements.len();
13376                self.out.push_str(&format!(
13377                    "<{count} empty item{}>",
13378                    if count > 1 { "s" } else { "" }
13379                ));
13380            }
13381        }
13382        self.out.push_str(" ]");
13383    }
13384
13385    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13386        self.out.push_str("{ ");
13387        let mut first = true;
13388        for key in object.own_keys() {
13389            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13390                continue;
13391            };
13392            if !property.enumerable {
13393                continue;
13394            }
13395            if !first {
13396                self.out.push_str(", ");
13397            }
13398            first = false;
13399            self.out
13400                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13401                    &key.to_string_lossy(),
13402                )));
13403            self.out.push_str(": ");
13404            // An accessor has no value to dump; the reference names the half that
13405            // exists instead of calling it.
13406            if property.is_accessor() {
13407                let text = match (property.getter.is_some(), property.setter.is_some()) {
13408                    (true, true) => "[Getter/Setter]",
13409                    (false, true) => "[Setter]",
13410                    _ => "[Getter]",
13411                };
13412                self.out.push_str(text);
13413            } else {
13414                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13415            }
13416        }
13417        self.out.push_str(" }");
13418    }
13419
13420    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13421    fn print_string(&mut self, text: &str) {
13422        self.out.push('"');
13423        for character in text.chars() {
13424            match character {
13425                '"' => self.out.push_str("\\\""),
13426                '\\' => self.out.push_str("\\\\"),
13427                '\n' => self.out.push_str("\\n"),
13428                '\r' => self.out.push_str("\\r"),
13429                '\t' => self.out.push_str("\\t"),
13430                c if (c as u32) < 0x20 => {
13431                    self.out.push_str(&format!("\\u{:04x}", c as u32));
13432                }
13433                c => self.out.push(c),
13434            }
13435        }
13436        self.out.push('"');
13437    }
13438}
13439
13440/// How `print` renders a value.
13441///
13442/// `ToString`, except that negative zero keeps its sign — the reference's host
13443/// printer does that while `String(-0)` is `"0"`.
13444pub fn display(value: &Value) -> String {
13445    match value {
13446        Value::Float(number) => crate::value::number_to_string_for_print(*number),
13447        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13448            "undefined".to_string()
13449        }
13450        other => other.to_js_string(),
13451    }
13452}
13453
13454// ---------------------------------------------------------------------------
13455// Numeric operators
13456// ---------------------------------------------------------------------------
13457
13458/// `a + b` keeping the `Int` representation when it fits.
13459fn add_numbers(left: Value, right: Value) -> Value {
13460    match (&left, &right) {
13461        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13462            Some(sum) => Value::Int(sum),
13463            None => Value::Float(*a as f64 + *b as f64),
13464        },
13465        _ => Value::Float(left.to_number() + right.to_number()),
13466    }
13467}
13468
13469/// The arithmetic operators other than `+`, which needs string concatenation.
13470fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13471    use Opcode::*;
13472    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13473    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13474    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13475    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13476        return Ok(match op {
13477            And => Value::Int(x & y),
13478            Or => Value::Int(x | y),
13479            Xor => Value::Int(x ^ y),
13480            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13481            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13482            Shr => match (*x as u32) >> ((*y as u32) & 31) {
13483                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13484                shifted => Value::Float(shifted as f64),
13485            },
13486            Sub => match x.checked_sub(*y) {
13487                Some(value) => Value::Int(value),
13488                None => Value::Float(*x as f64 - *y as f64),
13489            },
13490            _ => return arithmetic_slow(op, left, right),
13491        });
13492    }
13493    arithmetic_slow(op, left, right)
13494}
13495
13496/// [`arithmetic`] for everything the integer fast path above does not take.
13497fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13498    use Opcode::*;
13499    let (a, b) = (left.to_number(), right.to_number());
13500    Ok(match op {
13501        Sub => match (&left, &right) {
13502            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13503                Some(value) => Value::Int(value),
13504                None => Value::Float(a - b),
13505            },
13506            _ => Value::Float(a - b),
13507        },
13508        Mul => Value::Float(a * b),
13509        Div => Value::Float(a / b),
13510        Mod => Value::Float(js_mod(a, b)),
13511        Pow => Value::Float(a.powf(b)),
13512        And => Value::Int(left.to_int32() & right.to_int32()),
13513        Or => Value::Int(left.to_int32() | right.to_int32()),
13514        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13515        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13516        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13517        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13518        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13519        // fits the small-integer representation stays an `Int`; the rest become a
13520        // float, which is how the reference keeps `n >>> 0` non-negative.
13521        Shr => {
13522            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13523            match i32::try_from(shifted) {
13524                Ok(value) => Value::Int(value),
13525                Err(_) => Value::Float(shifted as f64),
13526            }
13527        }
13528        _ => Value::Float(a),
13529    })
13530}
13531
13532/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13533///
13534/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13535/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13536/// slow path where the rules live.
13537fn is_number(value: &Value) -> bool {
13538    matches!(value, Value::Int(_) | Value::Float(_))
13539}
13540
13541/// The `Value::Bool` a comparison operator answers for `ordering`.
13542///
13543/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13544/// false for it, including `<=` and `>=`.
13545fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13546    use Opcode::*;
13547    let answer = match (op, ordering) {
13548        (_, None) => false,
13549        (Lt, Some(ordering)) => ordering.is_lt(),
13550        (Lte, Some(ordering)) => ordering.is_le(),
13551        (Gt, Some(ordering)) => ordering.is_gt(),
13552        (Gte, Some(ordering)) => ordering.is_ge(),
13553        _ => false,
13554    };
13555    Value::Bool(answer)
13556}
13557
13558/// `%`, which follows the sign of the dividend rather than Rust's.
13559fn js_mod(left: f64, right: f64) -> f64 {
13560    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13561        return f64::NAN;
13562    }
13563    if right.is_infinite() {
13564        return left;
13565    }
13566    let remainder = left % right;
13567    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13568    // the spec makes the sign match the dividend.
13569    if remainder == 0.0 {
13570        0.0f64.copysign(left)
13571    } else {
13572        remainder
13573    }
13574}
13575
13576fn negate(value: Value) -> Value {
13577    match value {
13578        Value::Int(0) => Value::Float(-0.0),
13579        Value::Int(i) => Value::Int(-i),
13580        other => Value::Float(-other.to_number()),
13581    }
13582}
13583
13584fn increment(value: Value) -> Value {
13585    match value {
13586        Value::Int(i) => match i.checked_add(1) {
13587            Some(next) => Value::Int(next),
13588            None => Value::Float(i as f64 + 1.0),
13589        },
13590        other => Value::Float(other.to_number() + 1.0),
13591    }
13592}
13593
13594fn decrement(value: Value) -> Value {
13595    match value {
13596        Value::Int(i) => match i.checked_sub(1) {
13597            Some(next) => Value::Int(next),
13598            None => Value::Float(i as f64 - 1.0),
13599        },
13600        other => Value::Float(other.to_number() - 1.0),
13601    }
13602}
13603
13604/// Compare a `BigInt` with an `f64` on their mathematical values.
13605///
13606/// Neither side is rounded to the other's precision: the number is split into its integer
13607/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13608/// when the integer parts are equal. An infinite value is larger than every bigint.
13609fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13610    use std::cmp::Ordering;
13611    if number.is_nan() {
13612        return None;
13613    }
13614    if number.is_infinite() {
13615        return Some(if number > 0.0 {
13616            Ordering::Less
13617        } else {
13618            Ordering::Greater
13619        });
13620    }
13621    let truncated = number.trunc();
13622    // A number wider than `i128` still has an exact integer part, but no bigint form we can
13623    // build cheaply; the sign of the difference is all that is needed, so compare against
13624    // the bigint's own magnitude instead.
13625    if truncated.abs() >= 1.7e38 {
13626        let big_as_f64 = big.to_f64();
13627        return big_as_f64.partial_cmp(&number);
13628    }
13629    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13630    match big.cmp(&integer) {
13631        Ordering::Equal => {
13632            // Same integer part: the fraction decides, and a negative number's fraction is
13633            // below the integer (`-1.5` truncates to `-1`).
13634            if number > truncated {
13635                Some(Ordering::Less)
13636            } else if number < truncated {
13637                Some(Ordering::Greater)
13638            } else {
13639                Some(Ordering::Equal)
13640            }
13641        }
13642        other => Some(other),
13643    }
13644}