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    /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
129    ///
130    /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
131    /// whole `ThrowTypeError/` directory finds it through
132    /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
133    /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
134    /// Creating a fresh one per property would make
135    /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
136    /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
137    pub throw_type_error: Option<Gc<JsObject>>,
138    /// `%GeneratorPrototype%`, the prototype of every generator object.
139    pub generator_proto: Gc<JsObject>,
140    /// `Promise.prototype`, the prototype of every promise.
141    pub promise_proto: Option<Gc<JsObject>>,
142    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
143    pub async_generator_proto: Option<Gc<JsObject>>,
144    /// `Symbol.prototype`.
145    pub symbol_proto: Option<Gc<JsObject>>,
146    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
147    /// `_date_value`.
148    ///
149    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
150    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
151    /// language does not have and `new Error()` listed `_class` beside `message` and
152    /// `stack` — and a caller that copies every own property (which
153    /// `Object.create(null, props)` effectively does) tried to write an internal name and
154    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
155    /// and `JSON.stringify`, while remaining an ordinary traced property.
156    ///
157    /// `RefCell` because interning is memoisation rather than observable state: filling the
158    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
159    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
160    /// built while reporting a failure must not require an exclusive borrow.
161    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
162
163    /// The `Symbol.for` registry: `key -> symbol`.
164    ///
165    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
166    /// symbol every time within one script while a fresh realm starts empty.
167    pub symbol_registry: BTreeMap<String, Value>,
168    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
169    pub regexp_proto: Option<Gc<JsObject>>,
170    /// The `RegExp` constructor.
171    pub regexp_ctor: Option<Gc<JsObject>>,
172    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
173    ///
174    /// The prototype rather than the constructor on purpose: a script that replaces
175    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
176    /// error wrapping, which the `using` test suite checks explicitly.
177    pub suppressed_error_proto: Option<Gc<JsObject>>,
178    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
179    pub disposable_stack_proto: Option<Gc<JsObject>>,
180    /// `Map.prototype`.
181    pub map_proto: Option<Gc<JsObject>>,
182    /// `Set.prototype`.
183    pub set_proto: Option<Gc<JsObject>>,
184    /// Every live `FinalizationRegistry`, held weakly.
185    ///
186    /// The cleanup callback has to run from a *safe point* — a place where script is not
187    /// already executing and no engine borrow is held — and the collector cannot enumerate
188    /// heap objects by type. Registering each registry here gives the drain a list to walk.
189    ///
190    /// The handles are weak on purpose: a registry the script dropped must be collectable,
191    /// and it must not be resurrected merely because the drain knew about it. Entries whose
192    /// target has expired are swept out as the drain walks, so the vector does not grow
193    /// without bound in a program that creates many short-lived registries.
194    pub finalization_registries: Vec<WeakGc<JsObject>>,
195    /// `ArrayBuffer.prototype`.
196    pub array_buffer_proto: Option<Gc<JsObject>>,
197    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
198    pub typed_array_proto: Option<Gc<JsObject>>,
199    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
200    ///
201    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
202    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
203    /// `"Object"` and `r instanceof Int32Array` is false.
204    pub typed_array_protos: Vec<Gc<JsObject>>,
205    /// `DataView.prototype`.
206    pub data_view_proto: Option<Gc<JsObject>>,
207    /// The `AsyncDisposableStack` prototype.
208    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
209    /// `Iterator.prototype`.
210    pub iterator_proto: Option<Gc<JsObject>>,
211    /// The `Iterator` constructor itself.
212    ///
213    /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
214    /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
215    /// place it can live is the realm.
216    pub iterator_ctor: Option<Gc<JsObject>>,
217    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
218    ///
219    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
220    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
221    /// `[object Iterator Helper]`).
222    pub iterator_helper_proto: Option<Gc<JsObject>>,
223    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
224    /// that was not already an `Iterator`.
225    ///
226    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
227    /// untouched and does *not* override `@@toStringTag`, so
228    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
229    pub iterator_wrap_proto: Option<Gc<JsObject>>,
230    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
231    pub generator_function_proto: Option<Gc<JsObject>>,
232    /// `%AsyncFunction.prototype%`.
233    pub async_function_proto: Option<Gc<JsObject>>,
234    /// `%AsyncGeneratorFunction.prototype%`.
235    pub async_generator_function_proto: Option<Gc<JsObject>>,
236    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
237    ///
238    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
239    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
240    /// prototype per iterator made every array iterator's prototype distinct.
241    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
242    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
243    ///
244    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
245    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
246    /// both faster and impossible to break from a script.
247    well_known_symbols: WellKnownSymbols,
248    /// The classes the host registered, and the prototype each one hands its instances.
249    pub host_classes: HostClasses,
250}
251
252/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
253///
254/// One per realm, because a class id is only meaningful within the runtime that handed it
255/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
256/// a host class cannot collide.
257pub struct HostClasses {
258    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
259    /// `JS_GetOpaque(val, 0)` has to match nothing.
260    next_id: u32,
261    /// What each registered class does.
262    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
263    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
264    ///
265    /// A strong reference, so the prototype a host installed outlives every script
266    /// reference to it — which is what `JS_SetClassProto` promises.
267    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
268}
269
270impl HostClasses {
271    fn new() -> HostClasses {
272        HostClasses {
273            next_id: 1,
274            defs: std::collections::BTreeMap::new(),
275            protos: std::collections::BTreeMap::new(),
276        }
277    }
278
279    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
280    pub fn register(&mut self, def: ClassDef) -> ClassId {
281        let id = ClassId::from_raw(self.next_id);
282        self.next_id += 1;
283        self.defs.insert(id, std::rc::Rc::new(def));
284        id
285    }
286
287    /// Register `def` under an id the caller already has (`JS_NewClass`).
288    ///
289    /// The C API splits "get an id" from "register a class" because a module may be
290    /// initialised lazily; registering twice under one id replaces the definition, and an
291    /// object created under the old one keeps the old behaviour, since it carries its own
292    /// reference.
293    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
294        if !id.is_valid() {
295            return false;
296        }
297        // Keep the counter past any id handed out explicitly, so a later `register` cannot
298        // reuse one.
299        self.next_id = self.next_id.max(id.get() + 1);
300        self.defs.insert(id, std::rc::Rc::new(def));
301        true
302    }
303
304    /// What `id` was registered with.
305    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
306        self.defs.get(&id).cloned()
307    }
308
309    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
310    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
311        self.protos.insert(id, proto);
312    }
313
314    /// The prototype installed for `id`, if the host installed one.
315    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
316        self.protos.get(&id).cloned()
317    }
318
319    /// How many classes the host registered.
320    pub fn len(&self) -> usize {
321        self.defs.len()
322    }
323
324    /// Whether no class has been registered.
325    pub fn is_empty(&self) -> bool {
326        self.defs.is_empty()
327    }
328}
329
330impl Default for HostClasses {
331    fn default() -> HostClasses {
332        HostClasses::new()
333    }
334}
335
336/// One binding of the frame that called `eval`, so the eval'd code can read and
337/// write it by name.
338struct EvalBinding {
339    /// The name it was declared with.
340    name: String,
341    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
342    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
343    /// a function that declares `a` must find that `a`.
344    frame: usize,
345    /// Which table of that frame it lives in.
346    slot: EvalSlot,
347    /// The slot index within that table.
348    index: usize,
349}
350
351/// Which table of a frame an [`EvalBinding`] indexes.
352#[derive(Clone, Copy)]
353enum EvalSlot {
354    Arg,
355    Local,
356}
357
358/// One activation record.
359struct Frame {
360    /// The bytecode being run.
361    code: Gc<CompiledCode>,
362    /// The cells this closure captured.
363    env: Gc<ClosureEnv>,
364    /// The `this` binding.
365    this: Value,
366    /// Argument slots, sized to the declared parameter count.
367    args: Vec<Value>,
368    /// How many values the caller actually passed, which is what `arguments.length`
369    /// reports and what `...rest` slices from.
370    passed_count: usize,
371    /// The passed values, **only when they do not fit in [`Self::args`]**.
372    ///
373    /// `args` is sized to the declared parameters, so a call that passes no more than
374    /// that already holds every passed value in its first `passed_count` slots — copying
375    /// them here as well was two writes and a buffer per call, on the hottest path in
376    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
377    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
378    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
379    /// its own copy.
380    ///
381    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
382    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
383    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
384    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
385    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
386    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
387    #[allow(clippy::box_collection)]
388    passed_overflow: Option<Box<Vec<Value>>>,
389    /// Local slots.
390    locals: Vec<Value>,
391    /// Reference cells for this frame's own captured bindings.
392    cells: Vec<Gc<Cell>>,
393    /// The operand stack.
394    stack: Vec<Value>,
395    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
396    local_vars: Option<Gc<LocalVars>>,
397
398    /// Index of the next instruction, not a byte offset.
399    ///
400    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
401    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
402    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
403    /// `Frame`, and `frames.push` copies the whole struct on every call.
404    pc: usize,
405    /// Byte offset of the instruction being executed, which is what a stack trace
406    /// reports. `pc` has already moved past it by the time an instruction runs.
407    ///
408    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
409    at: usize,
410    /// The callee, so a native builtin can tell which constructor it is.
411    callee: Value,
412    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
413    new_target: Value,
414    /// What this frame costs against [`Interp::stack_limit`], in bytes.
415    ///
416    /// Cached rather than recomputed because it is charged on every call and a call is the
417    /// hottest thing in the interpreter.
418    cost: usize,
419    /// [`Interp::stack_used`] before this frame was pushed.
420    ///
421    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
422    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
423    /// leave the counter wrong. There are eight places that drop frames; one subtraction
424    /// forgotten in any of them would leak budget until the depth limit moved.
425    stack_base: usize,
426    /// Whether this frame's body ended in a `tail_call`.
427    ///
428    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
429    /// with its own frame just like `call` does and only skips storing the result
430    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
431    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
432    /// pushed as usual, and this marker makes its return value the *caller's* return
433    /// value without running the instructions after the call.
434    tail: bool,
435}
436
437impl Frame {
438    /// Read a local slot, taking the frame as `self`.
439    ///
440    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
441    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
442    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
443    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
444    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
445    #[inline]
446    fn read_loc(&self, slot: usize) -> Value {
447        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
448        if cell == -1 {
449            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
450        }
451        match self.cells.get(cell as usize) {
452            Some(cell) => cell.get(),
453            None => Value::Undefined,
454        }
455    }
456
457    /// [`Self::read_loc`] for an argument slot.
458    #[inline]
459    fn read_arg(&self, slot: usize) -> Value {
460        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
461        if cell == -1 {
462            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
463        }
464        match self.cells.get(cell as usize) {
465            Some(cell) => cell.get(),
466            None => Value::Undefined,
467        }
468    }
469
470    /// The values the caller actually passed, which is what `arguments` exposes.
471    ///
472    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
473    fn passed(&self) -> &[Value] {
474        match &self.passed_overflow {
475            Some(values) => values,
476            None => &self.args[..self.passed_count],
477        }
478    }
479
480    /// The decoded instructions of the function this frame runs.
481    ///
482    /// A method rather than `frame.code.insns` at the call site so that the borrow is
483    /// obviously of the frame — the dispatch loop holds one across a `get`.
484    fn insns(&self) -> &[crate::insn::Insn] {
485        &self.code.insns
486    }
487}
488
489impl js_gc::Trace for Frame {
490    fn trace(&self, tracer: &mut js_gc::Tracer) {
491        self.code.trace(tracer);
492        self.env.trace(tracer);
493        self.this.trace(tracer);
494        for value in &self.args {
495            value.trace(tracer);
496        }
497        for value in self.passed() {
498            value.trace(tracer);
499        }
500        for value in &self.locals {
501            value.trace(tracer);
502        }
503        for cell in &self.cells {
504            cell.trace(tracer);
505        }
506        if let Some(local_vars) = &self.local_vars {
507            tracer.visit(local_vars);
508        }
509        for value in &self.stack {
510            value.trace(tracer);
511        }
512        self.callee.trace(tracer);
513        self.new_target.trace(tracer);
514    }
515}
516
517/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
518/// emitted `if_false` treats as "keep going".
519/// How many finished frames' value buffers are kept for reuse.
520const RECYCLE_SLOTS: usize = 8;
521
522/// The largest buffer worth keeping. See [`Interp::free_values`].
523const RECYCLE_MAX_CAPACITY: usize = 4096;
524
525const RESUME_NEXT: i32 = 0;
526/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
527/// generator fall into its `return_async`.
528const RESUME_RETURN: i32 = 1;
529/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
530/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
531/// must forward the exception into the inner iterator rather than finish.
532const RESUME_THROW: i32 = 2;
533
534/// One microtask.
535///
536/// The queue holds *data* rather than closures because its contents are GC values: a
537/// closure would be invisible to the collector, and a pending reaction is exactly the
538/// kind of thing that must keep its handlers and its promise alive.
539pub enum Job {
540    /// A `then` reaction about to run.
541    Reaction {
542        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
543        handler: Option<Value>,
544        /// The value or reason to call it with.
545        argument: Value,
546        /// Whether the source promise rejected, which decides the pass-through kind.
547        rejected: bool,
548        /// The promise the answer settles.
549        promise: Gc<JsObject>,
550    },
551    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
552    Thenable {
553        /// The `then` that was found on the value.
554        then: Value,
555        /// The thenable itself, which becomes `then`'s `this`.
556        value: Value,
557        /// The promise being resolved.
558        promise: Gc<JsObject>,
559    },
560    /// A pending `import(specifier)`.
561    Import {
562        /// The specifier, already converted to a string.
563        specifier: String,
564        /// The module that asked, which the specifier resolves against.
565        referrer: String,
566        /// The promise `import()` handed back.
567        promise: Gc<JsObject>,
568    },
569    /// An async generator resuming after the value it awaited settled.
570    GeneratorResume {
571        /// The async generator to continue.
572        generator: Gc<JsObject>,
573        /// The promise the pending method returned.
574        promise: Gc<JsObject>,
575        /// Whether this delivers the value or raises the reason.
576        kind: ResumeKind,
577        /// The settled value, or the rejection reason.
578        value: Value,
579    },
580    /// An async function resuming after the value it awaited settled.
581    Resume {
582        /// The body, parked in a coroutine.
583        coroutine: Gc<JsObject>,
584        /// The promise the async function handed its caller.
585        promise: Gc<JsObject>,
586        /// Whether this resumption delivers a value or raises one.
587        kind: ResumeKind,
588        /// The settled value, or the rejection reason.
589        value: Value,
590    },
591}
592
593/// One macro-task: work the event loop owes the script but has not run yet.
594///
595/// The microtask queue ([`Job`]) is different: those run before the host regains control.
596/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
597/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
598/// logic: the engine decides *what* is due, the host decides *how to wait*.
599///
600/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
601/// reference counting even though nothing else references it — the same rule the `HostFn`
602/// documentation states from the other side (a host closure must not hold a `Gc`, so the
603/// `Gc` lives here instead).
604pub enum Task {
605    /// A `setTimeout` that is due at `due_at`.
606    ///
607    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
608    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
609    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
610    /// would give this engine a timer the reference cannot produce, with nothing to
611    /// compare it against.
612    Timer {
613        /// The id `setTimeout` returned, for `clearTimeout`.
614        id: i32,
615        /// What to call when it fires.
616        callback: Value,
617        /// When it becomes runnable, as a monotonic instant.
618        due_at: std::time::Instant,
619    },
620}
621
622/// A descriptor the host has to poll, and which directions have a handler.
623///
624/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
625/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
626/// blocks on it, and the host reports back through [`Interp::fire_fd`].
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub struct FdInterest {
629    /// The descriptor to watch.
630    pub fd: i32,
631    /// Whether `os.setReadHandler` registered a callback.
632    pub read: bool,
633    /// Whether `os.setWriteHandler` registered a callback.
634    pub write: bool,
635}
636
637/// The callbacks registered for one descriptor, per direction.
638#[derive(Default)]
639pub(crate) struct FdHandlers {
640    /// `os.setReadHandler`'s callback.
641    pub read: Option<Value>,
642    /// `os.setWriteHandler`'s callback.
643    pub write: Option<Value>,
644}
645
646/// The file name `eval` reports, which the reference does not inherit from the caller.
647///
648/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
649/// reference and the names show up in stack traces.
650/// The description of the private symbol a class brand is made from.
651///
652/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
653/// place no script can reach, since no expression can name a private symbol.
654const BRAND_DESCRIPTION: &str = "brand";
655
656/// One validated property lookup.
657///
658/// Covers both own-property hits and prototype hits. The second kind was deliberately left
659/// uncached at first ("a prototype hit depends on more than the object and the name"), and
660/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
661/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
662/// names on every iteration (measured: 100 ns per call over an empty loop).
663pub struct FieldCache {
664    /// The name, so two different properties of one object do not collide.
665    key: PropertyKey,
666    /// Where the value was found, relative to the chain below.
667    index: usize,
668    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
669    level: u8,
670    /// The receiver and every prototype down to (and including) the level that answered,
671    /// each with the length of its property table at the time.
672    ///
673    /// That length is the whole guard, and it is sufficient for the ways the answer can
674    /// change without a lookup: adding or deleting any property moves it, and a
675    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
676    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
677    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
678    /// the one that was cached.
679    ///
680    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
681    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
682    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
683}
684
685/// How many links of a prototype chain a [`FieldCache`] remembers.
686///
687/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
688/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
689/// at three.
690const MAX_CACHED_CHAIN: usize = 3;
691
692/// A remembered global-variable lookup.
693///
694/// A `var` global is an ordinary property of the global object, so reading one walks the
695/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
696/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
697/// fixed by the bytecode, and the slot in the object's table only changes if the global
698/// object is mutated, which the index-and-name check below catches.
699pub struct GlobalCache {
700    /// The global object the lookup was resolved on, weakly.
701    object: js_gc::WeakGc<JsObject>,
702    /// Index of the data property in the global object's table.
703    index: usize,
704}
705
706/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
707const GLOBAL_CACHE_SLOTS: usize = 1024;
708
709/// How many property lookups are remembered.
710///
711/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
712/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
713/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
714/// lookup itself. Making it bigger stops helping: the working set of a real program's
715/// property sites is bounded by its code size.
716const FIELD_CACHE_SLOTS: usize = 4096;
717
718/// How much the heap may grow past the last `out of memory` before saying it again.
719///
720/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
721/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
722/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
723/// because it looks like it works. The reference gets this for free: it fails inside
724/// `js_malloc`, and its printing path happens not to allocate.
725///
726/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
727/// allocating is stopped within a rounding error of the limit) and far above what a
728/// handler needs.
729const OOM_HYSTERESIS: usize = 64 * 1024;
730
731/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
732pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
733
734/// How many instructions run between polls of [`Interp::interrupt`].
735///
736/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
737/// order of magnitude on both implementations — which is what lets a C driver compare its
738/// output byte for byte (see `scripts/m15-capi.sh --embed`).
739pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
740
741/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
742///
743/// Chosen so that the byte budget is what actually decides for every ordinary
744/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
745/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
746/// millions of frames.
747pub const MAX_FRAMES: usize = 200_000;
748
749const EVAL_FILE: &str = "<input>";
750
751/// The file name `std.evalScript` reports.
752const EVAL_SCRIPT_FILE: &str = "<evalScript>";
753
754/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
755///
756/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
757/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
758fn clamp_delay(delay_ms: f64) -> std::time::Duration {
759    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
760    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
761    // non-positive delay mean "due now".
762    if delay_ms.is_nan() || delay_ms <= 0.0 {
763        return std::time::Duration::ZERO;
764    }
765    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
766}
767
768impl js_gc::Trace for Task {
769    fn trace(&self, tracer: &mut js_gc::Tracer) {
770        let Task::Timer { callback, .. } = self;
771        callback.trace(tracer);
772    }
773}
774
775/// What one turn of the event loop did, so the caller cannot spin by accident.
776///
777/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
778/// core until the timer is due. Naming the three cases makes the wait explicit.
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub enum Turn {
781    /// Something ran. Call again immediately — there may be more ready work.
782    Ran,
783    /// Nothing is runnable, but descriptors are registered: the host must poll
784    /// [`Interp::pending_fds`] for at most this long, then report readiness with
785    /// [`Interp::fire_fd`].
786    ///
787    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
788    /// the failure this project treats as worst — a handler that silently never fires —
789    /// so the two cannot be confused by accident.
790    Poll(std::time::Duration),
791    /// Nothing is runnable yet, but something is pending. Block at most this long, then
792    /// call again.
793    Wait(std::time::Duration),
794    /// Nothing is pending at all: the loop is done.
795    Done,
796}
797
798impl js_gc::Trace for Job {
799    fn trace(&self, tracer: &mut js_gc::Tracer) {
800        match self {
801            Job::Reaction {
802                handler,
803                argument,
804                promise,
805                ..
806            } => {
807                if let Some(handler) = handler {
808                    handler.trace(tracer);
809                }
810                argument.trace(tracer);
811                tracer.visit(promise);
812            }
813            Job::Thenable {
814                then,
815                value,
816                promise,
817            } => {
818                then.trace(tracer);
819                value.trace(tracer);
820                tracer.visit(promise);
821            }
822            Job::Resume {
823                coroutine,
824                promise,
825                value,
826                ..
827            } => {
828                tracer.visit(coroutine);
829                tracer.visit(promise);
830                value.trace(tracer);
831            }
832            Job::Import { promise, .. } => tracer.visit(promise),
833            Job::GeneratorResume {
834                generator,
835                promise,
836                value,
837                ..
838            } => {
839                tracer.visit(generator);
840                tracer.visit(promise);
841                value.trace(tracer);
842            }
843        }
844    }
845}
846
847/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
848#[derive(Debug, Clone, Copy, PartialEq, Eq)]
849pub enum ResumeKind {
850    /// The generator was just created and is being run to its first suspension.
851    Start,
852    /// `next(v)`.
853    Next,
854    /// `return(v)`.
855    Return,
856    /// `throw(e)`.
857    Throw,
858}
859
860/// A generator object's saved execution.
861///
862/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
863/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
864/// separately allocated buffers.
865pub struct GeneratorState {
866    /// The detached frame, or `None` once the generator has finished or while it runs.
867    frame: Option<Frame>,
868    /// How far it got.
869    phase: GeneratorPhase,
870    /// Whether the last suspension was an `await` rather than a `yield`.
871    ///
872    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
873    /// value and a magic number, because the emitted code branches on which method
874    /// resumed it, while an `await` simply continues with its value. Getting this wrong
875    /// leaves an extra value on the operand stack that the next instruction then
876    /// consumes — a wrong answer rather than a crash.
877    parked_on_await: bool,
878    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
879    ///
880    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
881    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
882    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
883    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
884    /// delegating. Tracking it as part of the phase, the way the reference splits
885    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
886    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
887    /// exception and never reached `xs.throw`.
888    parked_on_yield_star: bool,
889    /// Pending `next`/`return`/`throw` calls, oldest first.
890    ///
891    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
892    /// called back to back must answer in that order, with the second call's value
893    /// arriving at the *second* `yield`. Running each call straight into the body — which
894    /// is what this engine did before — delivered the last queued value to whichever
895    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
896    /// `a === b ===` the final argument.
897    ///
898    /// The front entry is the one being served; it stays there (with `async_busy` set)
899    /// until its promise settles, because an `await` inside the body is a suspension of
900    /// the *driver*, not the end of the request.
901    requests: std::collections::VecDeque<AsyncRequest>,
902    /// Whether the front request is in flight.
903    async_busy: bool,
904}
905
906/// How one async-generator request ended.
907enum AsyncOutcome {
908    /// The method answered this `{value, done}`.
909    Value(Value),
910    /// The body threw.
911    Error(Value),
912}
913
914/// One queued `next`/`return`/`throw` on an async generator: the reference's
915/// `JSAsyncGeneratorRequest`.
916pub struct AsyncRequest {
917    /// Which method was called.
918    kind: ResumeKind,
919    /// Its argument.
920    value: Value,
921    /// The promise the method answered.
922    promise: Gc<JsObject>,
923}
924
925/// Which of §27.5.3.3's states a generator is in.
926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
927enum GeneratorPhase {
928    /// Created, `initial_yield` reached, body not entered.
929    SuspendedStart,
930    /// Parked at a `yield`.
931    SuspendedYield,
932    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
933    Executing,
934    /// Finished; the frame is gone.
935    Completed,
936}
937
938impl js_gc::Trace for GeneratorState {
939    fn trace(&self, tracer: &mut js_gc::Tracer) {
940        if let Some(frame) = &self.frame {
941            frame.trace(tracer);
942        }
943        for request in &self.requests {
944            request.value.trace(tracer);
945            tracer.visit(&request.promise);
946        }
947    }
948}
949
950/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
951/// them in.
952///
953/// Each is a field rather than a map entry because the runtime reads them on hot paths
954/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
955/// failure — reaching a default here means the builtin did not install, and every
956/// accessor panics rather than silently answering `undefined`.
957///
958/// [`builtins::symbol`]: crate::builtins::symbol
959#[derive(Default)]
960pub struct WellKnownSymbols {
961    /// The symbol values, positionally. Empty until `Symbol` installs.
962    symbols: Vec<Value>,
963}
964
965/// Which well-known symbol a caller wants.
966///
967/// A typed accessor beats passing a name around: a typo is a compile error rather than
968/// an `undefined` key that quietly matches nothing.
969#[derive(Debug, Clone, Copy, PartialEq, Eq)]
970pub enum WellKnown {
971    /// `Symbol.toPrimitive`.
972    ToPrimitive,
973    /// `Symbol.iterator`.
974    Iterator,
975    /// `Symbol.match`.
976    Match,
977    /// `Symbol.matchAll`.
978    MatchAll,
979    /// `Symbol.replace`.
980    Replace,
981    /// `Symbol.search`.
982    Search,
983    /// `Symbol.split`.
984    Split,
985    /// `Symbol.toStringTag`.
986    ToStringTag,
987    /// `Symbol.isConcatSpreadable`.
988    IsConcatSpreadable,
989    /// `Symbol.hasInstance`.
990    HasInstance,
991    /// `Symbol.species`.
992    Species,
993    /// `Symbol.unscopables`.
994    Unscopables,
995    /// `Symbol.asyncIterator`.
996    AsyncIterator,
997    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
998    Disposable,
999    /// `Symbol.asyncDispose` — the awaited form.
1000    AsyncDisposable,
1001}
1002
1003impl WellKnown {
1004    /// The index `Symbol`'s installer creates this symbol at.
1005    fn index(self) -> usize {
1006        match self {
1007            WellKnown::ToPrimitive => 0,
1008            WellKnown::Iterator => 1,
1009            WellKnown::Match => 2,
1010            WellKnown::MatchAll => 3,
1011            WellKnown::Replace => 4,
1012            WellKnown::Search => 5,
1013            WellKnown::Split => 6,
1014            WellKnown::ToStringTag => 7,
1015            WellKnown::IsConcatSpreadable => 8,
1016            WellKnown::HasInstance => 9,
1017            WellKnown::Species => 10,
1018            WellKnown::Unscopables => 11,
1019            WellKnown::AsyncIterator => 12,
1020            WellKnown::Disposable => 13,
1021            WellKnown::AsyncDisposable => 14,
1022        }
1023    }
1024}
1025
1026impl Realm {
1027    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1028    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1029        self.well_known_symbols.symbols = symbols;
1030    }
1031
1032    /// A well-known symbol.
1033    pub fn well_known(&self, which: WellKnown) -> Value {
1034        self.well_known_symbols
1035            .symbols
1036            .get(which.index())
1037            .cloned()
1038            .unwrap_or(Value::Undefined)
1039    }
1040
1041    /// The well-known symbol as a property key.
1042    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1043        match self.well_known(which) {
1044            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1045            // Unreachable once `Symbol` has installed; an empty string key matches
1046            // nothing, which degrades to "the object has no such method".
1047            _ => PropertyKey::from(String::new()),
1048        }
1049    }
1050}
1051
1052/// The interpreter: a realm plus a frame stack.
1053pub struct Interp<'a> {
1054    /// The heap everything is allocated on.
1055    pub heap: &'a Heap,
1056    /// The realm.
1057    pub realm: Realm,
1058    /// Active frames, outermost first.
1059    frames: Vec<Frame>,
1060    /// Value buffers from frames that have finished, reused by the next call.
1061    ///
1062    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1063    /// the locals and the operand stack — and free all four on return. `call:recursion`
1064    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1065    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1066    ///
1067    /// Bounded in both directions: a few buffers per kind, and none larger than
1068    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1069    /// and keeping its buffer would pin that memory for the rest of the run.
1070    free_values: Vec<Vec<Value>>,
1071    /// A strict-mode `eval`'s own variable scope, while its script runs.
1072    ///
1073    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1074    /// become a global. Name lookups still fall through to the realm, which is why
1075    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1076    eval_scope: Option<BTreeMap<String, Value>>,
1077    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1078    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1079    eval_depth: usize,
1080    /// The calling frame's own bindings, which the running `eval` can read and write.
1081    ///
1082    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1083    /// come from the frame, and a write is applied back to the frame (or to the cell
1084    /// the frame captured) when the eval finishes. That is what makes
1085    /// `f("a = 3")` visible to the caller as `a === 3`.
1086    eval_bindings: Vec<EvalBinding>,
1087    /// The calling frame's `arguments`, while an `eval` runs.
1088    ///
1089    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1090    /// own yet still has to see the caller's `arguments`.
1091    eval_arguments: Option<Value>,
1092    /// The `with` objects live at the moment the running `eval` started, innermost first.
1093    ///
1094    /// `None` outside an eval, which is what keeps a finished block's object from
1095    /// shadowing ordinary bytecode reads.
1096    eval_with: Option<Vec<Gc<JsObject>>>,
1097    /// The bindings the running direct `eval` makes visible, as name → cell.
1098    ///
1099    /// Set for the duration of an eval and then restored, but every closure created
1100    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1101    /// `eval("f = () => i")` work after the eval has returned.
1102    active_eval_scope: Option<Gc<EvalScope>>,
1103    /// The frame that called the direct `eval` currently running, if any.
1104    ///
1105    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1106    /// on the global object, which is what keeps
1107    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1108    /// gives each call its own `x`.
1109    eval_caller: Option<Option<usize>>,
1110    /// The caller's `new.target`, while an `eval` runs.
1111    ///
1112    /// The eval'd code is a script with no constructor of its own, so it inherits the
1113    /// one the enclosing function was called with.
1114    eval_new_target: Option<Value>,
1115    /// `new.target` for the frame about to be pushed.
1116    ///
1117    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1118    /// value reaches the frame without threading a parameter through every call site.
1119    pending_new_target: Option<Value>,
1120    /// Names of the native functions currently executing, outermost first.
1121    ///
1122    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1123    /// trace still names it with `(native)` instead of a position, so the names are
1124    /// tracked separately and stitched into [`Interp::stack_trace`].
1125    ///
1126    /// The third field is how many bytecode frames were live when the native was entered,
1127    /// which is what places it *among* them rather than before all of them. Native
1128    /// functions used to be emitted up front on the grounds that they never re-enter
1129    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1130    /// The natives currently running, innermost last: the function object and the
1131    /// depth it was entered at.
1132    ///
1133    /// The *name* is deliberately not stored. It used to be, read with
1134    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1135    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1136    /// benchmark. A stack trace is built rarely; it can read the name then.
1137    native_frames: Vec<(Gc<JsObject>, usize)>,
1138    /// The native function currently executing, for the ones that have to know *which*
1139    /// function they are — a typed-array constructor reads its element type off itself.
1140    ///
1141    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1142    /// reports whatever the enclosing bytecode frame was called with.
1143    current_native: Option<Gc<JsObject>>,
1144    /// Text written by `print` and friends, in order.
1145    ///
1146    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1147    /// once at the end, which is also when upstream's line buffering becomes
1148    /// visible for the cases compared here.
1149    pub output: String,
1150    /// Where `print` also writes, as it goes. `output` keeps the full log for
1151    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1152    ///
1153    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1154    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1155    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1156    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1157    /// would show a script's output all at once when it finished.
1158    pub output_sink: Option<Box<dyn std::io::Write>>,
1159    /// Where recent property reads found their value.
1160    ///
1161    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1162    /// table remembering *which object* and *which entry of its property table* answered a
1163    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1164    /// can move; the property can become an accessor), which is what makes a stale entry a
1165    /// miss rather than a wrong answer.
1166    ///
1167    /// The object is held weakly: a cache that held it strongly would keep up to
1168    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1169    /// program cannot see and cannot work around.
1170    pub field_cache: Vec<Option<FieldCache>>,
1171    /// Global lookups, by binding slot. See [`GlobalCache`].
1172    global_cache: Vec<Option<GlobalCache>>,
1173    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1174    /// under its limit. See [`Interp::check_memory`].
1175    pub oom_reported_at: usize,
1176    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1177    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1178    ///
1179    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1180    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1181    /// host that wants to stop a runaway script must not have to wait for it to return.
1182    ///
1183    /// Two things this cannot do, both of them differences a host can observe:
1184    ///
1185    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1186    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1187    ///   needs a signal that the `catch` machinery does not see, which is a change to
1188    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1189    ///   a host that stops the script itself.
1190    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1191    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1192    ///   both, so the difference is when the counter hits zero, not whether it will.
1193    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1194    /// Instructions until the next [`Interp::interrupt`] poll.
1195    pub interrupt_counter: u32,
1196    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1197    ///
1198    /// A separate field from [`Interp::uncatchable`] because the two live for different
1199    /// spans. This one is the host's standing request; it survives the start of an
1200    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1201    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1202    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1203    /// cleared it before the script it was set for had a chance to throw.
1204    pub uncatchable_next: bool,
1205    /// Whether the exception now unwinding may be caught by a `catch`.
1206    ///
1207    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1208    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1209    /// a host stopping a runaway loop is not fought by the loop.
1210    ///
1211    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1212    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1213    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1214    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1215    pub uncatchable: bool,
1216    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1217    ///
1218    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1219    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1220    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1221    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1222    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1223    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1224    ///
1225    /// The numbers come out close for the same reason a C frame and a heap frame of this
1226    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1227    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1228    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1229    /// `crates/quickjs-cli/tests/limits.rs`.
1230    pub stack_limit: usize,
1231    /// The most frames that may be live at once, whatever the byte budget says.
1232    ///
1233    /// A second bound for a reason the reference does not have: our frames cost less than
1234    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1235    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1236    /// `--stack-size 1G` from being a memory bomb.
1237    pub max_frames: usize,
1238    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1239    ///
1240    /// Script execution does not return until this has drained, which is what makes
1241    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1242    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1243    /// not a `for`.
1244    pub(crate) jobs: std::collections::VecDeque<Job>,
1245    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1246    ///
1247    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1248    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1249    pub(crate) tasks: Vec<Task>,
1250    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1251    /// barrier'd evaluation started.
1252    ///
1253    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1254    /// lets a REPL report an error from the line it just evaluated without also reporting
1255    /// its own readline loop.
1256    trace_barriers: Vec<usize>,
1257    /// `os.signal` handlers, keyed by signal number.
1258    ///
1259    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1260    /// a handler cannot be freed while it is still registered.
1261    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1262    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1263    ///
1264    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1265    /// that is only reachable from a host closure could be freed while still registered.
1266    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1267    /// The next timer id.
1268    ///
1269    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1270    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1271    next_timer_id: i32,
1272    /// Errors thrown by timer callbacks, already rendered.
1273    ///
1274    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1275    /// that throws has no promise behind it. Both are reported by the host at the end of
1276    /// the loop, but only one is fixed up by a later `.catch`.
1277    timer_errors: Vec<String>,
1278    /// The module registry, keyed by canonical name.
1279    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1280    /// How the host turns a specifier into bytes.
1281    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1282    /// The module the host was asked to run, for `import.meta.main`.
1283    pub main_module_name: Option<String>,
1284    /// Module bodies currently running, innermost last.
1285    ///
1286    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1287    /// this is the only place that knows which module that is.
1288    pub module_stack: Vec<String>,
1289    /// Rejections that no handler has claimed, with the promise they belong to.
1290    ///
1291    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1292    /// reason alone cannot say whether somebody eventually listened.
1293    unhandled: Vec<(Gc<JsObject>, Value)>,
1294}
1295
1296impl<'a> Interp<'a> {
1297    /// Build an interpreter over `heap`, with a fresh realm.
1298    pub fn new(heap: &'a Heap) -> Interp<'a> {
1299        let object_proto = JsObject::ordinary(heap, None);
1300        let function_proto = JsObject::function(
1301            heap,
1302            Some(object_proto.clone()),
1303            Callable::Native {
1304                func: |_, _, _| Ok(Value::Undefined),
1305                own_instance: false,
1306            },
1307        );
1308        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1309        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1310        let mut interp = Interp {
1311            heap,
1312            realm: Realm {
1313                global,
1314                object_proto,
1315                function_proto,
1316                array_proto,
1317                array_constructor: None,
1318                promise_constructor: None,
1319                globals: BTreeMap::new(),
1320                declared: Vec::new(),
1321                lexical_consts: BTreeSet::new(),
1322                errors: BTreeMap::new(),
1323                string_proto: None,
1324                number_proto: None,
1325                boolean_proto: None,
1326                bigint_proto: None,
1327                error_proto: JsObject::ordinary(heap, None),
1328                date_proto: JsObject::ordinary(heap, None),
1329                throw_type_error: None,
1330                generator_proto: JsObject::ordinary(heap, None),
1331                promise_proto: None,
1332                async_generator_proto: None,
1333                symbol_proto: None,
1334                symbol_registry: BTreeMap::new(),
1335                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1336                regexp_proto: None,
1337                regexp_ctor: None,
1338                suppressed_error_proto: None,
1339                disposable_stack_proto: None,
1340                map_proto: None,
1341                set_proto: None,
1342                finalization_registries: Vec::new(),
1343                array_buffer_proto: None,
1344                typed_array_proto: None,
1345                typed_array_protos: Vec::new(),
1346                data_view_proto: None,
1347                async_disposable_stack_proto: None,
1348                iterator_proto: None,
1349                iterator_ctor: None,
1350                iterator_helper_proto: None,
1351                iterator_wrap_proto: None,
1352                generator_function_proto: None,
1353                async_function_proto: None,
1354                async_generator_function_proto: None,
1355                iterator_protos: std::collections::BTreeMap::new(),
1356                well_known_symbols: WellKnownSymbols::default(),
1357                host_classes: HostClasses::new(),
1358            },
1359            frames: Vec::new(),
1360            free_values: Vec::new(),
1361            global_cache: {
1362                let mut cache = Vec::new();
1363                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1364                cache
1365            },
1366            eval_scope: None,
1367            eval_depth: 0,
1368            eval_bindings: Vec::new(),
1369            eval_arguments: None,
1370            eval_with: None,
1371            active_eval_scope: None,
1372            eval_caller: None,
1373            pending_new_target: None,
1374            eval_new_target: None,
1375            native_frames: Vec::new(),
1376            current_native: None,
1377            output: String::new(),
1378            output_sink: None,
1379            field_cache: {
1380                let mut cache = Vec::new();
1381                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1382                cache
1383            },
1384            oom_reported_at: 0,
1385            interrupt: None,
1386            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1387            uncatchable_next: false,
1388            uncatchable: false,
1389            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1390            // absent.
1391            stack_limit: DEFAULT_STACK_SIZE,
1392            max_frames: MAX_FRAMES,
1393            jobs: std::collections::VecDeque::new(),
1394            tasks: Vec::new(),
1395            trace_barriers: Vec::new(),
1396            signal_handlers: std::collections::BTreeMap::new(),
1397            fd_handlers: std::collections::BTreeMap::new(),
1398            next_timer_id: 1,
1399            timer_errors: Vec::new(),
1400            modules: std::collections::BTreeMap::new(),
1401            module_loader: None,
1402            main_module_name: None,
1403            module_stack: Vec::new(),
1404            unhandled: Vec::new(),
1405        };
1406        crate::builtins::install(&mut interp);
1407        interp
1408    }
1409
1410    // -- allocation helpers -------------------------------------------------
1411
1412    /// A new string value.
1413    /// A `BigInt` value from a computed big integer.
1414    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1415        Value::BigInt(Gc::new(self.heap, value))
1416    }
1417
1418    /// A string value from bytes that are already WTF-8, which is how a string with an
1419    /// unpaired surrogate reaches a `Value`.
1420    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1421        Value::string_wtf8(self.heap, text)
1422    }
1423
1424    /// A new string value, from text that is valid UTF-8.
1425    pub fn string(&self, text: impl Into<String>) -> Value {
1426        Value::string(self.heap, text)
1427    }
1428
1429    /// A new ordinary object with the given prototype.
1430    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1431        JsObject::ordinary(self.heap, proto)
1432    }
1433
1434    // -- host classes -------------------------------------------------------
1435
1436    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1437    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1438        self.realm.host_classes.register(def)
1439    }
1440
1441    /// Register `def` under an id the host already holds (`JS_NewClass`).
1442    ///
1443    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1444    /// `JS_NewClass`.
1445    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1446        self.realm.host_classes.define(id, def)
1447    }
1448
1449    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1450    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1451        self.realm.host_classes.set_proto(id, proto);
1452    }
1453
1454    /// The prototype installed for `id`, if any.
1455    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1456        self.realm.host_classes.proto(id)
1457    }
1458
1459    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1460    ///
1461    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1462    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1463    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1464    /// host installed none.
1465    ///
1466    /// Answers `None` for an id that was never registered: the C API would return an
1467    /// exception, and silently making an ordinary object instead would move the failure to
1468    /// the first `JS_GetOpaque` that no longer matches.
1469    pub fn new_host_object(
1470        &mut self,
1471        proto: Option<Gc<JsObject>>,
1472        class_id: ClassId,
1473    ) -> Option<Gc<JsObject>> {
1474        let class = self.realm.host_classes.def(class_id)?;
1475        let proto = proto
1476            .or_else(|| self.realm.host_classes.proto(class_id))
1477            .or_else(|| Some(self.realm.object_proto.clone()));
1478        Some(JsObject::host_object(self.heap, proto, class_id, class))
1479    }
1480
1481    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1482    ///
1483    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1484    /// object, it is an object of another class, or the class never got a payload. A host
1485    /// that has to tell them apart uses [`JsObject::host_class_id`].
1486    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1487        let object = value.as_object()?;
1488        if object.host_class_id()? != class_id {
1489            return None;
1490        }
1491        object.host_opaque()
1492    }
1493
1494    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1495    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1496        match value.as_object() {
1497            Some(object) => object.set_host_opaque(opaque),
1498            None => false,
1499        }
1500    }
1501
1502    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1503    ///
1504    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1505    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1506    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1507    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1508    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1509    /// said `[object Object]` instead of `[object Array Iterator]`.
1510    ///
1511    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1512    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1513    /// its own.
1514    pub fn new_iterator_prototype(
1515        &mut self,
1516        tag: &str,
1517        next: crate::object::NativeFn,
1518    ) -> Gc<JsObject> {
1519        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1520            return existing.clone();
1521        }
1522        let parent = self.realm.iterator_proto.clone();
1523        let proto = self.new_object(parent);
1524        let next = self.new_native("next", 0, next);
1525        proto.define(
1526            "next",
1527            Property::with_attributes(Value::Object(next), true, false),
1528        );
1529        let key = self.realm.well_known_key(WellKnown::Iterator);
1530        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1531        proto.define_key(
1532            &key,
1533            Property::with_attributes(Value::Object(identity), true, false),
1534        );
1535        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1536        let tag_value = self.string(tag);
1537        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1538        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1539        // checks it.
1540        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1541        self.realm
1542            .iterator_protos
1543            .insert(tag.to_string(), proto.clone());
1544        proto
1545    }
1546
1547    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1548    ///
1549    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1550    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1551    /// produced. That is why the two branches are not merged.
1552    pub fn object_own_property_keys(
1553        &mut self,
1554        object: &Gc<JsObject>,
1555    ) -> JsResult<Vec<PropertyKey>> {
1556        if let Some(keys) = self.proxy_own_keys(object)? {
1557            return Ok(keys);
1558        }
1559        // Integer-like keys ascending, then the string keys in insertion order, then the
1560        // symbols — the order every schema that walks an object expects.
1561        let entries = object.property_entries();
1562        let mut numeric: Vec<u32> = Vec::new();
1563        // An integer-indexed exotic object reports its indices as own keys even though they
1564        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1565        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1566        // order). The length is asked per call, so a resizable buffer's view reports the
1567        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1568        if object.typed_array_parts().is_some() {
1569            for index in 0..object.typed_array_length().unwrap_or(0) {
1570                // `u32::try_from` cannot fail for a real length, but the length is a
1571                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1572                // as an array index and one element beyond is not.
1573                match u32::try_from(index) {
1574                    Ok(index) => numeric.push(index),
1575                    Err(_) => break,
1576                }
1577            }
1578        }
1579        let mut strings: Vec<PropertyKey> = Vec::new();
1580        let mut symbols: Vec<PropertyKey> = Vec::new();
1581        for (key, _) in entries {
1582            match &key {
1583                // A class-private name is never reported by any enumeration: that is the
1584                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1585                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1586                // symbol skip, `Object.assign`) therefore cannot see it.
1587                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1588                PropertyKey::Symbol(_) => symbols.push(key),
1589                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1590                    Some(index) => {
1591                        if !numeric.contains(&index) {
1592                            numeric.push(index);
1593                        }
1594                    }
1595                    None => strings.push(key),
1596                },
1597            }
1598        }
1599        numeric.sort_unstable();
1600        let mut keys: Vec<PropertyKey> = numeric
1601            .into_iter()
1602            .map(|index| PropertyKey::from(index.to_string()))
1603            .collect();
1604        keys.extend(strings);
1605        keys.extend(symbols);
1606        Ok(keys)
1607    }
1608
1609    /// The state behind a promise object, or `None` when `object` is not one.
1610    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1611        object.with(|data| match &data.kind {
1612            ObjectKind::Promise(state) => Some(state.clone()),
1613            _ => None,
1614        })
1615    }
1616
1617    /// A new pending promise.
1618    pub fn new_promise(&mut self) -> Gc<JsObject> {
1619        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1620        // the one place every promise is built, and a subclass that builds its instances
1621        // somewhere else would be invisible to `instanceof`.
1622        let default = self.realm.promise_proto.clone();
1623        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1624        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1625        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1626        // `prototype` getter therefore still gets a working promise; the alternative is a
1627        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1628        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1629        let promise = JsObject::ordinary(self.heap, proto);
1630        promise.with_mut(|data| {
1631            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1632                crate::object::PromiseState::default(),
1633            )));
1634        });
1635        promise
1636    }
1637
1638    /// Fulfil `promise`, unless it has already settled.
1639    ///
1640    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1641    /// after `reject`, changes nothing.
1642    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1643        let Some(state) = self.promise_state(promise) else {
1644            return;
1645        };
1646        let reactions = {
1647            let mut state = state.borrow_mut();
1648            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1649                return;
1650            }
1651            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1652            std::mem::take(&mut state.reactions)
1653        };
1654        self.queue_reactions(reactions, value, false);
1655    }
1656
1657    /// Reject `promise`, unless it has already settled.
1658    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1659        let Some(state) = self.promise_state(promise) else {
1660            return;
1661        };
1662        let reactions = {
1663            let mut state = state.borrow_mut();
1664            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1665                return;
1666            }
1667            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1668            std::mem::take(&mut state.reactions)
1669        };
1670        // Remember it only when nothing is listening *now*; a `then` registered later
1671        // prunes the entry in `perform_then`.
1672        if reactions.is_empty() {
1673            self.unhandled.push((promise.clone(), reason.clone()));
1674        }
1675        self.queue_reactions(reactions, reason, true);
1676    }
1677
1678    /// Queue one job per reaction.
1679    ///
1680    /// This is what makes `then` asynchronous even on an already-settled promise:
1681    /// `p.then(f); g()` calls `g` first.
1682    fn queue_reactions(
1683        &mut self,
1684        reactions: Vec<crate::object::PromiseReaction>,
1685        argument: Value,
1686        rejected: bool,
1687    ) {
1688        for reaction in reactions {
1689            let handler = if rejected {
1690                reaction.on_rejected.clone()
1691            } else {
1692                reaction.on_fulfilled.clone()
1693            };
1694            self.jobs.push_back(Job::Reaction {
1695                handler,
1696                argument: argument.clone(),
1697                rejected,
1698                promise: reaction.promise,
1699            });
1700        }
1701    }
1702
1703    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1704    /// resolve/reject pair.
1705    ///
1706    /// The pair are callable objects rather than Rust closures, because the script gets
1707    /// them and may stash them for later.
1708    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1709        let promise = self.new_promise();
1710        // Both handlers are built-ins with an empty name and length 1, in
1711        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1712        // off `Object.getOwnPropertyNames`.
1713        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1714        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1715        (promise, Value::Object(resolve), Value::Object(reject))
1716    }
1717
1718    /// §27.2.1.5 `NewPromiseCapability(C)`.
1719    ///
1720    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1721    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1722    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1723    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1724    /// silently ignored argument.
1725    ///
1726    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1727    /// the engine's own executor is exactly what `new_promise_capability` builds.
1728    pub fn new_promise_capability_for(
1729        &mut self,
1730        constructor: &Value,
1731    ) -> JsResult<(Value, Value, Value)> {
1732        let Some(object) = constructor.as_object().cloned() else {
1733            return Err(self.type_error("promise constructor is not a constructor"));
1734        };
1735        if !object.is_constructor() {
1736            return Err(self.type_error("promise constructor is not a constructor"));
1737        }
1738        if self
1739            .realm
1740            .promise_constructor
1741            .as_ref()
1742            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1743        {
1744            let (promise, resolve, reject) = self.new_promise_capability();
1745            return Ok((Value::Object(promise), resolve, reject));
1746        }
1747        let state = self.new_object(Some(self.realm.object_proto.clone()));
1748        // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1749        // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1750        // which only a *custom* constructor can observe, and none of the combinator tests
1751        // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1752        let executor = self.builtin_function(
1753            "",
1754            2,
1755            Callable::CapabilityExecutor {
1756                state: state.clone(),
1757            },
1758        );
1759        let promise = self.construct(
1760            Value::Object(object.clone()),
1761            Value::Object(object),
1762            vec![Value::Object(executor)],
1763        )?;
1764        // The pair is read *after* the constructor returns, so a constructor that never
1765        // called its executor, or called it with non-callables, is the spec's step 11
1766        // `TypeError` — not something the engine can paper over.
1767        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1768            return Err(self.type_error("promise executor never ran"));
1769        };
1770        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1771            return Err(self.type_error("promise executor never ran"));
1772        };
1773        for handler in [&resolve, &reject] {
1774            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1775                return Err(self.type_error("promise capability handler is not callable"));
1776            }
1777        }
1778        Ok((promise, resolve, reject))
1779    }
1780
1781    /// §27.2.3.1 `PromiseResolve(C, x)`.
1782    ///
1783    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1784    /// an `x` that is already a promise of exactly this constructor is handed back
1785    /// unchanged, and anything else gets a fresh capability from `C`.
1786    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1787        if let Value::Object(object) = &value
1788            && self.promise_state(object).is_some()
1789        {
1790            // `x.constructor === C` means "already the right kind", so no capability is
1791            // built — which is observable through a `resolve` that counts its calls.
1792            let x_constructor = self.get_property(object, "constructor")?;
1793            let same = match (
1794                x_constructor.as_ref().and_then(Value::as_object),
1795                constructor.as_object(),
1796            ) {
1797                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1798                _ => false,
1799            };
1800            if same {
1801                return Ok(value);
1802            }
1803        }
1804        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1805        self.call_value(resolve, Value::Undefined, vec![value])?;
1806        Ok(promise)
1807    }
1808
1809    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1810    /// promise, as `{ value: completion }`.
1811    ///
1812    /// The three cases are the reference's, and they differ on purpose:
1813    ///
1814    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1815    ///   exception before any promise exists;
1816    /// * a **runtime** error rejects the returned promise;
1817    /// * success resolves it with `{ value }`, where the value is the script's completion
1818    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1819    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1820    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1821    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1822    ///
1823    /// # What this does not do
1824    ///
1825    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1826    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1827    /// the parser and the suspension machinery to accept a suspended top-level script, and
1828    /// is not implemented — such source is a syntax error here. Everything else about the
1829    /// flag is reproduced.
1830    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1831        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1832        // too, and the reference truncates that one at the same place as a runtime failure.
1833        if barrier {
1834            let depth = self.frames.len();
1835            self.trace_barriers.push(depth);
1836        }
1837        // Compiled before the promise exists, so a parse failure propagates as a throw
1838        // instead of being folded into a rejection.
1839        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1840            Ok(compiled) => compiled,
1841            Err(error) => {
1842                if barrier {
1843                    self.trace_barriers.pop();
1844                }
1845                return Err(error);
1846            }
1847        };
1848        // An async body answers its own promise, and that promise is what the reference
1849        // hands back — the same object, not a wrapper around it. Its resolution value is
1850        // the `{value}` object the compiled epilogue built.
1851        if compiled.kind.is_async() {
1852            let strict = compiled.strict;
1853            let promise = self.run_eval_script(compiled, strict)?;
1854            if barrier {
1855                self.trace_barriers.pop();
1856            }
1857            return Ok(promise);
1858        }
1859        let (promise, resolve, reject) = self.new_promise_capability();
1860        let strict = compiled.strict;
1861        match self.run_eval_script(compiled, strict) {
1862            Ok(value) => {
1863                // `{ value }` is a plain object, so resolving with it adopts nothing even
1864                // when the completion value is itself a promise.
1865                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1866                self.set_property(&wrapped, "value", value)?;
1867                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1868            }
1869            Err(Signal::Throw(error)) => {
1870                self.call_value(reject, Value::Undefined, vec![error])?;
1871            }
1872            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1873        }
1874        if barrier {
1875            self.trace_barriers.pop();
1876        }
1877        Ok(Value::Object(promise))
1878    }
1879
1880    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1881    ///
1882    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1883    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1884    /// timer table, where the collector already scans it.
1885    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1886        let (promise, resolve, _reject) = self.new_promise_capability();
1887        let resolve = self.new_host_function(
1888            "resolve",
1889            1,
1890            Box::new(
1891                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1892                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1893                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1894                },
1895            ),
1896        );
1897        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1898        // timer table is part of what the collector walks.
1899        self.schedule_timer(Value::Object(resolve), delay_ms);
1900        Ok(Value::Object(promise))
1901    }
1902
1903    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1904    /// new promise resolved with it.
1905    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1906        if let Value::Object(object) = &value
1907            && self.promise_state(object).is_some()
1908        {
1909            return Ok(value);
1910        }
1911        let promise = self.new_promise();
1912        self.resolve_promise_with(&promise, value)?;
1913        Ok(Value::Object(promise))
1914    }
1915
1916    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1917    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1918        // Resolving a promise with itself is a `TypeError`. The check exists because the
1919        // alternative is a chain of self-reactions that never settles.
1920        if let Value::Object(object) = &value
1921            && object.ptr_eq(promise)
1922        {
1923            // The spec rejects *and* throws, so both the promise and the caller see it.
1924            let thrown = self.type_error("cannot resolve a promise with itself");
1925            let Signal::Throw(error) = thrown.clone() else {
1926                unreachable!("type_error always throws")
1927            };
1928            self.reject_promise(promise, error);
1929            return Err(thrown);
1930        }
1931        let then = match &value {
1932            Value::Object(object) => self.get_property(object, "then")?,
1933            _ => None,
1934        };
1935        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1936        if !callable_then {
1937            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1938            self.fulfill_promise(promise, value);
1939            return Ok(());
1940        }
1941        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1942        // inside `resolve`, so a script cannot make a promise settle synchronously.
1943        self.jobs.push_back(Job::Thenable {
1944            then: then.expect("checked callable"),
1945            value,
1946            promise: promise.clone(),
1947        });
1948        Ok(())
1949    }
1950
1951    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1952    ///
1953    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1954    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1955    ///
1956    /// The property read is **not** short-circuitable even for a real promise: the spec says
1957    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1958    /// expects it to run. Skipping the read for promises not only lost the throw, it made
1959    /// the combinator's loop infinite — the test's iterator never sets `done`.
1960    pub fn invoke_then(
1961        &mut self,
1962        thenable: Value,
1963        on_fulfilled: Value,
1964        on_rejected: Value,
1965    ) -> JsResult<()> {
1966        let then = match &thenable {
1967            Value::Object(object) => self.get_property(object, "then")?,
1968            primitive => {
1969                let boxed = self.object_from(primitive)?;
1970                self.get_property(&boxed, "then")?
1971            }
1972        };
1973        let Some(then) = then else {
1974            return Err(self.type_error("thenable has no then method"));
1975        };
1976        if !matches!(&then, Value::Object(object) if object.is_callable()) {
1977            return Err(self.type_error("then is not a function"));
1978        }
1979        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1980        Ok(())
1981    }
1982
1983    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1984    ///
1985    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1986    /// promise.
1987    pub fn perform_then(
1988        &mut self,
1989        promise: &Gc<JsObject>,
1990        on_fulfilled: Option<Value>,
1991        on_rejected: Option<Value>,
1992    ) -> JsResult<Value> {
1993        let Some(state) = self.promise_state(promise) else {
1994            return Err(self.type_error("not a promise"));
1995        };
1996        // Whether a rejection handler is being attached decides whether a recorded
1997        // rejection stops being unhandled, so it is read before the values are moved.
1998        let has_rejection_handler = on_rejected.is_some();
1999        let derived = self.new_promise();
2000        let reaction = crate::object::PromiseReaction {
2001            on_fulfilled,
2002            on_rejected,
2003            promise: derived.clone(),
2004        };
2005        let settled = {
2006            let mut state = state.borrow_mut();
2007            // A rejection somebody reacts to is no longer unhandled.
2008            state.handled = true;
2009            match &state.status {
2010                crate::object::PromiseStatus::Pending => {
2011                    state.reactions.push(reaction.clone());
2012                    None
2013                }
2014                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2015                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2016            }
2017        };
2018        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2019        // later, means somebody is listening after all.
2020        if has_rejection_handler {
2021            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2022        }
2023        if let Some((argument, rejected)) = settled {
2024            let handler = if rejected {
2025                reaction.on_rejected
2026            } else {
2027                reaction.on_fulfilled
2028            };
2029            self.jobs.push_back(Job::Reaction {
2030                handler,
2031                argument,
2032                rejected,
2033                promise: reaction.promise,
2034            });
2035        }
2036        Ok(Value::Object(derived))
2037    }
2038
2039    /// The rejections nobody listened to, formatted the way the reference reports them.
2040    ///
2041    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2042    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2043    /// unhandled at the point the queue drains, because a `then` may still be attached
2044    /// before the host acts on it.
2045    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2046        let entries = std::mem::take(&mut self.unhandled);
2047        // Somebody may have attached a handler after the rejection was recorded, so the
2048        // promise is the authority rather than the list.
2049        let still_unhandled: Vec<Value> = entries
2050            .into_iter()
2051            .filter_map(|(promise, reason)| {
2052                let handled = self
2053                    .promise_state(&promise)
2054                    .map(|state| state.borrow().handled)
2055                    .unwrap_or(true);
2056                (!handled).then_some(reason)
2057            })
2058            .collect();
2059        still_unhandled
2060            .into_iter()
2061            .map(|reason| {
2062                let text = self.describe_exception(&reason);
2063                let stack = match &reason {
2064                    Value::Object(object) => self
2065                        .get_property(object, "stack")
2066                        .ok()
2067                        .flatten()
2068                        .map(|value| value.to_js_string())
2069                        // `stack` carries a trailing newline of its own, which would leave
2070                        // a blank line between two reported rejections.
2071                        .map(|text| text.trim_end().to_string())
2072                        .unwrap_or_default(),
2073                    _ => String::new(),
2074                };
2075                if stack.is_empty() {
2076                    format!("Possibly unhandled promise rejection: {text}")
2077                } else {
2078                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2079                }
2080            })
2081            .collect()
2082    }
2083
2084    /// Run the microtask queue to exhaustion.
2085    ///
2086    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2087    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2088    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2089    ///
2090    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2091    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2092    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2093    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2094        crate::builtins::json::parse_text(self, text, true)
2095    }
2096
2097    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2098    ///
2099    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2100    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2101    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2102    ///
2103    /// The callback is called with **no arguments**. The reference stores only the function
2104    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2105    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2106    /// extra arguments arrive as `undefined`.
2107    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2108        let id = self.next_timer_id;
2109        // Wrap rather than grow: the id reaches the script as an `Int32`.
2110        self.next_timer_id = if self.next_timer_id == i32::MAX {
2111            1
2112        } else {
2113            self.next_timer_id + 1
2114        };
2115        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2116        self.tasks.push(Task::Timer {
2117            id,
2118            callback,
2119            due_at,
2120        });
2121        id
2122    }
2123
2124    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2125    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2126    pub fn cancel_timer(&mut self, id: i32) -> bool {
2127        let before = self.tasks.len();
2128        self.tasks.retain(|task| match task {
2129            Task::Timer { id: task_id, .. } => *task_id != id,
2130        });
2131        self.tasks.len() != before
2132    }
2133
2134    /// How long until the earliest pending timer, or `None` when none is pending.
2135    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2136        let now = std::time::Instant::now();
2137        self.tasks
2138            .iter()
2139            .map(|task| match task {
2140                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2141            })
2142            .min()
2143    }
2144
2145    /// Run one turn of the event loop.
2146    ///
2147    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2148    /// run at most one due timer, then drain again. The blocking belongs to the caller
2149    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2150    /// is how it asks.
2151    ///
2152    /// One timer per turn rather than all of them: a timer callback may schedule another
2153    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2154    /// starve the microtask queue.
2155    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2156        self.drain_jobs()?;
2157        let now = std::time::Instant::now();
2158        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2159        // followed by `setTimeout(g, 1)` must run `g` first.
2160        let due = self
2161            .tasks
2162            .iter()
2163            .enumerate()
2164            .filter(|(_, task)| match task {
2165                Task::Timer { due_at, .. } => *due_at <= now,
2166            })
2167            .min_by_key(|(_, task)| match task {
2168                Task::Timer { due_at, .. } => *due_at,
2169            })
2170            .map(|(index, _)| index);
2171        let Some(index) = due else {
2172            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2173            // descriptor is registered but no timer is closer, so a script that never
2174            // touches the descriptor still gets control back. Without a cap a handler on a
2175            // descriptor that is never ready would block for as long as the host allows.
2176            let timeout = self
2177                .next_timeout()
2178                .unwrap_or(std::time::Duration::from_secs(10))
2179                .min(std::time::Duration::from_secs(10));
2180            if !self.fd_handlers.is_empty() {
2181                // Blocking on a timer while descriptors are registered would starve them,
2182                // and blocking on the descriptors while a timer is due would delay it; the
2183                // host polls with the earlier of the two deadlines, which this timeout is.
2184                return Ok(Turn::Poll(timeout));
2185            }
2186            return Ok(match self.next_timeout() {
2187                Some(wait) => Turn::Wait(wait),
2188                None => Turn::Done,
2189            });
2190        };
2191        let Task::Timer { callback, .. } = self.tasks.remove(index);
2192        let this = Value::Undefined;
2193        // A throwing timer callback must not stop the loop: the reference reports it and
2194        // keeps going, because the alternative is that one bad timer silently stops every
2195        // later one.
2196        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2197        match self.call_value(callback, this, Vec::new()) {
2198            Ok(_) => {}
2199            Err(Signal::Throw(value)) => {
2200                let text = self.describe_exception(&value);
2201                self.timer_errors.push(text);
2202            }
2203            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2204        }
2205        self.drain_jobs()?;
2206        Ok(Turn::Ran)
2207    }
2208
2209    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2210    ///
2211    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2212    /// left is removed — the reference does the same, so a script can rely on
2213    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2214    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2215        let entry = self.fd_handlers.entry(fd).or_default();
2216        if readable {
2217            entry.read = callback;
2218        } else {
2219            entry.write = callback;
2220        }
2221        if entry.read.is_none() && entry.write.is_none() {
2222            self.fd_handlers.remove(&fd);
2223        }
2224    }
2225
2226    /// Register or clear an `os.signal` handler.
2227    ///
2228    /// `None` removes it; the host separately restores the default disposition or sets
2229    /// ignore, because which of those happened is the script's choice (`null` versus
2230    /// `undefined`) and not something this table can express.
2231    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2232        match handler {
2233            Some(handler) => {
2234                self.signal_handlers.insert(signal, handler);
2235            }
2236            None => {
2237                self.signal_handlers.remove(&signal);
2238            }
2239        }
2240    }
2241
2242    /// Run the handler for `signal`, reporting whether one ran.
2243    ///
2244    /// A throwing handler is reported and the loop continues, like a timer's.
2245    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2246        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2247            return Ok(false);
2248        };
2249        match self.call_value(handler, Value::Undefined, Vec::new()) {
2250            Ok(_) => {}
2251            Err(Signal::Throw(value)) => {
2252                let text = self.describe_exception(&value);
2253                self.timer_errors.push(text);
2254            }
2255            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2256        }
2257        self.drain_jobs()?;
2258        Ok(true)
2259    }
2260
2261    /// The descriptors the host has to poll, and in which direction.
2262    ///
2263    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2264    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2265    /// `os_poll` asks for.
2266    pub fn pending_fds(&self) -> Vec<FdInterest> {
2267        self.fd_handlers
2268            .iter()
2269            .map(|(fd, entry)| FdInterest {
2270                fd: *fd,
2271                read: entry.read.is_some(),
2272                write: entry.write.is_some(),
2273            })
2274            .collect()
2275    }
2276
2277    /// Call the handler registered for `fd`, reporting whether one ran.
2278    ///
2279    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2280    /// poll iteration and then restarts the loop, because the handler may have changed the
2281    /// registration list underneath it; doing the same here keeps a handler that
2282    /// unregisters itself from being called with stale state.
2283    ///
2284    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2285    /// every later one, exactly as with timers.
2286    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2287        let Some(entry) = self.fd_handlers.get(&fd) else {
2288            return Ok(false);
2289        };
2290        let callback = if readable {
2291            entry.read.clone()
2292        } else if writable {
2293            entry.write.clone()
2294        } else {
2295            None
2296        };
2297        let Some(callback) = callback else {
2298            return Ok(false);
2299        };
2300        self.drain_jobs()?;
2301        match self.call_value(callback, Value::Undefined, Vec::new()) {
2302            Ok(_) => {}
2303            Err(Signal::Throw(value)) => {
2304                let text = self.describe_exception(&value);
2305                self.timer_errors.push(text);
2306            }
2307            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2308        }
2309        self.drain_jobs()?;
2310        Ok(true)
2311    }
2312
2313    /// Take the errors timer callbacks threw, leaving the list empty.
2314    pub fn take_timer_errors(&mut self) -> Vec<String> {
2315        std::mem::take(&mut self.timer_errors)
2316    }
2317
2318    /// Whether anything is still pending: a microtask or a timer.
2319    pub fn has_pending_work(&self) -> bool {
2320        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2321    }
2322
2323    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2324    pub fn has_pending_timers_or_jobs(&self) -> bool {
2325        !self.jobs.is_empty() || !self.tasks.is_empty()
2326    }
2327
2328    /// Run every queued microtask, including ones queued while draining.
2329    pub fn drain_jobs(&mut self) -> JsResult<()> {
2330        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2331        // would spin forever, so the drain is bounded the way the call stack is.
2332        let mut budget = 1_000_000usize;
2333        while let Some(job) = self.jobs.pop_front() {
2334            if budget == 0 {
2335                return Err(Signal::Throw(
2336                    self.make_error("InternalError", "promise job queue did not drain"),
2337                ));
2338            }
2339            budget -= 1;
2340            self.run_job(job)?;
2341            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2342            // engine may run script that the script itself did not ask for. Doing it here
2343            // rather than from a drop hook is what keeps the callback out of arbitrary
2344            // engine bookkeeping — see `builtins::weak`'s header.
2345            crate::builtins::weak::drain_finalizers(self)?;
2346        }
2347        // A script that queued no jobs may still have dropped targets, so the checkpoint
2348        // runs once more after the queue empties.
2349        crate::builtins::weak::drain_finalizers(self)?;
2350        Ok(())
2351    }
2352
2353    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2354    ///
2355    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2356    /// `None` and is swept out here. This is also where the realm learns that a registry
2357    /// died, which is why it is a mutation rather than a read.
2358    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2359        let handles = std::mem::take(&mut self.realm.finalization_registries);
2360        let mut live = Vec::with_capacity(handles.len());
2361        for handle in handles {
2362            let Some(object) = handle.upgrade() else {
2363                continue;
2364            };
2365            let Some(state) = object.finalization_state() else {
2366                continue;
2367            };
2368            live.push((object.clone(), *state));
2369            self.realm.finalization_registries.push(object.downgrade());
2370        }
2371        live
2372    }
2373
2374    /// Run one microtask.
2375    fn run_job(&mut self, job: Job) -> JsResult<()> {
2376        match job {
2377            Job::Reaction {
2378                handler: None,
2379                argument,
2380                rejected,
2381                promise,
2382            } => {
2383                // No handler: the settlement passes straight through to the derived
2384                // promise, which is why `p.catch(f)` ignores fulfilments.
2385                if rejected {
2386                    self.reject_promise(&promise, argument);
2387                } else {
2388                    self.fulfill_promise(&promise, argument);
2389                }
2390                Ok(())
2391            }
2392            Job::Reaction {
2393                handler: Some(handler),
2394                argument,
2395                promise,
2396                ..
2397            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2398                Ok(answer) => {
2399                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2400                        self.reject_promise(&promise, error);
2401                    }
2402                    Ok(())
2403                }
2404                Err(Signal::Throw(reason)) => {
2405                    self.reject_promise(&promise, reason);
2406                    Ok(())
2407                }
2408                Err(other) => Err(other),
2409            },
2410            Job::Thenable {
2411                then,
2412                value,
2413                promise,
2414            } => {
2415                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2416                // the value it produces settles `promise`.
2417                // The thenable's `then` gets this promise's own pair, so whatever it
2418                // produces settles `promise`.
2419                let resolve = JsObject::function(
2420                    self.heap,
2421                    Some(self.realm.function_proto.clone()),
2422                    Callable::PromiseResolve(promise.clone()),
2423                );
2424                let reject = JsObject::function(
2425                    self.heap,
2426                    Some(self.realm.function_proto.clone()),
2427                    Callable::PromiseReject(promise.clone()),
2428                );
2429                match self.call_value(
2430                    then,
2431                    value,
2432                    vec![Value::Object(resolve), Value::Object(reject)],
2433                ) {
2434                    Ok(_) => Ok(()),
2435                    Err(Signal::Throw(reason)) => {
2436                        self.reject_promise(&promise, reason);
2437                        Ok(())
2438                    }
2439                    Err(other) => Err(other),
2440                }
2441            }
2442            Job::Resume {
2443                coroutine,
2444                promise,
2445                kind,
2446                value,
2447            } => self.drive_async(&coroutine, &promise, kind, value),
2448            Job::GeneratorResume {
2449                generator,
2450                promise,
2451                kind,
2452                value,
2453            } => self.step_async_generator(&generator, &promise, kind, value),
2454            Job::Import {
2455                specifier,
2456                referrer,
2457                promise,
2458            } => {
2459                self.run_dynamic_import(&specifier, &referrer, &promise);
2460                Ok(())
2461            }
2462        }
2463    }
2464
2465    /// One element of a `Promise` combinator settled.
2466    ///
2467    /// The shared state object holds the result array, the number still outstanding, and
2468    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2469    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2470    /// to settle, only whatever `Sub` said a capability is.
2471    ///
2472    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2473    /// and `any` must ignore every later settlement, and `all` must not report a second
2474    /// rejection after the first.
2475    fn settle_combinator(
2476        &mut self,
2477        state: &Gc<JsObject>,
2478        index: usize,
2479        fulfilled: bool,
2480        value: Value,
2481    ) -> JsResult<()> {
2482        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2483        // Each element settles at most once: a thenable may call `onFulfilled` twice
2484        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2485        // call a no-op. Without it the second call decremented `remaining` again and settled
2486        // `all` with a short values array (`call-resolve-element-items`).
2487        let done = field("done");
2488        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2489        let settled = field("settled").is_some_and(|value| value.to_boolean());
2490        if settled {
2491            return Ok(());
2492        }
2493        if let Some(Value::Object(done)) = &done {
2494            if done
2495                .array_get(index)
2496                .is_some_and(|value| value.to_boolean())
2497            {
2498                return Ok(());
2499            }
2500            done.array_set(self.heap, index, Value::Bool(true));
2501        }
2502        let resolve = field("resolve");
2503        let reject = field("reject");
2504        let keys = field("keys");
2505        let results = field("results").and_then(|value| value.as_object().cloned());
2506        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2507        // promise: the handler is a plain function the constructor chose.
2508        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2509            if let Some(handler) = handler {
2510                interp.call_value(handler, Value::Undefined, vec![value])?;
2511            }
2512            Ok(())
2513        };
2514        match kind {
2515            // `race`: the first settlement wins and stops the rest.
2516            3 => {
2517                state.define_data("settled", Value::Bool(true));
2518                let handler = if fulfilled { resolve } else { reject };
2519                settle_with(self, handler, value)?;
2520                return Ok(());
2521            }
2522            // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2523            // the first rejection wins outright.
2524            0 | 4 if !fulfilled => {
2525                state.define_data("settled", Value::Bool(true));
2526                settle_with(self, reject, value)?;
2527                return Ok(());
2528            }
2529            // `any`: the first fulfilment wins.
2530            2 if fulfilled => {
2531                state.define_data("settled", Value::Bool(true));
2532                settle_with(self, resolve, value)?;
2533                return Ok(());
2534            }
2535            _ => {}
2536        }
2537        let Some(results) = &results else {
2538            return Ok(());
2539        };
2540        match kind {
2541            4 => {
2542                results.array_set(self.heap, index, value);
2543            }
2544            0 => {
2545                results.array_set(self.heap, index, value);
2546            }
2547            // `allSettled` (and its keyed twin) never rejects; each slot records what
2548            // happened.
2549            1 | 5 => {
2550                let record = self.new_object(Some(self.realm.object_proto.clone()));
2551                if fulfilled {
2552                    record.define_data("status", self.string("fulfilled"));
2553                    record.define_data("value", value);
2554                } else {
2555                    record.define_data("status", self.string("rejected"));
2556                    record.define_data("reason", value);
2557                }
2558                results.array_set(self.heap, index, Value::Object(record));
2559            }
2560            // `any`: a rejection is parked in the errors array and the sweep continues.
2561            2 => {
2562                results.array_set(self.heap, index, value);
2563            }
2564            _ => {}
2565        }
2566        let remaining = field("remaining")
2567            .map(|value| value.to_int32())
2568            .unwrap_or(0);
2569        let left = remaining - 1;
2570        state.define_data("remaining", Value::Int(left));
2571        if left != 0 {
2572            return Ok(());
2573        }
2574        state.define_data("settled", Value::Bool(true));
2575        match kind {
2576            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2577            // The keyed result: an ordinary object with a **null** prototype, holding the
2578            // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2579            4 | 5 => {
2580                let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2581                settle_with(self, resolve, keyed)?;
2582            }
2583            2 => {
2584                // The rejection is an `AggregateError` whose `errors` is the results array
2585                // itself — the slots are the reasons, in input order.
2586                let errors = results.array_elements().unwrap_or_default();
2587                let error = self.aggregate_error(errors, "all promises were rejected");
2588                settle_with(self, reject, error)?;
2589            }
2590            _ => {}
2591        }
2592        Ok(())
2593    }
2594
2595    /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2596    ///
2597    /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2598    /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2599    /// prototype is load-bearing in both directions: a key called `toString` must not
2600    /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2601    /// (`resolves-empty-object.js`).
2602    pub(crate) fn keyed_result_object(
2603        &mut self,
2604        keys: Option<&Value>,
2605        values: &Gc<JsObject>,
2606    ) -> JsResult<Value> {
2607        let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2608            return Ok(Value::Object(self.new_object(None)));
2609        };
2610        let result = self.new_object(None);
2611        let count = values.array_length().unwrap_or(0);
2612        for index in 0..count {
2613            let Some(key) = keys.array_get(index) else {
2614                continue;
2615            };
2616            let Some(value) = values.array_get(index) else {
2617                continue;
2618            };
2619            let property = Property::with_attributes(value, true, true);
2620            match &key {
2621                Value::Symbol(symbol) => {
2622                    result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2623                }
2624                other => {
2625                    let text = self.to_js_string(other)?;
2626                    result.define_key(&PropertyKey::from(text.as_str()), property);
2627                }
2628            }
2629        }
2630        Ok(Value::Object(result))
2631    }
2632
2633    /// Build an async function's result: a promise whose body runs as a coroutine.
2634    pub fn new_async_function(
2635        &mut self,
2636        function: Value,
2637        this: Value,
2638        args: Vec<Value>,
2639    ) -> JsResult<Value> {
2640        let promise = self.new_promise();
2641        let coroutine = self.new_coroutine(function, this, args)?;
2642        if let Err(Signal::Throw(reason)) =
2643            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2644        {
2645            self.reject_promise(&promise, reason);
2646        }
2647        Ok(Value::Object(promise))
2648    }
2649
2650    /// The coroutine an async body runs in.
2651    ///
2652    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2653    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2654    /// than growing a second state machine. The difference is only in the ending — a
2655    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2656    /// Run `code` as an async function body, answering the promise it settles.
2657    ///
2658    /// Used for a module with top-level `await`: its body is an async function whose
2659    /// caller is the host, so there is no function object to pass through
2660    /// [`Interp::new_async_function`].
2661    pub fn run_async_body(
2662        &mut self,
2663        code: Gc<CompiledCode>,
2664        env: Gc<ClosureEnv>,
2665        this: Value,
2666    ) -> JsResult<Value> {
2667        let promise = self.new_promise();
2668        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2669        if let Err(Signal::Throw(reason)) =
2670            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2671        {
2672            self.reject_promise(&promise, reason);
2673        }
2674        Ok(Value::Object(promise))
2675    }
2676
2677    fn new_coroutine(
2678        &mut self,
2679        function: Value,
2680        this: Value,
2681        args: Vec<Value>,
2682    ) -> JsResult<Gc<JsObject>> {
2683        let Some(object) = function.as_object().cloned() else {
2684            return Err(self.type_error("not a function"));
2685        };
2686        let Some((code, env)) = bytecode_of(&object) else {
2687            return Err(self.type_error("not a function"));
2688        };
2689        self.new_coroutine_from(code, env, this, args)
2690    }
2691
2692    /// Build a coroutine over an already-resolved body.
2693    fn new_coroutine_from(
2694        &mut self,
2695        code: Gc<CompiledCode>,
2696        env: Gc<ClosureEnv>,
2697        this: Value,
2698        args: Vec<Value>,
2699    ) -> JsResult<Gc<JsObject>> {
2700        let function = Value::Undefined;
2701        self.push_frame(code, env, this, args, function)?;
2702        let frame = self.frames.pop().expect("push_frame just pushed it");
2703        let state = GeneratorState {
2704            frame: Some(frame),
2705            phase: GeneratorPhase::SuspendedStart,
2706            parked_on_await: false,
2707            parked_on_yield_star: false,
2708            requests: std::collections::VecDeque::new(),
2709            async_busy: false,
2710        };
2711        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2712        coroutine.with_mut(|data| {
2713            data.kind = ObjectKind::Generator(Box::new(state));
2714        });
2715        Ok(coroutine)
2716    }
2717
2718    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2719    /// `await` and `value` is what it awaited.
2720    fn resume_coroutine(
2721        &mut self,
2722        coroutine: &Gc<JsObject>,
2723        kind: ResumeKind,
2724        value: Value,
2725    ) -> JsResult<(Value, bool)> {
2726        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2727            ObjectKind::Generator(state) => Some(std::mem::replace(
2728                state.as_mut(),
2729                GeneratorState {
2730                    frame: None,
2731                    phase: GeneratorPhase::Executing,
2732                    parked_on_await: false,
2733                    parked_on_yield_star: false,
2734                    requests: std::collections::VecDeque::new(),
2735                    async_busy: false,
2736                },
2737            )),
2738            _ => None,
2739        }) else {
2740            return Err(self.type_error("not a coroutine"));
2741        };
2742        let result = self.step_generator(&mut state, kind, value);
2743        coroutine.with_mut(|data| {
2744            data.kind = ObjectKind::Generator(Box::new(state));
2745        });
2746        let (value, done, _ready, _reason) = result?;
2747        Ok((value, done))
2748    }
2749
2750    /// Advance an async body and settle its promise with the outcome.
2751    fn drive_async(
2752        &mut self,
2753        coroutine: &Gc<JsObject>,
2754        promise: &Gc<JsObject>,
2755        kind: ResumeKind,
2756        value: Value,
2757    ) -> JsResult<()> {
2758        match self.resume_coroutine(coroutine, kind, value) {
2759            Ok((value, true)) => {
2760                // `Ok` with `done` means the body finished *normally*, even when it was
2761                // resumed by a `throw` — `try { await p } catch {}` completes by
2762                // returning. Only the `Err` arm below is a rejection.
2763                //
2764                // Resolving rather than fulfilling matters: `return promise` in an async
2765                // body adopts the inner promise, so `async function f(){ return
2766                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2767                // promise.
2768                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2769                    self.reject_promise(promise, reason);
2770                }
2771                Ok(())
2772            }
2773            Ok((value, false)) => {
2774                // Parked on `await`: follow what it awaited and resume with the outcome.
2775                let awaited = match self.promise_resolve_value(value) {
2776                    Ok(awaited) => awaited,
2777                    Err(Signal::Throw(error)) => {
2778                        self.reject_promise(promise, error);
2779                        return Ok(());
2780                    }
2781                    Err(other) => return Err(other),
2782                };
2783                self.hook_await(awaited, coroutine, promise)
2784            }
2785            Err(Signal::Throw(reason)) => {
2786                self.reject_promise(promise, reason);
2787                Ok(())
2788            }
2789            Err(other) => Err(other),
2790        }
2791    }
2792
2793    /// Arrange for `coroutine` to resume when `awaited` settles.
2794    fn hook_await(
2795        &mut self,
2796        awaited: Value,
2797        coroutine: &Gc<JsObject>,
2798        promise: &Gc<JsObject>,
2799    ) -> JsResult<()> {
2800        let resumed = JsObject::function(
2801            self.heap,
2802            Some(self.realm.function_proto.clone()),
2803            Callable::AwaitResume {
2804                coroutine: coroutine.clone(),
2805                promise: promise.clone(),
2806                kind: ResumeKind::Next,
2807            },
2808        );
2809        let raised = JsObject::function(
2810            self.heap,
2811            Some(self.realm.function_proto.clone()),
2812            Callable::AwaitResume {
2813                coroutine: coroutine.clone(),
2814                promise: promise.clone(),
2815                kind: ResumeKind::Throw,
2816            },
2817        );
2818        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2819        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2820        let Value::Object(awaited) = &awaited else {
2821            self.jobs.push_back(Job::Resume {
2822                coroutine: coroutine.clone(),
2823                promise: promise.clone(),
2824                kind: ResumeKind::Next,
2825                value: awaited,
2826            });
2827            return Ok(());
2828        };
2829        self.perform_then(
2830            awaited,
2831            Some(Value::Object(resumed)),
2832            Some(Value::Object(raised)),
2833        )?;
2834        Ok(())
2835    }
2836
2837    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2838    /// things an engine keeps outside it — array elements and an array's `length`.
2839    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2840        if let Some(property) = object.own_property_key(key) {
2841            return Some(property);
2842        }
2843        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2844        // be synthesized too — and every one of them is a plain writable, enumerable,
2845        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2846        // `undefined` before this, which made `key-is-numericindex` fail on its own
2847        // side effect check.
2848        //
2849        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2850        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2851        // likewise not elements however numeric they look.
2852        if object.typed_array_element_type().is_some()
2853            && let Some(numeric) = canonical_numeric_index(key)
2854            && numeric.is_finite()
2855            && numeric.fract() == 0.0
2856            && !(numeric == 0.0 && numeric.is_sign_negative())
2857            && numeric >= 0.0
2858            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2859        {
2860            let value = object.typed_array_element(numeric as usize)?;
2861            return Some(Property::data(value));
2862        }
2863        // An array's elements live in their own vector rather than the property table, so
2864        // a descriptor for one has to be synthesized — with the attributes an element has.
2865        if let Some(index) = key.as_str().and_then(array_index)
2866            && let Some(value) = object.array_get(index as usize)
2867            && !matches!(value, Value::Hole)
2868        {
2869            return Some(Property::data(value));
2870        }
2871        // `length` is an own property of an array that is not in its property table
2872        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2873        // and non-enumerable.
2874        if key.as_str() == Some("length")
2875            && let Some(length) = object.array_length()
2876        {
2877            return Some(Property {
2878                value: Some(crate::object::length_value(length)),
2879                writable: object.length_writable(),
2880                enumerable: false,
2881                configurable: false,
2882                getter: None,
2883                setter: None,
2884                descriptor_fields: None,
2885            });
2886        }
2887        None
2888    }
2889
2890    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2891    pub fn object_get_own_property(
2892        &mut self,
2893        object: &Gc<JsObject>,
2894        key: &PropertyKey,
2895    ) -> JsResult<Option<Property>> {
2896        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2897            return Ok(answer);
2898        }
2899        if let Some(exotic) = object.exotic()
2900            && let Some(answer) = exotic.get_own_property(self, object, key)?
2901        {
2902            return Ok(answer);
2903        }
2904        // A mapped `arguments` index is a data property as far as script can see: the
2905        // accessor pair that aliases the parameter is plumbing, and exposing it would
2906        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2907        // report a `get` where the spec has a `[[Value]]`.
2908        if let Some(index) = key.as_str().and_then(crate::object::array_index)
2909            && let Some(cell) = object.mapped_argument_cell(index as usize)
2910        {
2911            // Non-configurable is *not* the default: an ordinary mapped index is
2912            // configurable, and only becomes non-configurable once something
2913            // redefines it. Preserve whatever the property table currently says.
2914            // The attributes come from whatever the property table holds, because they
2915            // can be changed independently of the mapping; only the *value* and the
2916            // data-property *kind* are the accessor's secret.
2917            let flags = Self::ordinary_own_property(object, key);
2918            if let Some(existing) = &flags
2919                && !existing.is_accessor()
2920            {
2921                // Already demapped: the table entry is the answer, not the cell.
2922                return Ok(flags);
2923            }
2924            return Ok(Some(Property {
2925                value: Some(cell.get()),
2926                writable: true,
2927                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2928                configurable: flags.as_ref().is_some_and(|p| p.configurable),
2929                ..Property::default()
2930            }));
2931        }
2932        Ok(Self::ordinary_own_property(object, key))
2933    }
2934
2935    /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
2936    ///
2937    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
2938    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
2939    /// abstract operation here rather than a private helper in `error.rs`.
2940    ///
2941    /// The name is the whole point: the setter must behave as if the prototype were not
2942    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
2943    /// the accessor for every error object in the realm. Everything below follows from that:
2944    ///
2945    /// 1. `thisValue` must be an object — otherwise `TypeError`.
2946    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
2947    ///    accessor's own home an error rather than a self-shadow.
2948    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
2949    ///    either has a string or has made a mistake.
2950    /// 4. An existing *own* property decides the path — an own setter is called, an own
2951    ///    non-writable data property is a `TypeError` — and only a missing own property
2952    ///    falls through to defining one.
2953    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
2954    ///    traps and a non-extensible receiver is a `TypeError`.
2955    ///
2956    /// The installed shape is writable + configurable, not enumerable.
2957    pub fn setter_that_ignores_prototype_properties(
2958        &mut self,
2959        this_value: Value,
2960        home: &Gc<JsObject>,
2961        property_key: &str,
2962        args: &[Value],
2963    ) -> JsResult<Value> {
2964        let Some(receiver) = this_value.as_object().cloned() else {
2965            return Err(self.type_error("setter called on a non-object"));
2966        };
2967        if Gc::ptr_eq(&receiver, home) {
2968            return Err(self.type_error("cannot assign to the accessor's own home object"));
2969        }
2970        // No type check here: §7.3.40 takes an arbitrary `v`, and
2971        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
2972        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
2973        // before calling this.
2974        let value = args.first().cloned().unwrap_or(Value::Undefined);
2975        let key = PropertyKey::from(property_key);
2976        // Step 4: an own property on the receiver changes what happens, and there are three
2977        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
2978        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
2979        // `Set` with `throw = true`, and a test exists for each.
2980        if let Some(existing) = self.object_get_own_property(&receiver, &key)? {
2981            if existing.is_accessor() && existing.setter.is_none() {
2982                // A getter-only own accessor cannot be written through.
2983                return Err(self.type_error("no setter for the own property"));
2984            }
2985            // Everything else — an own data property, or an own accessor *with* a setter —
2986            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
2987            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
2988            // an own user setter receives the value (`setter-own-accessor`), because
2989            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
2990            // setter directly is the difference between one code path and two that can
2991            // disagree.
2992            self.set_property(&receiver, property_key, value.clone())?;
2993            return Ok(Value::Undefined);
2994        }
2995        let property = Property {
2996            value: Some(value.clone()),
2997            writable: true,
2998            // Enumerable, despite the accessor it shadows not being. The reference installs
2999            // it that way and six cases check it (`setter-creates-own-property` and friends).
3000            enumerable: true,
3001            configurable: true,
3002            ..Property::default()
3003        };
3004        if !self.object_define_own_property(&receiver, &key, property)? {
3005            return Err(self.type_error("the receiver refused the definition"));
3006        }
3007        Ok(Value::Undefined)
3008    }
3009
3010    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3011    ///
3012    /// The indices of a typed array are not properties at all — they are bytes in the
3013    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3014    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3015    /// enumerable and configurable, so a definition can only ever change the *value*, and
3016    /// every other descriptor is refused rather than applied.
3017    ///
3018    /// The order of the checks is the spec's, and two of them are load-bearing:
3019    ///
3020    /// * the index is validated **before** the value is converted, because the conversion
3021    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3022    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3023    ///   happens when the index was valid on the way in;
3024    /// * the store is attempted even when the index has gone out of bounds by the time the
3025    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3026    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3027    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3028    ///
3029    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3030    /// the existing element, which is harmless here: every valid index is already
3031    /// writable, enumerable and configurable, so a `false` in the merged property can only
3032    /// have come from the descriptor having named `false`.
3033    fn integer_indexed_define_own_property(
3034        &mut self,
3035        object: &Gc<JsObject>,
3036        numeric: f64,
3037        property: &Property,
3038    ) -> JsResult<bool> {
3039        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3040        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3041        if !typed_array_index_is_valid(object, numeric) {
3042            return Ok(false);
3043        }
3044        // Step 6: the indices are data properties, so an accessor descriptor is refused
3045        // rather than converted. `Object.defineProperty` turns the `false` into a
3046        // `TypeError`; `Reflect.defineProperty` reports it.
3047        if property.is_accessor() {
3048            return Ok(false);
3049        }
3050        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3051        // definition that asks for anything else cannot be honoured.
3052        if !property.writable || !property.enumerable || !property.configurable {
3053            return Ok(false);
3054        }
3055        // Step 10: only a descriptor that names a value stores anything.
3056        let Some(value) = property.value.clone() else {
3057            return Ok(true);
3058        };
3059        let Some(element) = object.typed_array_element_type() else {
3060            return Ok(false);
3061        };
3062        let stored = self.element_value(element, value)?;
3063        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3064            return Err(self.type_error(reason));
3065        }
3066        Ok(true)
3067    }
3068
3069    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3070    pub fn object_define_own_property(
3071        &mut self,
3072        object: &Gc<JsObject>,
3073        key: &PropertyKey,
3074        property: Property,
3075    ) -> JsResult<bool> {
3076        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3077            return Ok(accepted);
3078        }
3079        // A proxy always answers above — with `Some` from its trap, or with `None` when
3080        // the trap is absent, and then the definition belongs to the **target**
3081        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3082        // when there is no trap). Falling through to the ordinary path here defined the
3083        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3084        // property the target never saw.
3085        if object.proxy_state().is_some() {
3086            let Some((target, _handler)) = self.proxy_parts(object)? else {
3087                return Err(self.type_error("cannot use a proxy that has been revoked"));
3088            };
3089            return self.object_define_own_property(&target, key, property);
3090        }
3091        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3092        // they accept exactly one descriptor shape. This has to happen before the
3093        // ordinary path, which would happily store a data property next to the buffer —
3094        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3095        // and `TypedArray/prototype/set` are about this section.
3096        if object.typed_array_element_type().is_some()
3097            && let Some(index) = canonical_numeric_index(key)
3098        {
3099            return self.integer_indexed_define_own_property(object, index, &property);
3100        }
3101        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3102        // non-extensible object. The check lives here rather than in the callers because
3103        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3104        // `Array.prototype.filter` uses to store its result, and a species object made
3105        // non-extensible by its own constructor must make that a `TypeError`
3106        // (`target-array-non-extensible`).
3107        // Note the `is_none()`: an already-present property may still be **redefined** on a
3108        // non-extensible object, and only *adding* one is refused (as Distinct from
3109        // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3110        // properties — testing extensibility before looking for the property made every
3111        // `Object.freeze` of an ordinary object refuse its own second step).
3112        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3113            return Ok(false);
3114        }
3115        // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3116        // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3117        // an omitted field is left alone). Merging here rather than at each call site is
3118        // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3119        // the value and `enumerable` in place.
3120        //
3121        // The merge is a no-op when the property is absent: there is nothing to keep.
3122        let property = match property.descriptor_fields {
3123            None => property,
3124            Some(fields) => {
3125                let base = self.object_get_own_property(object, key)?;
3126                let mut merged = base.clone().unwrap_or_default();
3127                if fields.value {
3128                    merged.value = property.value.clone();
3129                }
3130                if fields.writable {
3131                    merged.writable = property.writable;
3132                }
3133                if fields.enumerable {
3134                    merged.enumerable = property.enumerable;
3135                }
3136                if fields.configurable {
3137                    merged.configurable = property.configurable;
3138                }
3139                merged.descriptor_fields = None;
3140                merged
3141            }
3142        };
3143        // A host class that intercepts definitions owns the attributes of the properties it
3144        // defines: `_class`-style storage on the native side is the usual reason.
3145        if let Some(exotic) = object.exotic()
3146            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3147        {
3148            return Ok(accepted);
3149        }
3150        // An array index is stored in the element vector, which can hold a plain value and
3151        // nothing else. An accessor — or a data property with non-default attributes —
3152        // therefore has to live in the property table, and the element slot is blanked so
3153        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3154        // {get})` stored the accessor where no read ever looked, and the array kept
3155        // answering its old value.
3156        // An array's `length` is not stored in the property table, so defining it has to
3157        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3158        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3159        // {value: 1})` reported success and changed nothing.
3160        if key.as_str() == Some("length") && object.is_array() {
3161            // `{writable: false}` on `length` does not change the length, but it does make
3162            // it read-only — after which neither a later `{writable: true}` nor a store
3163            // past the end may succeed.
3164            if property.value.is_none() {
3165                if !object.length_writable() && property.writable {
3166                    return Ok(false);
3167                }
3168                object.set_length_writable(property.writable);
3169                return Ok(true);
3170            }
3171            if !object.length_writable() {
3172                return Ok(false);
3173            }
3174        }
3175        if key.as_str() == Some("length")
3176            && object.is_array()
3177            && let Some(value) = property.value.clone()
3178        {
3179            let requested = value.to_number();
3180            let valid = requested.is_finite()
3181                && requested >= 0.0
3182                && requested.fract() == 0.0
3183                && requested <= u32::MAX as f64;
3184            if !valid {
3185                return Err(self.range_error("invalid array length"));
3186            }
3187            // Truncating deletes the elements above the new length, and a non-configurable
3188            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3189            // makes `a.length = 2` fail rather than quietly drop it.
3190            let current = object.array_length().unwrap_or(0);
3191            let requested = requested as usize;
3192            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3193                return Ok(false);
3194            }
3195            object.array_set_length(self.heap, requested);
3196            return Ok(true);
3197        }
3198        let plain = property.writable
3199            && property.enumerable
3200            && property.configurable
3201            && !property.is_accessor();
3202        if let Some(index) = key.as_str().and_then(array_index)
3203            && object.is_array()
3204        {
3205            // Growing the array needs a writable `length`: after
3206            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3207            // be added.
3208            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3209                return Ok(false);
3210            }
3211            if plain && property.value.is_some() {
3212                // An ordinary element: the vector is where a read looks first, so it has
3213                // to be the vector that changes — unless the index is too far out to be
3214                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3215                // one property, because past its own limit it stores the index as an
3216                // ordinary key. Falling through to `define_key` below is the same choice,
3217                // and the alternative was worse: the store used to be *dropped* and the
3218                // length left at 0, which is a silent wrong answer.
3219                let value = property.value.clone().unwrap_or(Value::Undefined);
3220                object.delete_key(key);
3221                if object.array_set(self.heap, index as usize, value) {
3222                    return Ok(true);
3223                }
3224                // Past the dense limit the element lives in the table like any property.
3225                object.note_element_descriptor();
3226                object.define_key(key, property);
3227                // A sparse store past the dense limit still extends `length`, which is what
3228                // `a[a.length] = v` relies on — but only extends: shortening would delete
3229                // the sparse properties above the index, including this one.
3230                if index as usize + 1 > object.array_length().unwrap_or(0) {
3231                    object.array_set_length(self.heap, index as usize + 1);
3232                }
3233                return Ok(true);
3234            }
3235            // A non-plain element — an accessor, or an attribute that is not the default —
3236            // lives in the table while the slot becomes a hole. Recording it keeps every
3237            // later `a[i] = v` off the dense path, where the write would have shadowed the
3238            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3239            // replace the accessor with a plain data property.
3240            object.note_element_descriptor();
3241            object.define_key(key, property);
3242            // The slot stays, so `length` does not shrink; a hole is not an element, so
3243            // the table entry is now what a read finds.
3244            object.array_set(self.heap, index as usize, Value::Hole);
3245            return Ok(true);
3246        }
3247        object.define_key(key, property);
3248        Ok(true)
3249    }
3250
3251    /// Build a proxy object over `target`, with its traps read from `handler`.
3252    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3253        JsObject::proxy(self.heap, target, handler)
3254    }
3255
3256    /// The `revoke` function for a proxy's slots.
3257    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3258        JsObject::function(
3259            self.heap,
3260            Some(self.realm.function_proto.clone()),
3261            Callable::Revoker(slots),
3262        )
3263    }
3264
3265    /// A new array.
3266    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3267        let array = JsObject::array(
3268            self.heap,
3269            Some(self.realm.array_proto.clone()),
3270            elements.len(),
3271        );
3272        for (index, element) in elements.into_iter().enumerate() {
3273            array.array_set(self.heap, index, element);
3274        }
3275        array
3276    }
3277
3278    /// A new native function object.
3279    ///
3280    /// The observable `name` and `length` are installed as properties here, which is
3281    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3282    /// so `f.name = "x"` behaves like the writable property it is.
3283    /// A native constructor that builds its own instance after validating its arguments.
3284    ///
3285    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3286    /// check runs before `new.target.prototype` is read.
3287    pub fn new_native_ctor(
3288        &self,
3289        name: impl Into<String>,
3290        length: u32,
3291        func: NativeFn,
3292    ) -> Gc<JsObject> {
3293        let function = JsObject::function(
3294            self.heap,
3295            Some(self.realm.function_proto.clone()),
3296            Callable::Native {
3297                func,
3298                own_instance: true,
3299            },
3300        );
3301        function.set_constructible(true);
3302        function.define(
3303            "length",
3304            Property::name_or_length(Value::Int(length as i32)),
3305        );
3306        function.define("name", Property::name_or_length(self.string(name)));
3307        function
3308    }
3309
3310    /// A native constructor that lets `new` build the instance first.
3311    ///
3312    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3313    /// validation that must precede reading `new.target.prototype`, so the object can be
3314    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3315    /// which makes a *method* and therefore not a constructor at all.
3316    pub fn new_native_constructor(
3317        &self,
3318        name: impl Into<String>,
3319        length: u32,
3320        func: NativeFn,
3321    ) -> Gc<JsObject> {
3322        let function = self.new_native(name, length, func);
3323        function.set_constructible(true);
3324        function
3325    }
3326
3327    /// A new host function object: a native closure that carries its own state.
3328    ///
3329    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3330    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3331    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3332    /// this safe: the closure must not capture a `Gc`.
3333    pub fn new_host_function(
3334        &self,
3335        name: impl Into<String>,
3336        length: u32,
3337        func: crate::object::HostFn,
3338    ) -> Gc<JsObject> {
3339        self.new_host_inner(name.into(), length, func, false)
3340    }
3341
3342    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3343    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3344    pub fn new_host_ctor(
3345        &self,
3346        name: impl Into<String>,
3347        length: u32,
3348        func: crate::object::HostFn,
3349    ) -> Gc<JsObject> {
3350        let function = self.new_host_inner(name.into(), length, func, true);
3351        function.set_constructible(true);
3352        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3353        // installs its own methods on it, so it starts as a plain object.
3354        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3355        function.define(
3356            "prototype",
3357            Property {
3358                value: Some(Value::Object(proto)),
3359                writable: true,
3360                enumerable: false,
3361                configurable: false,
3362                ..Property::default()
3363            },
3364        );
3365        function
3366    }
3367
3368    fn new_host_inner(
3369        &self,
3370        name: String,
3371        length: u32,
3372        func: crate::object::HostFn,
3373        own_instance: bool,
3374    ) -> Gc<JsObject> {
3375        let function = JsObject::function(
3376            self.heap,
3377            Some(self.realm.function_proto.clone()),
3378            Callable::Host {
3379                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3380                own_instance,
3381            },
3382        );
3383        function.define(
3384            "length",
3385            Property::name_or_length(Value::Int(length as i32)),
3386        );
3387        function.define("name", Property::name_or_length(self.string(name)));
3388        function
3389    }
3390
3391    /// A callable object with the `length`/`name` a built-in function has, in that order.
3392    ///
3393    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3394    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3395    /// [`JsObject::function`] defines neither, which is why every capability helper built
3396    /// with it reported no own `length` and no own `name` at all.
3397    ///
3398    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3399    /// configurable.
3400    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3401        let function =
3402            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3403        function.define(
3404            "length",
3405            Property::name_or_length(Value::Int(length as i32)),
3406        );
3407        function.define("name", Property::name_or_length(self.string(name)));
3408        function
3409    }
3410
3411    /// A new native function object.
3412    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3413        let function = JsObject::function(
3414            self.heap,
3415            Some(self.realm.function_proto.clone()),
3416            Callable::Native {
3417                func,
3418                own_instance: false,
3419            },
3420        );
3421        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3422        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3423        // `length,name` and this listed `name,length`. A bytecode function already gets it
3424        // the right way round; only native ones were built backwards.
3425        function.define(
3426            "length",
3427            Property::name_or_length(Value::Int(length as i32)),
3428        );
3429        function.define("name", Property::name_or_length(self.string(name)));
3430        function
3431    }
3432
3433    /// A new bound function.
3434    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3435        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3436        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3437        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3438        let constructible = target
3439            .as_object()
3440            .is_some_and(|target| target.is_constructor());
3441        let bound = JsObject::function(
3442            self.heap,
3443            Some(self.realm.function_proto.clone()),
3444            Callable::Bound { target, this, args },
3445        );
3446        bound.set_constructible(constructible);
3447        bound
3448    }
3449
3450    /// A new reference cell.
3451    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3452        Gc::new(self.heap, Cell::new(value))
3453    }
3454
3455    // -- running ------------------------------------------------------------
3456
3457    /// Evaluate `code` as a script body and return its completion value.
3458    /// Compile and run `source` for the engine's own use, returning its completion value.
3459    ///
3460    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3461    /// needs to be a real async function, and the engine already runs those as coroutines,
3462    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3463    ///
3464    /// Differences from [`Self::eval_in_global`], both deliberate:
3465    ///
3466    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3467    ///   being built, and the source is an IIFE that only constructs a closure, so there
3468    ///   is nothing to drain — and draining here would run script-queued jobs in the
3469    ///   middle of `install`.
3470    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3471    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3472    ///   and it should not look like the user wrote something wrong.
3473    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3474        let program = match js_parse::parse_script(source) {
3475            Ok(program) => program,
3476            Err(error) => {
3477                let message = format!("builtin source does not parse: {error}");
3478                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3479            }
3480        };
3481        let mut code = match js_compile::compile_script_with_source(&program, source) {
3482            Ok(code) => code,
3483            Err(error) => {
3484                let message = format!("builtin source does not compile: {}", error.message);
3485                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3486            }
3487        };
3488        // The frame has to name something, and `<builtin>` is what a stack trace through
3489        // this code should say.
3490        code.set_filename("<builtin>");
3491        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3492        let closure_vars = compiled.code.closure_vars.clone();
3493        let env = self.global_env(&closure_vars);
3494        let this = Value::Object(self.realm.global.clone());
3495        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3496    }
3497
3498    /// Run an already-parsed script and drain the microtasks it queued.
3499    ///
3500    /// The drain is what lets an `async` function's body advance past its first `await`
3501    /// before the host sees the result: nothing else pumps the job queue.
3502    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3503        let this = Value::Object(self.realm.global.clone());
3504        self.run_script_with_this(code, this)
3505    }
3506
3507    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3508    ///
3509    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3510    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3511    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3512    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3513    /// state the next script evaluation tripped over.
3514    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3515        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3516        let closure_vars = compiled.code.closure_vars.clone();
3517        let env = self.global_env(&closure_vars);
3518        let callee = Value::Undefined;
3519        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3520        // The script is done, so the microtasks it queued run before the host sees the
3521        // result. Without this an `async` function's body would never advance past its
3522        // first `await`, because nothing else drains the queue.
3523        self.drain_jobs()?;
3524        Ok(result)
3525    }
3526
3527    /// Compile and run `source` in global scope, returning its completion value.
3528    ///
3529    /// This is what `eval` and `new Function` use. Running it as a script means it
3530    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3531    /// for a `Function` body; a *direct* eval that reads a local variable would need
3532    /// the compiler to hand its variable environment over, which is not implemented.
3533    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3534        self.eval_in_global_named(source, EVAL_FILE, false)
3535    }
3536
3537    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3538    ///
3539    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3540    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3541    /// through the code, so they cannot share one constant.
3542    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3543        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3544    }
3545
3546    /// Evaluate `source` as a global script, reported under `file`.
3547    ///
3548    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3549    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3550    /// from inside a C callback, where the interpreter is the running one rather than a
3551    /// context's own.
3552    pub fn eval_in_global_named(
3553        &mut self,
3554        source: &str,
3555        file: &str,
3556        barrier: bool,
3557    ) -> JsResult<Value> {
3558        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3559        // eval-created global binding — configurable, unlike a script's own `var`.
3560        self.eval_depth += 1;
3561        if barrier {
3562            let depth = self.frames.len();
3563            self.trace_barriers.push(depth);
3564        }
3565        let result = self.eval_in_global_inner(source, file);
3566        if barrier {
3567            self.trace_barriers.pop();
3568        }
3569        self.eval_depth -= 1;
3570        result
3571    }
3572
3573    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3574        let compiled = self.compile_global_script(source, file, false)?;
3575        let strict = compiled.strict;
3576        self.run_eval_script(compiled, strict)
3577    }
3578
3579    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3580    ///
3581    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3582    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3583    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3584    /// direct eval's is.
3585    pub fn eval_script_with_this(
3586        &mut self,
3587        source: &str,
3588        file: &str,
3589        this: Value,
3590    ) -> JsResult<Value> {
3591        let program = match js_parse::parse_script(source) {
3592            Ok(program) => program,
3593            Err(error) => {
3594                return Err(Signal::Throw(self.syntax_error_at(
3595                    file,
3596                    error.span.start.line,
3597                    error.span.start.column,
3598                    &error.message,
3599                )));
3600            }
3601        };
3602        let mut compiled = match js_compile::compile_script(&program) {
3603            Ok(compiled) => compiled,
3604            Err(error) => {
3605                return Err(Signal::Throw(self.syntax_error_at(
3606                    file,
3607                    error.span.start.line,
3608                    error.span.start.column,
3609                    &error.message,
3610                )));
3611            }
3612        };
3613        compiled.set_filename(file);
3614        self.run_script_with_this(compiled, this)
3615    }
3616
3617    /// Parse and compile `source` as a global script, without running it.
3618    ///
3619    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3620    /// before a promise exists to reject — while still evaluating in the same eval context
3621    /// (direct-eval strictness, `new.target`, `super`).
3622    fn compile_global_script(
3623        &mut self,
3624        source: &str,
3625        file: &str,
3626        async_body: bool,
3627    ) -> JsResult<CompiledFunction> {
3628        // A *direct* eval inherits the strictness of the code that called it, which is
3629        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3630        // implicit global. The caller's frame is the innermost one here, because a
3631        // native function does not push a frame of its own.
3632        let strict = self.current_strict();
3633        // `eval` runs in the caller's function context, so `new.target` is legal here
3634        // even though the source is a bare script — and so is `super.x` when the caller
3635        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3636        // caller's, which is what `special_object 4` already does.
3637        let context = js_parse::EvalContext {
3638            in_method: self.enclosing_home_object().is_some(),
3639            // `super()` belongs to a derived constructor, and an eval'd body is not a
3640            // constructor at all: the caller frame's `this` is already built.
3641            in_derived_constructor: false,
3642        };
3643        // A *global* eval is not a function body: `new.target` and `super` are out of
3644        // reach there. Its `{async: true}` form differs in the other direction — the body
3645        // may `await` — so the two flags are independent and the reference sets both from
3646        // the eval type rather than from the caller.
3647        let parsed = if async_body {
3648            js_parse::parse_suspensible_global_eval(source, strict)
3649        } else {
3650            js_parse::parse_eval_script_in(source, strict, context)
3651        };
3652        let program = match parsed {
3653            Ok(program) => program,
3654            Err(error) => {
3655                // The message is bare: the position lives in `fileName`,
3656                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3657                // the reference puts it. An `invalid source: L:C: ` prefix made
3658                // `e.message` differ from the reference while the stack already agreed.
3659                return Err(Signal::Throw(self.syntax_error_at(
3660                    file,
3661                    error.span.start.line,
3662                    error.span.start.column,
3663                    &error.message,
3664                )));
3665            }
3666        };
3667        let mut compiled = match if async_body {
3668            js_compile::compile_script_suspensible(&program)
3669        } else {
3670            js_compile::compile_script(&program)
3671        } {
3672            Ok(compiled) => compiled,
3673            // A construct the compiler does not handle yet is reported the same way a
3674            // parse error is: it happens before anything runs, so the trace is the
3675            // position in the source followed by the caller.
3676            Err(error) => {
3677                return Err(Signal::Throw(self.syntax_error_at(
3678                    file,
3679                    error.span.start.line,
3680                    error.span.start.column,
3681                    &error.message,
3682                )));
3683            }
3684        };
3685        compiled.set_filename(file);
3686        Ok(compiled)
3687    }
3688
3689    /// Run an `eval`'d script in the caller's scope.
3690    ///
3691    /// Three things have to come from the calling frame, because the eval'd code is a
3692    /// script and would otherwise see only the global object:
3693    ///
3694    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3695    /// * `arguments`, exposed as a binding of the eval's own scope, so
3696    ///   `f("arguments.length", 1)` sees the caller's arguments;
3697    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3698    ///   `eval("var v = 1")` into the global object.
3699    ///
3700    /// Locals of the calling function are *not* reachable: that needs the compiler to
3701    /// hand its variable environment over, which this milestone does not do.
3702    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3703        // `this` and `arguments` come from the innermost frame only — those are not
3704        // lexical — while the name bindings come from the whole chain of frames, part
3705        // of it being ordinary scope resolution.
3706        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3707        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3708        // read from its closure.
3709        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3710        // variable environment is the innermost frame of all: an arrow's own body is where
3711        // `var`s declared by an `eval` inside it belong.
3712        let caller_index = self
3713            .frames
3714            .iter()
3715            .rposition(|frame| !frame.code.code.is_arrow)
3716            .or_else(|| self.frames.len().checked_sub(1));
3717        let env_index = self.frames.len().checked_sub(1);
3718        let caller = caller_index.and_then(|index| self.frames.get(index));
3719        let (this, passed) = match caller {
3720            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3721            // No frame at all: the eval is running at the top level, so there is
3722            // nothing to inherit and the global receiver is right.
3723            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3724        };
3725        // Innermost frame first, so the first binding found for a name is the one that
3726        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3727        let mut bindings: Vec<EvalBinding> = Vec::new();
3728        // The calling function's own bindings, resolved by the compiler at the call
3729        // site. That table is the only reliable answer when a name is declared twice in
3730        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3731        // body means, and guessing by declaration order picks the wrong one as soon as
3732        // two loops in a row use the same name.
3733        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3734        // every direct call — a bare `eval(...)` callee — so finding one at the current
3735        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3736        // callee to a value first and leave no site behind.
3737        let mut direct = false;
3738        let mut resolved_here = false;
3739        if let Some(frame) = self.frames.last() {
3740            let (line, column) = frame
3741                .code
3742                .code
3743                .position_at(frame.at as u32)
3744                .unwrap_or_default();
3745            // The nearest site at or before the current position, not an exact match:
3746            // the recorded position of the `call` instruction is the callee's, which
3747            // sits a few columns inside the call expression the compiler recorded. A
3748            // site is unique per call, so "the closest one behind us" identifies it.
3749            if let Some(site) = frame
3750                .code
3751                .code
3752                .eval_sites
3753                .iter()
3754                .filter(|site| (site.line, site.column) <= (line, column))
3755                .max_by_key(|site| (site.line, site.column))
3756            {
3757                direct = true;
3758                resolved_here = true;
3759                for binding in &site.bindings {
3760                    // An enclosing function's frame sits `owner` levels below the one
3761                    // running the call.
3762                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3763                    else {
3764                        continue;
3765                    };
3766                    bindings.push(EvalBinding {
3767                        name: binding.name.clone(),
3768                        frame,
3769                        slot: if binding.is_arg {
3770                            EvalSlot::Arg
3771                        } else {
3772                            EvalSlot::Local
3773                        },
3774                        index: binding.index as usize,
3775                    });
3776                }
3777            }
3778        }
3779        for frame_index in (0..self.frames.len()).rev() {
3780            // Skip the innermost frame's flat scan when the compiler already answered
3781            // for it; an enclosing frame still needs one, because the eval resolves
3782            // those names dynamically.
3783            if resolved_here && frame_index == self.frames.len() - 1 {
3784                continue;
3785            }
3786            let frame = &self.frames[frame_index];
3787            for (index, arg) in frame.code.code.args.iter().enumerate() {
3788                bindings.push(EvalBinding {
3789                    name: arg.name.clone(),
3790                    frame: frame_index,
3791                    slot: EvalSlot::Arg,
3792                    index,
3793                });
3794            }
3795            for (index, local) in frame.code.code.vars.iter().enumerate() {
3796                bindings.push(EvalBinding {
3797                    name: local.name.clone(),
3798                    frame: frame_index,
3799                    slot: EvalSlot::Local,
3800                    index,
3801                });
3802            }
3803        }
3804        let mut seen = BTreeSet::new();
3805        bindings.retain(|binding| seen.insert(binding.name.clone()));
3806
3807        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3808        // elements is all the spec's ordinary uses need.
3809        //
3810        // Known divergence: this is bound for a *global* eval too, where there is no
3811        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3812        // needs "does the calling frame have an `arguments` of its own", which is not
3813        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3814        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3815        // the call-site detection does not answer it. Modelled as a binding in the caller's
3816        // variable environment, this would fall out; that is a larger change than the one
3817        // this comment is attached to.
3818        let arguments = Value::Object(self.new_array(passed));
3819
3820        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3821        // declares its `var`s in the caller's — which for a top-level eval is the global
3822        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3823        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3824        // vanish into a scope nobody reads back from.
3825        let previous_scope = if code_strict {
3826            self.eval_scope.replace(BTreeMap::new())
3827        } else {
3828            None
3829        };
3830        let previous_arguments = self.eval_arguments.replace(arguments);
3831        let previous_with = self.eval_with.replace(self.with_objects());
3832        let inherited_new_target = self
3833            .frames
3834            .iter()
3835            .rev()
3836            .find(|frame| !frame.code.code.is_arrow)
3837            .map(|frame| frame.new_target.clone());
3838        let previous_new_target = self
3839            .eval_new_target
3840            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3841        let eval_cells = self.eval_cells_for(&bindings);
3842        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3843        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3844        // `declare_eval_local` needs to know which frame that is.
3845        // An indirect eval gets the global environment, so nothing of the caller's is
3846        // recorded as the place its `var`s belong.
3847        let previous_caller = self
3848            .eval_caller
3849            .replace(if direct { env_index } else { None });
3850        // The cell-based view of the same bindings, which is what a closure created
3851        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3852        // whose compiler did not put a binding in a cell simply does not appear here —
3853        // reads and writes still work through `eval_bindings`, they just cannot outlive
3854        // the eval.
3855        let previous_eval_scope = self
3856            .active_eval_scope
3857            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3858        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3859        let closure_vars = compiled.code.closure_vars.clone();
3860        let env = self.global_env(&closure_vars);
3861        let callee = Value::Undefined;
3862        // An async body does not run here: it becomes a coroutine and answers a promise,
3863        // which is what makes `await` legal in it. `this` still has to be the caller's
3864        // (for a global eval, the global object), because `this` is not part of `await`.
3865        let result = if compiled.code.kind.is_async() {
3866            self.run_async_body(compiled, env, this)
3867        } else {
3868            self.execute(compiled, env, this, Vec::new(), callee)
3869        };
3870        self.eval_scope = previous_scope;
3871        self.eval_arguments = previous_arguments;
3872        self.eval_with = previous_with;
3873        self.eval_new_target = previous_new_target;
3874        self.eval_bindings = previous_bindings;
3875        self.eval_caller = previous_caller;
3876        self.active_eval_scope = previous_eval_scope;
3877        result
3878    }
3879
3880    /// The cell-backed subset of `bindings`, in the same priority order.
3881    ///
3882    /// Both lookup routes have to agree — the eval's own reads go through
3883    /// [`Interp::eval_binding_value`] and the closures it builds go through
3884    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3885    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3886    /// is not in a cell simply does not appear: reads and writes still work, they just
3887    /// cannot be handed to a closure that outlives the eval.
3888    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3889        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3890        for binding in bindings {
3891            let Some(frame) = self.frames.get(binding.frame) else {
3892                continue;
3893            };
3894            let cell = match binding.slot {
3895                EvalSlot::Arg => frame
3896                    .code
3897                    .arg_cell
3898                    .get(binding.index)
3899                    .copied()
3900                    .unwrap_or(-1),
3901                EvalSlot::Local => frame
3902                    .code
3903                    .loc_cell
3904                    .get(binding.index)
3905                    .copied()
3906                    .unwrap_or(-1),
3907            };
3908            if cell < 0 {
3909                continue;
3910            }
3911            if let Some(cell) = frame.cells.get(cell as usize) {
3912                names.push((binding.name.clone(), cell.clone()));
3913            }
3914        }
3915        names
3916    }
3917
3918    /// A `SyntaxError` that reports where in the source it happened.
3919    ///
3920    /// Compile-time failures never run, so they have no frame of their own; the
3921    /// reference still puts the position first in the trace, with no function name and
3922    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3923    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3924    /// reference borrows), which is how a script reads the position without parsing
3925    /// the trace.
3926    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3927    ///
3928    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3929    /// `columnNumber`, which is how the reference prints one. A positionless error
3930    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3931    /// the reference raises it from `js_resolve_module`, where there is no position.
3932    pub(crate) fn syntax_error_plain(
3933        &mut self,
3934        error: &js_parse::SyntaxError,
3935        file: &str,
3936    ) -> Value {
3937        if error.positionless {
3938            return self.make_error("SyntaxError", &error.message);
3939        }
3940        self.syntax_error_at(
3941            file,
3942            error.span.start.line,
3943            error.span.start.column,
3944            &error.message,
3945        )
3946    }
3947
3948    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3949        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
3950        let value = self.make_error("SyntaxError", message);
3951        if let Value::Object(object) = &value {
3952            let text = self.string(blamed);
3953            // `stack` is an own data property, and the reference keeps it
3954            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
3955            object.define("stack", Property::with_attributes(text, true, false));
3956            let name = self.string(file);
3957            object.define("fileName", Property::with_attributes(name, true, true));
3958            object.define(
3959                "lineNumber",
3960                Property::with_attributes(Value::Int(line as i32), true, true),
3961            );
3962            object.define(
3963                "columnNumber",
3964                Property::with_attributes(Value::Int(column as i32), true, true),
3965            );
3966        }
3967        value
3968    }
3969
3970    /// Run a compiled script whose completion value is a function, returning it.
3971    ///
3972    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3973    /// get the closure out, which keeps the constant-pool plumbing in one place.
3974    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3975        self.run_script(code)
3976    }
3977
3978    /// The environment of a script or of any function compiled at global scope:
3979    /// every entry is a global binding, so each one resolves to the realm's cell.
3980    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3981        let mut cells = Vec::with_capacity(closure_vars.len());
3982        for closure_var in closure_vars {
3983            let cell = match closure_var.closure_type {
3984                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3985                    if closure_var.is_lexical =>
3986                {
3987                    // A lexical declaration: the cell is created here holding the
3988                    // dead-zone marker, which is what makes the binding exist and
3989                    // unreadable before its initialiser runs.
3990                    self.declare_global(&closure_var.name, closure_var.is_const);
3991                    self.realm.globals[&closure_var.name].clone()
3992                }
3993                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3994                    // A `var` or function declaration becomes a property of the global
3995                    // object, and it exists from here on — which is why
3996                    // `print(v); var v = 1` prints `undefined` instead of raising.
3997                    // Declaring it at instantiation time (rather than at the
3998                    // initialiser) is also what makes it non-configurable: the store
3999                    // then lands on an existing property instead of creating one.
4000                    self.declare_var_global(&closure_var.name);
4001                    // The cell is a placeholder that nothing indexes; it cannot be
4002                    // omitted because the slot has to hold something.
4003                    self.new_cell(Value::Undefined)
4004                }
4005                _ => {
4006                    // An undeclared global is read by name; the cell is a
4007                    // placeholder that nothing indexes.
4008                    self.new_cell(Value::Undefined)
4009                }
4010            };
4011            cells.push(cell);
4012        }
4013        Gc::new(
4014            self.heap,
4015            ClosureEnv {
4016                cells,
4017                eval_scope: None,
4018                local_vars: None,
4019                local_phase: 1,
4020            },
4021        )
4022    }
4023
4024    /// Push a frame and run until it returns.
4025    pub(crate) fn execute(
4026        &mut self,
4027        code: Gc<CompiledCode>,
4028        env: Gc<ClosureEnv>,
4029        this: Value,
4030        args: Vec<Value>,
4031        callee: Value,
4032    ) -> JsResult<Value> {
4033        let depth = self.frames.len();
4034        if depth == 0 {
4035            // A throw that reached the host ends the *active* mode: the next one is catchable
4036            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4037            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4038            // for the throw that evaluation will raise.
4039            self.uncatchable = false;
4040        }
4041        self.push_frame(code, env, this, args, callee)?;
4042        loop {
4043            // The fast loop first: it runs whole runs of records with `pc` in a register.
4044            //
4045            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4046            // reads it again — a store, a load and two bounds checks that a loop body does
4047            // not need, because nothing outside the loop can run in between. This is the
4048            // classic split: advance a register, and only spill it when leaving.
4049            //
4050            // `Some(value)` means the function ended by running off the end of its
4051            // instruction array, which is a normal return.
4052            let step = match self.run_fast() {
4053                Ok(Some(value)) => Ok(Step::Return(value)),
4054                Ok(None) => self.step(),
4055                Err(signal) => Err(signal),
4056            };
4057            match step {
4058                Ok(Step::Continue) => {}
4059                Ok(Step::Return(value)) => {
4060                    self.pop_frame();
4061                    // A frame that ended in a `tail_call` hands its value straight to
4062                    // its caller: nothing after the call can run, so every frame above
4063                    // the callee unwinds with the same value. See [`Frame::tail`] —
4064                    // the reference does not reuse frames either, so recursion depth
4065                    // and the stack-overflow limit behave the same way.
4066                    while self.frames.len() > depth && self.frame().tail {
4067                        self.pop_frame();
4068                    }
4069                    if self.frames.len() == depth {
4070                        return Ok(value);
4071                    }
4072                    // The caller resumes with the value on its stack.
4073                    self.frames
4074                        .last_mut()
4075                        .expect("a caller is live")
4076                        .stack
4077                        .push(value);
4078                }
4079                Err(Signal::Throw(value)) => {
4080                    // The host's standing request becomes the active mode for this unwind,
4081                    // and is consumed here so it does not leak into the next throw.
4082                    if self.uncatchable_next {
4083                        self.uncatchable_next = false;
4084                        self.uncatchable = true;
4085                    }
4086                    // An uncatchable throw walks past every `catch` on the way out. The
4087                    // frames are still popped, because the values they hold have to be
4088                    // dropped — only the search for a handler is skipped.
4089                    if self.uncatchable {
4090                        while self.frames.len() > depth {
4091                            self.frames.pop();
4092                        }
4093                        return Err(Signal::Throw(value));
4094                    }
4095                    // A handler lives on the stack of the frame that is throwing —
4096                    // `catch` pushed it there — so this frame gets the first chance
4097                    // to catch before it is popped.
4098                    let value = value;
4099                    loop {
4100                        if self.frames.len() <= depth {
4101                            return Err(Signal::Throw(value));
4102                        }
4103                        if self.catch_here(value.clone()).is_some() {
4104                            break;
4105                        }
4106                        self.frames.pop();
4107                    }
4108                }
4109                // A `yield` in a frame that `execute` is running directly means a
4110                // generator body was entered as an ordinary call, which only happens if
4111                // the generator check in `call_or_push` was bypassed.
4112                Ok(Step::Suspend(_)) => {
4113                    return Err(Signal::Throw(self.make_error(
4114                        "InternalError",
4115                        "a generator body ran as an ordinary call",
4116                    )));
4117                }
4118                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4119            }
4120        }
4121    }
4122
4123    /// Install a handler for `value` if this frame has one, resuming at it.
4124    ///
4125    /// The scan is the reference's: walk the frame's stack downwards looking for the
4126    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4127    /// `0` is an enumerator marker rather than a handler — it exists so that a
4128    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4129    /// here and the unwinding continues.
4130    fn catch_here(&mut self, value: Value) -> Option<()> {
4131        let frame = self.frames.last_mut()?;
4132        while let Some(top) = frame.stack.pop() {
4133            if let Value::CatchOffset(offset) = top {
4134                if offset == 0 {
4135                    continue;
4136                }
4137                frame.stack.push(value);
4138                frame.pc = offset as usize;
4139                return Some(());
4140            }
4141        }
4142        None
4143    }
4144
4145    fn push_frame(
4146        &mut self,
4147        code: Gc<CompiledCode>,
4148        env: Gc<ClosureEnv>,
4149        this: Value,
4150        mut args: Vec<Value>,
4151        callee: Value,
4152    ) -> JsResult<()> {
4153        // Two bounds, and the byte budget is the one that decides in practice. The
4154        // reference's message is `stack overflow` on an `InternalError`, not V8's
4155        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4156        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4157        let frame_cost = Self::frame_cost(&code);
4158        let stack_base = self.stack_used();
4159        if self.frames.len() >= self.max_frames
4160            || stack_base.saturating_add(frame_cost) > self.stack_limit
4161        {
4162            return Err(Signal::Throw(
4163                self.make_error("InternalError", "stack overflow"),
4164            ));
4165        }
4166        let arg_count = code.code.args.len();
4167        // How many were actually passed, which `arguments.length` reports and
4168        // `assert(x)` depends on: a call with one argument must not look like a call
4169        // with one argument and an explicit `undefined`.
4170        let passed = args.len();
4171        // Missing arguments are `undefined` in their slots; extra ones are dropped
4172        // from the slots but still reachable through `arguments`.
4173        //
4174        // A call that passes no more than the declared parameters needs **no** copy:
4175        // after the resize below, `args[..passed]` *is* the passed values. Only the
4176        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4177        // the rare case. This used to copy every call: one `Value` clone per argument
4178        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4179        let passed_overflow = (passed > arg_count).then(|| {
4180            let mut values = self.take_values(passed, Value::Undefined);
4181            values[..passed].clone_from_slice(&args[..passed]);
4182            values
4183        });
4184        // Only when the counts differ, which for the overwhelmingly common call — as many
4185        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4186        // lengths is two length compares and nothing else, but this is the hottest few
4187        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4188        if passed != arg_count {
4189            args.resize(arg_count, Value::Undefined);
4190            args.truncate(arg_count);
4191        }
4192        let cell_count = code.code.var_ref_count as usize;
4193        let mut cells = Vec::with_capacity(cell_count);
4194        for _ in 0..cell_count {
4195            cells.push(self.new_cell(Value::Undefined));
4196        }
4197        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4198        // A captured argument lives in its cell, not in the argument slot, so the
4199        // incoming value has to be moved there before the body runs.
4200        for (slot, cell) in code.arg_cell.iter().enumerate() {
4201            if *cell >= 0
4202                && let Some(value) = args.get(slot).cloned()
4203            {
4204                cells[*cell as usize].set(value);
4205            }
4206        }
4207        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4208        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4209        // reports `object`. Strict mode passes the value through untouched.
4210        let this = if code.code.strict {
4211            this
4212        } else if this.is_nullish() {
4213            Value::Object(self.realm.global.clone())
4214        } else if matches!(this, Value::Object(_)) {
4215            this
4216        } else {
4217            match crate::builtins::this_object(self, &this) {
4218                Ok(boxed) => Value::Object(boxed),
4219                Err(_) => this,
4220            }
4221        };
4222        let stack_depth = code.code.stack_size as usize + 1;
4223        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4224        // out of the same recycle pool the locals did.
4225        let stack = self.take_values(stack_depth, Value::Undefined);
4226        self.frames.push(Frame {
4227            code,
4228            env,
4229            this,
4230            args,
4231            passed_count: passed,
4232            passed_overflow: passed_overflow.map(Box::new),
4233            locals,
4234            cells,
4235            local_vars: None,
4236            // Exactly the depth the compiler computed, so the operand stack never
4237            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4238            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4239            // the buffer between calls, so "exactly" costs nothing after the first one.
4240            stack,
4241            pc: 0,
4242            at: 0,
4243            callee,
4244            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4245            cost: frame_cost,
4246            stack_base,
4247            tail: false,
4248        });
4249        Ok(())
4250    }
4251
4252    /// A value buffer of `len` slots, from the recycle pool when there is one.
4253    ///
4254    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4255    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4256        // A frame with no locals asks for nothing, and that is most frames: taking a
4257        // buffer out of the pool, clearing it and resizing it to zero is four operations
4258        // and a pool pop for an empty `Vec`, which is free to construct.
4259        if len == 0 {
4260            return Vec::new();
4261        }
4262        let mut buffer = self.free_values.pop().unwrap_or_default();
4263        buffer.clear();
4264        buffer.resize(len, fill);
4265        buffer
4266    }
4267
4268    /// Return a finished frame's value buffers for the next call to reuse.
4269    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4270        for mut buffer in [
4271            std::mem::take(&mut frame.locals),
4272            frame
4273                .passed_overflow
4274                .take()
4275                .map(|buffer| *buffer)
4276                .unwrap_or_default(),
4277            std::mem::take(&mut frame.stack),
4278        ] {
4279            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4280            // GC root: it kept every value the frame held reachable, which is invisible
4281            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4282            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4283            // exactly that within one run — the target `{}` of a finished IIFE was still
4284            // in its operand stack, in the pool.
4285            buffer.clear();
4286            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4287            // fill the pool with nothing to offer.
4288            if free_values.len() < RECYCLE_SLOTS
4289                && buffer.capacity() > 0
4290                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4291            {
4292                free_values.push(buffer);
4293            }
4294        }
4295    }
4296
4297    /// Pop a finished frame and keep its buffers.
4298    ///
4299    /// Every place that drops a frame goes through here: a recycled buffer is also where
4300    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4301    /// nothing but the reuse.
4302    fn pop_frame(&mut self) -> Option<()> {
4303        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4304        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4305        let last = self.frames.len().checked_sub(1)?;
4306        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4307        self.frames.truncate(last);
4308        Some(())
4309    }
4310
4311    /// Poll the host's interrupt handler, if one is installed.
4312    ///
4313    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4314    /// one `Option` test, and with no handler installed the whole function is that test —
4315    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4316    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4317    #[inline]
4318    fn check_interrupt(&mut self) -> JsResult<()> {
4319        if self.interrupt.is_none() {
4320            return Ok(());
4321        }
4322        if self.interrupt_counter > 0 {
4323            self.interrupt_counter -= 1;
4324            return Ok(());
4325        }
4326        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4327        // The closure is taken out for the duration so that a handler which re-enters the
4328        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4329        let mut handler = self.interrupt.take().expect("checked above");
4330        let abort = handler();
4331        self.interrupt = Some(handler);
4332        if abort {
4333            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4334            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4335            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4336            // documentation says.
4337            self.uncatchable = true;
4338            return Err(Signal::Throw(
4339                self.make_error("InternalError", "interrupted"),
4340            ));
4341        }
4342        Ok(())
4343    }
4344
4345    /// A memory checkpoint: does the heap still fit under its limit?
4346    ///
4347    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4348    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4349    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4350    /// only at calls would let it run until the machine died, which is the exact failure
4351    /// `--memory-limit` exists to prevent.
4352    ///
4353    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4354    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4355    /// script that catches it, drops the reference and carries on is legitimate: measured
4356    /// on `qjs --memory-limit 1M`, the engine recovers.
4357    fn check_memory(&mut self) -> JsResult<()> {
4358        // One `Cell` read and a predictable branch when no limit is set, and an integer
4359        // compare when one is. Containers report their own growth as it happens
4360        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4361        // walking it here was the first version and it was O(live) per 256 instructions,
4362        // which turned a 100k-element push loop into a five-minute one.
4363        let Some(limit) = self.heap.memory_limit() else {
4364            return Ok(());
4365        };
4366        let used = self.heap.used_bytes();
4367        if used <= limit {
4368            // Back under the limit — a collection or a dropped reference did it. The next
4369            // time it goes over is a new failure, not a repeat of this one.
4370            self.oom_reported_at = 0;
4371            return Ok(());
4372        }
4373        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4374        // block runs normally after `out of memory` — it allocates nothing, so nothing
4375        // fails. A check that re-fired on every instruction made the handler itself throw,
4376        // which is a dead end: the error became unobservable from script.
4377        //
4378        // Comparing against the total at the last report gives the same behaviour: the
4379        // handler runs while the total is unchanged, and the very next allocation over the
4380        // limit fails.
4381        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4382        {
4383            return Ok(());
4384        }
4385        self.oom_reported_at = used;
4386        Err(Signal::Throw(
4387            self.make_error("InternalError", "out of memory"),
4388        ))
4389    }
4390
4391    /// Fail before allocating `payload` bytes, if they would not fit.
4392    ///
4393    /// For the allocations whose size comes from script data — `new Array(n)`,
4394    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4395    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4396    /// answering NULL for the one big request.
4397    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4398        if self.heap.fits(payload) {
4399            return Ok(());
4400        }
4401        Err(Signal::Throw(
4402            self.make_error("InternalError", "out of memory"),
4403        ))
4404    }
4405
4406    /// Bytes of frame state the live call chain accounts for.
4407    pub fn stack_used(&self) -> usize {
4408        match self.frames.last() {
4409            Some(frame) => frame.stack_base + frame.cost,
4410            None => 0,
4411        }
4412    }
4413
4414    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4415    ///
4416    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4417    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4418    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4419    /// instead. That is the whole difference between the two models: it rations C stack, we
4420    /// ration frame state, and both quantities are dominated by the value slots — which is
4421    /// why the two depths come out comparable rather than merely proportional.
4422    fn frame_cost(code: &CompiledCode) -> usize {
4423        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4424        std::mem::size_of::<Frame>()
4425            + std::mem::size_of::<Value>() * slots
4426            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4427    }
4428
4429    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4430    ///
4431    /// Only names the eval created are here: a name the frame already declared statically
4432    /// is written through to its own slot instead, so this cannot shadow a real local.
4433    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4434        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4435        let (local_vars, phase) = self.visible_local_vars()?;
4436        if !local_vars.contains(name) {
4437            return None;
4438        }
4439        local_vars.get(name, phase)
4440    }
4441
4442    /// The variables a direct `eval` declared, as the code currently running sees them.
4443    ///
4444    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4445    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4446    /// else it is the current frame's, falling back to the frame the closure was created
4447    /// in.
4448    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4449    ///
4450    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4451    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4452    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4453    /// just to be asked `is_none`.
4454    fn has_visible_local_vars(&self) -> bool {
4455        let index = match self.eval_caller.flatten() {
4456            Some(caller) => caller,
4457            None => match self.frames.len().checked_sub(1) {
4458                Some(top) => top,
4459                None => return false,
4460            },
4461        };
4462        match self.frames.get(index) {
4463            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4464            None => false,
4465        }
4466    }
4467
4468    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4469        // While an `eval` runs, its own frame is on top but its variable environment is
4470        // the *caller's* — so the caller is what the lookup has to start from.
4471        let (index, phase) = match self.eval_caller.flatten() {
4472            Some(caller) => (
4473                caller,
4474                if self.in_parameter_list_at(caller) {
4475                    0
4476                } else {
4477                    1
4478                },
4479            ),
4480            None => (
4481                self.frames.len().checked_sub(1)?,
4482                if self.in_parameter_list() { 0 } else { 1 },
4483            ),
4484        };
4485        let frame = self.frames.get(index)?;
4486        // The frame's own variables, or — for an arrow, which has no variable environment
4487        // of its own — the one it was created in, which `ClosureEnv` carries.
4488        if let Some(local_vars) = frame.local_vars.clone() {
4489            return Some((local_vars, phase));
4490        }
4491        frame
4492            .env
4493            .local_vars
4494            .clone()
4495            .map(|local_vars| (local_vars, frame.env.local_phase))
4496    }
4497
4498    /// Whether the innermost frame is still evaluating its parameter list.
4499    ///
4500    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4501    /// and a closure created there may only see that much of [`LocalVars`].
4502    fn in_parameter_list(&self) -> bool {
4503        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4504    }
4505
4506    /// [`Interp::in_parameter_list`] for a specific frame.
4507    fn in_parameter_list_at(&self, frame: usize) -> bool {
4508        let Some(frame) = self.frames.get(frame) else {
4509            return false;
4510        };
4511        let code = &frame.code.code;
4512        if !code.has_parameter_expressions {
4513            return false;
4514        }
4515        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4516        // function as its body and let a direct `eval` act accordingly.
4517        if code.body_start == (0, 0) {
4518            return false;
4519        }
4520        match code.position_at(frame.at as u32) {
4521            Some(position) => position < code.body_start,
4522            None => false,
4523        }
4524    }
4525
4526    fn frame(&self) -> &Frame {
4527        self.frames.last().expect("a frame is live")
4528    }
4529
4530    fn frame_mut(&mut self) -> &mut Frame {
4531        self.frames.last_mut().expect("a frame is live")
4532    }
4533
4534    // -- slot access --------------------------------------------------------
4535
4536    /// Move a local's value out, leaving `undefined` in the slot.
4537    ///
4538    /// `None` for a captured slot: its value lives in a cell shared with every closure
4539    /// that closed over it, so it can never be exclusively ours and must not be taken.
4540    ///
4541    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4542    /// for every read and fatal for this one — a clone is exactly the second handle that
4543    /// rules out growing the string in place.
4544    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4545        let frame = self.frames.last_mut()?;
4546        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4547            return None;
4548        }
4549        frame
4550            .locals
4551            .get_mut(slot)
4552            .map(|value| std::mem::replace(value, Value::Undefined))
4553    }
4554
4555    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4556    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4557    ///
4558    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4559    /// it** — the value is put back before the general path runs — so a `valueOf` that
4560    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4561    /// error as it would have without the fusion. This is why the in-place attempt is a
4562    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4563    /// a wrong answer with a good excuse.
4564    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4565        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4566        // is put back on every path that does not append. An earlier version wrote the two
4567        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4568        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4569        // through with its value already taken and dropped: the general path below then
4570        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4571        // A wrong answer, from an optimisation, with every test green.
4572        if matches!(right, Value::String(_))
4573            && let Some(taken) = self.take_loc(slot)
4574        {
4575            if let Value::String(mut left) = taken {
4576                let appended = match left.get_mut() {
4577                    Some(string) => string.append_in_place(
4578                        // The pattern is the one `matches!` just checked.
4579                        match &right {
4580                            Value::String(text) => text,
4581                            _ => unreachable!("guarded above"),
4582                        },
4583                    ),
4584                    None => None,
4585                };
4586                self.put_loc(slot, Value::String(left));
4587                if let Some(added) = appended {
4588                    // The buffer grew where it stood, so the heap's running total has to
4589                    // be told: `measure_used` would report the new length, and the two must
4590                    // agree or the subtraction at free time leaves the counter wrong.
4591                    self.heap.adjust_payload(added as isize);
4592                    return Ok(());
4593                }
4594            } else {
4595                self.put_loc(slot, taken);
4596            }
4597        }
4598        // The two-number case, without an operand stack round trip. Everything below
4599        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4600        // store it — five operations and two `Value` clones for what is one integer add.
4601        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4602        // for string append and never got the numeric half, so `t += i` — a counting loop
4603        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4604        let left = self.get_loc(slot);
4605        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4606            self.put_loc(
4607                slot,
4608                match a.checked_add(*b) {
4609                    Some(sum) => Value::Int(sum),
4610                    None => Value::Float(*a as f64 + *b as f64),
4611                },
4612            );
4613            return Ok(());
4614        }
4615        self.push(left);
4616        self.push(right);
4617        self.binary_add()?;
4618        let value = self.pop();
4619        self.put_loc(slot, value);
4620        Ok(())
4621    }
4622
4623    fn get_arg(&self, slot: usize) -> Value {
4624        self.frame().read_arg(slot)
4625    }
4626
4627    fn put_arg(&mut self, slot: usize, value: Value) {
4628        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4629        if cell == -1 {
4630            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4631                *slot = value;
4632            }
4633        } else {
4634            self.frame().cells[cell as usize].set(value);
4635        }
4636    }
4637
4638    fn get_loc(&self, slot: usize) -> Value {
4639        // The cell mapping is `-1` for every slot that was not captured — which is all of
4640        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4641        // so the common case is one array read and a clone: 20% of every loop iteration
4642        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4643        // sample of `dispatch:arith`).
4644        self.frame().read_loc(slot)
4645    }
4646
4647    fn put_loc(&mut self, slot: usize, value: Value) {
4648        // One borrow instead of three, and the cell check on the frame we already hold.
4649        let frame = self.frames.last_mut().expect("a frame is live");
4650        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4651        if cell < 0 {
4652            if let Some(slot) = frame.locals.get_mut(slot) {
4653                *slot = value;
4654            }
4655        } else if let Some(cell) = frame.cells.get(cell as usize) {
4656            cell.set(value);
4657        }
4658    }
4659
4660    // -- globals ------------------------------------------------------------
4661
4662    /// The name a global-slot operand refers to.
4663    fn global_name(&self, slot: usize) -> String {
4664        self.frame()
4665            .code
4666            .code
4667            .closure_vars
4668            .get(slot)
4669            .map(|c| c.name.clone())
4670            .unwrap_or_default()
4671    }
4672
4673    /// The facts about a global binding that decide where it lives.
4674    ///
4675    /// A script's globals split in two, and the split is observable: `var` and
4676    /// function declarations become properties of the global object (`globalThis.v`
4677    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4678    /// declarations live in the global *lexical* environment and are invisible there
4679    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4680    /// `is_lexical` flag means the answer is already in the bytecode.
4681    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4682        let name = self.global_name(slot);
4683        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4684        // while forwarding a reference through a nested function is built with the
4685        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4686        // closure. Presence in the realm's lexical table is the same fact, recorded
4687        // once, and every slot sees it.
4688        let lexical = self.realm.globals.contains_key(&name);
4689        let is_const = self.realm.lexical_consts.contains(&name);
4690        (name, lexical, is_const)
4691    }
4692
4693    /// The value of `name` in the innermost active `with` object, if any.
4694    ///
4695    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4696    /// innermost frame first and innermost block first within one. Walking frames rather
4697    /// than keeping a separate stack is what makes a closure called from inside a `with`
4698    /// see it, and what keeps the object alive only as long as the block is.
4699    /// The innermost active `with` object that has `name`, if any.
4700    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4701        let objects = self.eval_with.clone().unwrap_or_default();
4702        for object in objects {
4703            let key = self.string(name.to_string());
4704            if self
4705                .has_property(&key, &Value::Object(object.clone()))
4706                .ok()?
4707            {
4708                return Some(object);
4709            }
4710        }
4711        None
4712    }
4713
4714    /// Every active `with` object, innermost first.
4715    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4716        let mut objects = Vec::new();
4717        for frame in self.frames.iter().rev() {
4718            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4719                if var.kind != js_compile::VarKind::With {
4720                    continue;
4721                }
4722                // A captured binding lives in its cell and not in the slot list, so the
4723                // cell is consulted first — a closure created inside the block is exactly
4724                // what makes the object captured. Before the store runs the slot still
4725                // holds `undefined`, and a `with` object is always boxed, so a non-object
4726                // entry is simply not in scope yet.
4727                let value = frame
4728                    .code
4729                    .loc_cell
4730                    .get(index)
4731                    .copied()
4732                    .filter(|cell| *cell >= 0)
4733                    .and_then(|cell| frame.cells.get(cell as usize))
4734                    .map(|cell| cell.get())
4735                    .or_else(|| frame.locals.get(index).cloned());
4736                if let Some(Value::Object(object)) = value {
4737                    objects.push(object);
4738                }
4739            }
4740        }
4741        objects
4742    }
4743
4744    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4745        for object in self.eval_with.clone().unwrap_or_default() {
4746            let key = self.string(name.to_string());
4747            if self.has_property(&key, &Value::Object(object.clone()))? {
4748                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4749            }
4750        }
4751        Ok(None)
4752    }
4753
4754    /// Whether every scope between here and the global object is an ordinary one.
4755    ///
4756    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4757    /// bytecode resolved; when any is live the general path has to run in full order. When
4758    /// none is — every ordinary program — a global read is a property read and nothing
4759    /// else, and that is worth caching.
4760    fn scopes_are_plain(&self) -> bool {
4761        self.eval_caller.is_none()
4762            && self.eval_with.is_none()
4763            && self.eval_arguments.is_none()
4764            && self.eval_bindings.is_empty()
4765            && self.eval_scope.is_none()
4766            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4767            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4768            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4769            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4770            // upstream corpus caught and no unit test did.
4771            && !self.has_visible_local_vars()
4772            && self.frame().env.eval_scope.is_none()
4773    }
4774
4775    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4776        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4777        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4778        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4779        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4780        // borrow outlive the `&mut self` the lookup needs.
4781        //
4782        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4783        // forwarded through a nested function has its flags cleared, so the flag cannot
4784        // be believed.
4785        let code = self.frame().code.clone();
4786        let name = code
4787            .code
4788            .closure_vars
4789            .get(slot)
4790            .map(|c| c.name.as_str())
4791            .unwrap_or_default();
4792        let lexical = self.realm.globals.contains_key(name);
4793        // The common case, first: an ordinary global `var`, with a cache in front of the
4794        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4795        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4796        // cache hit and return without touching any of it.
4797        if !lexical && self.scopes_are_plain() {
4798            return self.get_plain_global(name, slot);
4799        }
4800        if name == "arguments"
4801            && let Some(arguments) = &self.eval_arguments
4802        {
4803            return Ok(arguments.clone());
4804        }
4805        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4806        // the objects live when the eval started are consulted before anything else. The
4807        // snapshot is taken at entry rather than scanning the frames on every read: a
4808        // block that has already finished still leaves its object in the slot, and a
4809        // bytecode read outside the block must not see it.
4810        if let Some(value) = self.with_lookup(name)? {
4811            return Ok(value);
4812        }
4813        // A variable a direct `eval` declared shadows everything the compiler resolved,
4814        // including an enclosing function's binding: the eval put it in the caller's own
4815        // variable environment, which is nearer than any captured scope.
4816        if let Some((local_vars, phase)) = self.visible_local_vars()
4817            && let Some(cell) = local_vars.get(name, phase)
4818        {
4819            return Ok(cell.get());
4820        }
4821        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4822        // its local `a` wins over a global `a`.
4823        if let Some(value) = self.eval_binding_value(name) {
4824            return Ok(value);
4825        }
4826        // A closure created by an `eval` resolves its free names against the bindings
4827        // that eval saw, even after the eval (and its frames) are gone.
4828        if let Some(cell) = self
4829            .frame()
4830            .env
4831            .eval_scope
4832            .as_ref()
4833            .and_then(|scope| scope.get(name))
4834        {
4835            let value = cell.get();
4836            if matches!(value, Value::Uninitialized) {
4837                return Err(self.throw_reference(name));
4838            }
4839            return Ok(value);
4840        }
4841        // A binding declared by the strict `eval` currently running shadows anything
4842        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4843        if let Some(scope) = &self.eval_scope
4844            && let Some(value) = scope.get(name)
4845        {
4846            return Ok(value.clone());
4847        }
4848        if lexical {
4849            // A lexical global is a binding in a side table, so the dead zone is
4850            // visible and it is nowhere on the global object.
4851            if let Some(cell) = self.realm.globals.get(name) {
4852                let value = cell.get();
4853                if matches!(value, Value::Uninitialized) {
4854                    return Err(self.throw_reference(name));
4855                }
4856                return Ok(value);
4857            }
4858            return Err(self.throw_reference(name));
4859        }
4860        // A `var` global is an ordinary property, so the prototype chain and the
4861        // global object's own builtins are all reachable through it.
4862        match self.get_property(&self.realm.global.clone(), name)? {
4863            Some(value) => Ok(value),
4864            None => Err(self.throw_reference(name)),
4865        }
4866    }
4867
4868    /// Read a plain global `var`: a cached own data property, or the full lookup.
4869    ///
4870    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4871    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4872    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4873        let object = self.realm.global.clone();
4874        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4875        if let Some(cached) = &self.global_cache[site]
4876            && object.upgrades_to(&cached.object)
4877            && let Some(value) = object.data_property_at(cached.index, name)
4878        {
4879            return Ok(value);
4880        }
4881        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4882        // chain exactly as before, then remember the answer if it is worth remembering.
4883        let Some(value) = self.get_property(&object, name)? else {
4884            return Err(self.throw_reference(name));
4885        };
4886        if let Some(index) = object.own_data_index(name) {
4887            self.global_cache[site] = Some(GlobalCache {
4888                object: object.downgrade(),
4889                index,
4890            });
4891        }
4892        Ok(value)
4893    }
4894
4895    /// Store to a global binding.
4896    ///
4897    /// Returns a signal when the store is refused: a `const` global may only be
4898    /// written by its initialiser, and a non-configurable `var` global may not be
4899    /// deleted but is always writable.
4900    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4901        let (name, lexical, is_const) = self.global_binding(slot);
4902
4903        // An assignment inside a `with` writes through to the object that supplies the
4904        // name, which for an `eval` means consulting the same chain `get_global` does.
4905        if let Some(owner) = self.with_owner(&name) {
4906            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4907            return Ok(());
4908        }
4909        // A variable the running eval *declared* takes the write before any caller
4910        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4911        // environment even when an enclosing function has a `var c` of its own.
4912        if self.eval_caller.flatten().is_some()
4913            && let Some((local_vars, phase)) = self.visible_local_vars()
4914            && local_vars.contains(&name)
4915            && let Some(cell) = local_vars.get(&name, phase)
4916        {
4917            cell.set(value);
4918            return Ok(());
4919        }
4920        // A binding of the frame that called `eval` takes the write, which is what
4921        // makes `f("a = 3")` change the caller's `a`.
4922        if self.set_eval_binding(&name, &value)? {
4923            return Ok(());
4924        }
4925        // A closure that outlived its `eval` writes through to the same cell it reads.
4926        if let Some(cell) = self
4927            .frame()
4928            .env
4929            .eval_scope
4930            .as_ref()
4931            .and_then(|scope| scope.get(&name))
4932            .cloned()
4933        {
4934            cell.set(value);
4935            return Ok(());
4936        }
4937        // Inside a strict `eval`, a name it declared itself is stored there. An
4938        // *assignment* to a name nobody declared is not a declaration, so it falls
4939        // through: strict mode raises `ReferenceError` for it, which is what
4940        // `eval("1 + (@not_def = 1)")` has to do.
4941        if let Some(scope) = self.eval_scope.as_mut()
4942            && scope.contains_key(&name)
4943        {
4944            scope.insert(name, value);
4945            return Ok(());
4946        }
4947        if lexical {
4948            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4949                if is_const && !matches!(cell.get(), Value::Uninitialized) {
4950                    return Err(self.read_only_global(&name));
4951                }
4952                cell.set(value);
4953                return Ok(());
4954            }
4955            // Writing an undeclared lexical global is a `ReferenceError` in strict
4956            // mode and a silent global creation otherwise; creating the cell here
4957            // keeps both paths from losing the value.
4958            let cell = self.new_cell(value);
4959            self.realm.globals.insert(name, cell);
4960            return Ok(());
4961        }
4962        // A variable a direct `eval` declared in this call shadows the global object, even
4963        // when the global already has a property of that name — `var c = "global"` at the
4964        // top level must not capture `eval("var c = 1")` inside a function.
4965        if let Some((local_vars, phase)) = self.visible_local_vars()
4966            && local_vars.contains(&name)
4967            && let Some(cell) = local_vars.get(&name, phase)
4968        {
4969            cell.set(value);
4970            return Ok(());
4971        }
4972        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
4973        // remembered a global's slot index since M12b, but the *store* side never did: it
4974        // converted the name to a `PropertyKey` (two allocations) and then scanned the
4975        // global object's whole table — which holds every builtin — on every assignment to
4976        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
4977        // full global lookup per iteration; measured with a counter, `s` as a global made
4978        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
4979        //
4980        // Re-validated exactly like the read: same object, same index, still the name, and
4981        // — the one extra check a store needs — still writable. A global that is an
4982        // accessor, non-writable, or inherited fails here and falls through to the full
4983        // path below, which reports the failure the way it always did.
4984        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4985        let global = self.realm.global.clone();
4986        if let Some(cached) = &self.global_cache[site]
4987            && global.upgrades_to(&cached.object)
4988            && global.write_data_at(cached.index, &name, value.clone())
4989        {
4990            return Ok(());
4991        }
4992        match global.own_property(&name) {
4993            // A `var` global is writable, so the store goes straight through — but
4994            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4995            // store (a non-writable or accessor-without-setter global) is a silent
4996            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4997            // split every other assignment has.
4998            Some(_) => {
4999                let on_failure = if self.current_strict() {
5000                    DeleteFailure::Throw
5001                } else {
5002                    DeleteFailure::Ignore
5003                };
5004                let result = self.set_property_with(&global, &name, value, on_failure);
5005                // Teach the cache the slot for a plain writable own data property, which is
5006                // what a declared `var` is. Without this the fast path above could never
5007                // fire for a global that is only ever *written* — its entry would have to
5008                // be put there by a read of the same slot, and a write-only loop has none.
5009                if result.is_ok()
5010                    && let Some(index) = global.own_data_index(&name)
5011                {
5012                    self.global_cache[site] = Some(GlobalCache {
5013                        object: global.downgrade(),
5014                        index,
5015                    });
5016                }
5017                result
5018            }
5019            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5020            // declaration creates a *configurable* property, which is what makes it
5021            // deletable and is the one way a global differs from a declared `var`.
5022            // In strict mode the same store is a `ReferenceError` instead: that is the
5023            // whole point of strict mode, and creating the global silently meant
5024            // `"use strict"; x = 1` looked like it worked.
5025            None => {
5026                if self.current_strict() {
5027                    return Err(self.throw_reference(&name));
5028                }
5029                // A direct eval declares here rather than on the global object: its
5030                // `var`s belong to the caller's variable environment. `declare_eval_local`
5031                // also covers a plain assignment to a variable an earlier eval made.
5032                if let Some(cell) = self.declare_eval_local(&name) {
5033                    cell.set(value);
5034                    return Ok(());
5035                }
5036                global.define_data(&name, value);
5037                Ok(())
5038            }
5039        }
5040    }
5041
5042    /// The value of a binding of the frame that called `eval`, if there is one.
5043    fn eval_binding_value(&self, name: &str) -> Option<Value> {
5044        let binding = self
5045            .eval_bindings
5046            .iter()
5047            .find(|binding| binding.name == name)?;
5048        let owner = self.frames.get(binding.frame)?;
5049        let (slot, index) = (binding.slot, binding.index);
5050        Some(match slot {
5051            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5052                cell if cell >= 0 => owner
5053                    .cells
5054                    .get(cell as usize)
5055                    .map(|cell| cell.get())
5056                    .unwrap_or(Value::Undefined),
5057                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5058            },
5059            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5060                cell if cell >= 0 => owner
5061                    .cells
5062                    .get(cell as usize)
5063                    .map(|cell| cell.get())
5064                    .unwrap_or(Value::Undefined),
5065                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5066            },
5067        })
5068    }
5069
5070    /// Write to a binding of the frame that called `eval`.
5071    ///
5072    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5073    /// matched binding can still refuse the store, which is why this is fallible: a
5074    /// `const` is read-only everywhere, and a named function expression's own name is
5075    /// read-only in strict mode.
5076    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5077        let Some(binding) = self
5078            .eval_bindings
5079            .iter()
5080            .find(|binding| binding.name == name)
5081        else {
5082            return Ok(false);
5083        };
5084        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5085        let strict = self.current_strict();
5086        let Some(owner) = self.frames.get_mut(frame) else {
5087            return Ok(false);
5088        };
5089        match slot {
5090            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5091                cell if cell >= 0 => {
5092                    if let Some(cell) = owner.cells.get(cell as usize) {
5093                        cell.set(value.clone());
5094                    }
5095                }
5096                _ => {
5097                    if let Some(slot) = owner.args.get_mut(index) {
5098                        *slot = value.clone();
5099                    }
5100                }
5101            },
5102            EvalSlot::Local => {
5103                let declared = owner.code.code.vars.get(index);
5104                // A `const` is read-only even through `eval`. The realm records this for
5105                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5106                // the bytecode, so this is where it has to be enforced.
5107                if declared.is_some_and(|var| var.is_const) {
5108                    return Err(self.read_only_local(name));
5109                }
5110                // The name of a named function expression is read-only too, but only
5111                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5112                // such a name is ignored, the same as a direct store would be.
5113                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5114                    return if strict {
5115                        Err(self.read_only_local(name))
5116                    } else {
5117                        Ok(true)
5118                    };
5119                }
5120                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5121                    cell if cell >= 0 => {
5122                        if let Some(cell) = owner.cells.get(cell as usize) {
5123                            cell.set(value.clone());
5124                        }
5125                    }
5126                    _ => {
5127                        if let Some(slot) = owner.locals.get_mut(index) {
5128                            *slot = value.clone();
5129                        }
5130                    }
5131                }
5132            }
5133        }
5134        Ok(true)
5135    }
5136
5137    /// The `TypeError` an assignment to a read-only binding raises.
5138    fn read_only_local(&self, name: &str) -> Signal {
5139        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5140    }
5141
5142    /// Declare `name` as a variable of the frame that called the running `eval`.
5143    ///
5144    /// `None` when there is no direct eval in progress, or it was called from the top
5145    /// level — then the caller's variable environment *is* the global one and the
5146    /// existing path is right.
5147    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5148        let caller = self.eval_caller.flatten()?;
5149        // The bottom frame is the top-level script, whose variable environment *is* the
5150        // global one — so `eval("var x = 1")` at the top level still creates a global.
5151        if caller == 0 {
5152            return None;
5153        }
5154        // A name the eval's *own* variable environment already binds is not a new
5155        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5156        // `arguments`, and creating a second binding would leave the first — the one
5157        // closures read — untouched. A binding of an *outer* frame does not count: a
5158        // declaration shadows it rather than writing through.
5159        if self
5160            .eval_bindings
5161            .iter()
5162            .any(|binding| binding.name == name && binding.frame == caller)
5163        {
5164            return None;
5165        }
5166        let phase = if self.in_parameter_list_at(caller) {
5167            0
5168        } else {
5169            1
5170        };
5171        self.frame_local_vars(caller)?;
5172        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5173        if let Some(cell) = local_vars.get(name, 1) {
5174            return Some(cell);
5175        }
5176        let cell = self.new_cell(Value::Undefined);
5177        Some(local_vars.declare(name, phase, cell))
5178    }
5179
5180    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5181    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5182        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5183            return Some(local_vars.clone());
5184        }
5185        let local_vars = Gc::new(self.heap, LocalVars::new());
5186        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5187        Some(local_vars)
5188    }
5189
5190    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5191    /// property of the global object. Used to decide whether a store inside an
5192    /// `eval` writes through to the realm or declares a binding of its own.
5193    ///
5194    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5195    /// write to `Object.prototype.toString`, and must not shadow it either.
5196    fn global_knows(&mut self, name: &str) -> bool {
5197        if self.realm.globals.contains_key(name) {
5198            return true;
5199        }
5200        self.realm.global.own_property(name).is_some()
5201    }
5202
5203    /// Whether the code currently running is strict.
5204    ///
5205    /// Read off the frame's function, which is where the parser's answer ended up; a
5206    /// native function never runs strict-only checks, and there is no frame at all
5207    /// before the first script.
5208    pub fn current_strict(&self) -> bool {
5209        self.frames
5210            .last()
5211            .is_some_and(|frame| frame.code.code.strict)
5212    }
5213
5214    /// Initialise a declared global, which is what ends its dead zone.
5215    ///
5216    /// A `var` global becomes a property of the global object: writable, so a later
5217    /// assignment goes through, and non-configurable, so `delete` refuses.
5218    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5219        let (name, lexical, _) = self.global_binding(slot);
5220        // A `var` declared by the strict `eval` currently running belongs to the
5221        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5222        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5223        // initialised in place, which is what a re-declaration inside eval does.
5224        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5225            self.eval_scope
5226                .as_mut()
5227                .expect("checked above")
5228                .insert(name, value);
5229            return Ok(());
5230        }
5231        if let Some(scope) = self.eval_scope.as_mut()
5232            && scope.contains_key(&name)
5233        {
5234            scope.insert(name, value);
5235            return Ok(());
5236        }
5237        if lexical {
5238            // The cell exists (created at declaration time) holding the dead-zone
5239            // marker; storing the value is what makes the binding readable.
5240            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5241                cell.set(value);
5242                return Ok(());
5243            }
5244            let cell = self.new_cell(value);
5245            self.realm.globals.insert(name, cell);
5246            return Ok(());
5247        }
5248        let global = self.realm.global.clone();
5249        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5250        // to answer `false` and leave the binding in place. `with_attributes` ties
5251        // `configurable` to `writable`, so the property is built field by field.
5252        global.define(
5253            &name,
5254            Property {
5255                value: Some(value),
5256                writable: true,
5257                enumerable: true,
5258                configurable: false,
5259                ..Property::default()
5260            },
5261        );
5262        Ok(())
5263    }
5264
5265    /// The `TypeError` a store to a `const` global raises.
5266    fn read_only_global(&self, name: &str) -> Signal {
5267        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5268    }
5269
5270    // -- properties ---------------------------------------------------------
5271
5272    /// Read `object[key]`, following the prototype chain.
5273    ///
5274    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5275    /// lookup returns the owner rather than just the value.
5276    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5277        self.get_property_key(object, &PropertyKey::from(key))
5278    }
5279
5280    /// [`Interp::get_property`] with a key that may be a symbol.
5281    pub fn get_property_key(
5282        &mut self,
5283        object: &Gc<JsObject>,
5284        key: &PropertyKey,
5285    ) -> JsResult<Option<Value>> {
5286        self.get_property_key_for(object, None, key)
5287    }
5288
5289    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5290    ///
5291    /// The receiver matters when the property is found on a *prototype*: a getter has to
5292    /// see the object the read started from. For a primitive that is the primitive
5293    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5294    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5295    /// the owner.
5296    pub fn get_property_key_for(
5297        &mut self,
5298        object: &Gc<JsObject>,
5299        receiver: Option<&Value>,
5300        key: &PropertyKey,
5301    ) -> JsResult<Option<Value>> {
5302        // A proxy answers for itself, before any of the shortcuts below: `new
5303        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5304        // have.
5305        if object.proxy_state().is_some() {
5306            let receiver = receiver
5307                .cloned()
5308                .unwrap_or_else(|| Value::Object(object.clone()));
5309            return self.proxy_get(object, &receiver, key);
5310        }
5311        // A host class's `get_property` trap replaces the whole read, prototype walk
5312        // included — that is what makes a native accessor free rather than a JavaScript
5313        // getter call.
5314        if let Some(exotic) = object.exotic() {
5315            let receiver_value = receiver
5316                .cloned()
5317                .unwrap_or_else(|| Value::Object(object.clone()));
5318            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5319                return Ok(Some(value));
5320            }
5321            // With no `get_property` trap, a `get_own_property` trap still answers for the
5322            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5323            // and the hook lives exactly there. A key the trap reports as absent is still
5324            // looked for on the prototype, which is why the search resumes *above*.
5325            if let Some(property) = exotic.get_own_property(self, object, key)? {
5326                return match property {
5327                    Some(property) => self.read_property(property, object, receiver),
5328                    None => match lookup_key_above(object, key) {
5329                        Some((_, property)) => self.read_property(property, object, receiver),
5330                        None => Ok(None),
5331                    },
5332                };
5333            }
5334        }
5335        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5336        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5337        // The `[[Get]]` short-circuit therefore belongs to this one arm.
5338        //
5339        // Constructibility is exactly the split the reference makes: `function f(){}` and
5340        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5341        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5342        // function" — it *is* the predicate, which is why no extra marker is needed.
5343        if let Some(text) = key.as_str()
5344            && (text == "caller" || text == "arguments")
5345            && object.is_constructor()
5346            && object.is_callable()
5347            && !object.is_bound_function()
5348            && object.own_property(text).is_none()
5349        {
5350            return Ok(Some(Value::Undefined));
5351        }
5352        // The element-vector and `length` shortcuts are string-only: an array index
5353        // has no symbol spelling.
5354        if let Some(text) = key.as_str() {
5355            if let Some(value) = self.own_element(object, text) {
5356                return Ok(Some(value));
5357            }
5358            // `length` is not stored as a property: an array's length is its element
5359            // count, and keeping one copy of it is what makes `push`/`pop` and
5360            // `a.length = n` agree.
5361            if let Some(length) = object.array_length()
5362                && text == "length"
5363            {
5364                // Not `Value::Int(length as i32)`: see [`length_value`].
5365                return Ok(Some(crate::object::length_value(length)));
5366            }
5367        }
5368        match lookup_key(object, key) {
5369            Some((_, property)) => self.read_property(property, object, receiver),
5370            None => Ok(None),
5371        }
5372    }
5373
5374    /// The value a property read answers.
5375    ///
5376    /// One place rather than three, because an accessor has to run with the *receiver* as
5377    /// `this` whether the descriptor came from the property table, an exotic
5378    /// `get_own_property` trap, or a prototype above one.
5379    fn read_property(
5380        &mut self,
5381        property: Property,
5382        object: &Gc<JsObject>,
5383        receiver: Option<&Value>,
5384    ) -> JsResult<Option<Value>> {
5385        if property.is_accessor() {
5386            match &property.getter {
5387                Some(getter) if !matches!(getter, Value::Undefined) => {
5388                    let receiver = receiver
5389                        .cloned()
5390                        .unwrap_or_else(|| Value::Object(object.clone()));
5391                    self.call_value(getter.clone(), receiver, Vec::new())
5392                        .map(Some)
5393                }
5394                // An accessor with no getter reads as `undefined`.
5395                _ => Ok(Some(Value::Undefined)),
5396            }
5397        } else {
5398            Ok(property.value)
5399        }
5400    }
5401
5402    /// `super.key` — start the search at `proto`, but report to `receiver`.
5403    ///
5404    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5405    /// found on the prototype of a class has to see the *instance* as `this`, and a
5406    /// plain property read off `proto` would lose that.
5407    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5408        let start = self.require_object(proto)?;
5409        let key = self.propkey(key)?;
5410        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5411        if matches!(proto, Value::Null) {
5412            return Ok(Value::Undefined);
5413        }
5414        match lookup_key(&start, &key) {
5415            Some((_, property)) if property.is_accessor() => match &property.getter {
5416                Some(getter) if !matches!(getter, Value::Undefined) => {
5417                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5418                }
5419                _ => Ok(Value::Undefined),
5420            },
5421            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5422            None => Ok(Value::Undefined),
5423        }
5424    }
5425
5426    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5427    ///
5428    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5429    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5430    /// assignment follows.
5431    fn super_write(
5432        &mut self,
5433        receiver: &Value,
5434        proto: &Value,
5435        key: &Value,
5436        value: Value,
5437    ) -> JsResult<()> {
5438        let target = self.require_object(receiver)?;
5439        let key = self.propkey(key)?;
5440        if !matches!(proto, Value::Null)
5441            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5442        {
5443            if property.is_accessor() {
5444                if let Some(setter) = &property.setter
5445                    && !matches!(setter, Value::Undefined)
5446                {
5447                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5448                }
5449                return Ok(());
5450            }
5451            // A data property on the prototype is writable or not; reading `owner` at
5452            // all is only for the attribute check.
5453            if !property.writable {
5454                return Err(self.type_error(format!("'{key}' is read-only")));
5455            }
5456            let _ = owner;
5457        }
5458        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5459    }
5460
5461    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5462    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5463        match value.as_object() {
5464            Some(object) => Ok(object.clone()),
5465            None => Err(Signal::Throw(
5466                self.make_error("TypeError", "value is not an object"),
5467            )),
5468        }
5469    }
5470
5471    /// Build the class object `define_class` produces.
5472    ///
5473    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5474    /// whose prototype property is a fresh object inheriting from the parent's
5475    /// prototype, and whose own prototype is the parent constructor — which is what makes
5476    /// a static method inherited too.
5477    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5478        let ctor = self.pop();
5479        let parent = self.pop();
5480        let Value::Object(function) = &ctor else {
5481            return Err(Signal::Throw(
5482                self.make_error("TypeError", "class constructor must be a function"),
5483            ));
5484        };
5485        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5486        // but gives the instances no prototype at all.
5487        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5488            match &parent {
5489                Value::Null => (Some(self.realm.function_proto.clone()), None),
5490                Value::Object(parent_class) => {
5491                    if !parent_class.is_callable() {
5492                        return Err(Signal::Throw(
5493                            self.make_error("TypeError", "parent class must be constructor"),
5494                        ));
5495                    }
5496                    let proto = self.get_property(parent_class, "prototype")?;
5497                    match proto {
5498                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5499                        Some(Value::Null) => (Some(parent_class.clone()), None),
5500                        _ => {
5501                            return Err(Signal::Throw(self.make_error(
5502                                "TypeError",
5503                                "parent prototype must be an object or null",
5504                            )));
5505                        }
5506                    }
5507                }
5508                _ => {
5509                    return Err(Signal::Throw(
5510                        self.make_error("TypeError", "parent class must be constructor"),
5511                    ));
5512                }
5513            }
5514        } else {
5515            (
5516                Some(self.realm.function_proto.clone()),
5517                Some(self.realm.object_proto.clone()),
5518            )
5519        };
5520        let proto = self.new_object(parent_proto);
5521        function.set_proto(parent_ctor);
5522        // A class is not callable without `new`, and its `prototype` is not writable —
5523        // both follow from being a class and are what `class A {}; A()` throws on.
5524        function.set_class_constructor(true);
5525        function.set_home_object(None);
5526        self.set_function_name(&ctor, name);
5527        self.define_class_properties(function, &ctor, &proto)?;
5528        Ok((ctor, proto))
5529    }
5530
5531    /// Give the constructor its `prototype` and `length`, and the prototype its
5532    /// `constructor` back-pointer.
5533    fn define_class_properties(
5534        &mut self,
5535        function: &Gc<JsObject>,
5536        ctor: &Value,
5537        proto: &Gc<JsObject>,
5538    ) -> JsResult<()> {
5539        proto.define(
5540            "constructor",
5541            Property::with_attributes(ctor.clone(), true, false),
5542        );
5543        function.define(
5544            "prototype",
5545            Property::prototype_of(Value::Object(proto.clone()), false),
5546        );
5547        if let Some((code, _)) = bytecode_of(function) {
5548            let length = code.code.defined_args;
5549            function.define(
5550                "length",
5551                Property::name_or_length(Value::Int(length as i32)),
5552            );
5553        }
5554        Ok(())
5555    }
5556
5557    /// The own array element `key` names, if this object has one.
5558    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5559        // A typed array's elements live in its buffer, not in a property list: reading one
5560        // goes through the view's element type so a bounds check and a detached buffer are
5561        // both handled there.
5562        //
5563        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5564        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5565        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5566        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5567        // consulted. Testing with `array_index` rejected all three, which let a throwing
5568        // getter installed on `TypedArray.prototype["-1"]` run.
5569        if object.typed_array_parts().is_some() {
5570            let property_key = PropertyKey::from(key);
5571            let numeric = canonical_numeric_index(&property_key)?;
5572            if typed_array_index_is_valid(object, numeric) {
5573                return object.typed_array_element(numeric as usize);
5574            }
5575            // Canonical, but not a valid index: `undefined`, and *final*.
5576            return Some(Value::Undefined);
5577        }
5578        let index = array_index(key)?;
5579        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5580        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5581        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5582        // `[1,,3][1]`.
5583        match object.array_get(index as usize) {
5584            Some(Value::Hole) | None => None,
5585            other => other,
5586        }
5587    }
5588
5589    /// Store `object[key] = value`, honouring setters and inherited properties.
5590    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5591        self.set_property_with(object, key, value, DeleteFailure::Throw)
5592    }
5593
5594    /// Store a property, choosing what to do when the object refuses.
5595    ///
5596    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5597    /// mode, which is the one place assignment differs by mode. Native code (the array
5598    /// methods, `JSON`) always asks for the throw.
5599    pub fn set_property_with(
5600        &mut self,
5601        object: &Gc<JsObject>,
5602        key: &str,
5603        value: Value,
5604        on_failure: DeleteFailure,
5605    ) -> JsResult<()> {
5606        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5607    }
5608
5609    /// [`Interp::set_property_with`] with a key that may be a symbol.
5610    pub fn set_property_with_key(
5611        &mut self,
5612        object: &Gc<JsObject>,
5613        key: &PropertyKey,
5614        value: Value,
5615        on_failure: DeleteFailure,
5616    ) -> JsResult<()> {
5617        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5618    }
5619
5620    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5621    ///
5622    /// The receiver split lives one level up, in
5623    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5624    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5625    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5626    /// stores into `object` itself, which is why the element branch below converts `V`
5627    /// before asking whether the index is valid: `V` may put it back in bounds
5628    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5629    fn set_property_with_key_receiver_aware(
5630        &mut self,
5631        object: &Gc<JsObject>,
5632        key: &PropertyKey,
5633        value: Value,
5634        on_failure: DeleteFailure,
5635    ) -> JsResult<()> {
5636        // A proxy's `set` trap decides, and its `false` means the same thing an
5637        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5638        if object.proxy_state().is_some() {
5639            let receiver = Value::Object(object.clone());
5640            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5641                return match (accepted, on_failure) {
5642                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5643                    (false, DeleteFailure::Throw) => {
5644                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5645                    }
5646                };
5647            }
5648        }
5649        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5650        // refusal and means exactly what a proxy's `false` means.
5651        if let Some(exotic) = object.exotic() {
5652            let receiver = Value::Object(object.clone());
5653            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5654                return match (accepted, on_failure) {
5655                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5656                    (false, DeleteFailure::Throw) => {
5657                        Err(self.type_error(format!("property '{key}' is read-only")))
5658                    }
5659                };
5660            }
5661        }
5662        // The element and `length` shortcuts only exist for string keys: an array
5663        // index has no symbol spelling, and a symbol named `length` is an ordinary
5664        // property.
5665        let text = key.as_str();
5666        // A typed array's elements are a window onto its buffer: the store has to go
5667        // through the view's element type so the value is wrapped (or clamped) and so an
5668        // out-of-range or detached write is a silent no-op, as the spec says.
5669        //
5670        // The key test is `CanonicalNumericIndexString`, like every other index operation
5671        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5672        // does not exist, so they do nothing and leave no own property behind
5673        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5674        // path, which created a property named `"-0"`.
5675        //
5676        // The conversion comes **first**, before the index is checked at all, and that
5677        // order is observable twice over:
5678        //
5679        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5680        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5681        //   then store the converted value;
5682        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5683        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5684        //   run and its exception to escape.
5685        //
5686        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5687        // validity check, not a validity check that skips the conversion. The store itself
5688        // is a no-op when the index is invalid by then, which is why no extra guard is
5689        // needed around `typed_array_set`.
5690        if let Some(element) = object.typed_array_element_type()
5691            && let Some(numeric) = canonical_numeric_index(key)
5692        {
5693            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5694            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5695            // in `Interp`, because it is script-observable and the storage borrow inside
5696            // `typed_array_set` must not be held across it.
5697            let stored = self.element_value(element, value)?;
5698            if typed_array_index_is_valid(object, numeric)
5699                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5700            {
5701                return Err(self.type_error(reason));
5702            }
5703            return Ok(());
5704        }
5705        if let Some(text) = text
5706            && let Some(index) = array_index(text)
5707            && object.is_array()
5708        {
5709            // An accessor defined on an index lives in the property table while the
5710            // element slot is a hole, so the store has to go through the property first.
5711            // Writing the vector directly skipped the setter entirely.
5712            if let Some(existing) = object.own_property_key(key) {
5713                if existing.is_accessor() {
5714                    return match existing.setter.clone() {
5715                        Some(setter) if !matches!(setter, Value::Undefined) => {
5716                            let receiver = Value::Object(object.clone());
5717                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5718                        }
5719                        _ => match on_failure {
5720                            DeleteFailure::Throw => Err(self.type_error(format!(
5721                                "cannot set property '{text}', it has only a getter"
5722                            ))),
5723                            DeleteFailure::Ignore => Ok(()),
5724                        },
5725                    };
5726                }
5727                if !existing.writable {
5728                    return match on_failure {
5729                        DeleteFailure::Throw => {
5730                            Err(self.type_error(format!("'{text}' is read-only")))
5731                        }
5732                        DeleteFailure::Ignore => Ok(()),
5733                    };
5734                }
5735            }
5736            {
5737                // Growing the array needs a writable `length`.
5738                if (index as usize) >= object.array_length().unwrap_or(0)
5739                    && !object.length_writable()
5740                {
5741                    return match on_failure {
5742                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5743                        DeleteFailure::Ignore => Ok(()),
5744                    };
5745                }
5746                // Adding an index past the end makes the array longer, which a
5747                // non-extensible array refuses.
5748                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5749                    return match on_failure {
5750                        DeleteFailure::Throw => Err(self.type_error(format!(
5751                            "cannot add property '{key}', object is not extensible"
5752                        ))),
5753                        DeleteFailure::Ignore => Ok(()),
5754                    };
5755                }
5756                if object.element_is_locked(index) {
5757                    return match on_failure {
5758                        DeleteFailure::Throw => {
5759                            Err(self.type_error(format!("'{key}' is read-only")))
5760                        }
5761                        DeleteFailure::Ignore => Ok(()),
5762                    };
5763                }
5764                // The element vector is only half of `[[Set]]` for an index: the
5765                // prototype chain is consulted first, and a setter there answers instead
5766                // of the element store. This branch used to write the element directly, so
5767                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5768                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5769                // the reference calls the setter and the array keeps no own index.
5770                //
5771                // An *exotic* prototype has no entry to find, because its indices live
5772                // outside the property table — `Object.setPrototypeOf([], typedArray)`
5773                // then looked like "nothing on the chain" and the store created the
5774                // element, where the view's `[[Set]]` answers `true` and does nothing for
5775                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
5776                // checks the array's `length` stays 0). So the dispatch comes first.
5777                if !object.has_own_key(key)
5778                    && let Some(proto) = object.proto()
5779                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
5780                {
5781                    let receiver = Value::Object(object.clone());
5782                    let accepted =
5783                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5784                    return if accepted {
5785                        Ok(())
5786                    } else {
5787                        match on_failure {
5788                            DeleteFailure::Throw => {
5789                                Err(self.type_error(format!("'{key}' is read-only")))
5790                            }
5791                            DeleteFailure::Ignore => Ok(()),
5792                        }
5793                    };
5794                }
5795                if let Some((owner, property)) = lookup_key(object, key)
5796                    && !owner.ptr_eq(object)
5797                {
5798                    match &property {
5799                        property if property.is_accessor() => {
5800                            match &property.setter {
5801                                Some(setter) if !matches!(setter, Value::Undefined) => {
5802                                    let receiver = Value::Object(object.clone());
5803                                    self.call_value(setter.clone(), receiver, vec![value])?;
5804                                }
5805                                _ => {
5806                                    return match on_failure {
5807                                        DeleteFailure::Throw => Err(self.type_error(format!(
5808                                            "cannot set property '{text}', it has only a getter"
5809                                        ))),
5810                                        DeleteFailure::Ignore => Ok(()),
5811                                    };
5812                                }
5813                            }
5814                            return Ok(());
5815                        }
5816                        property if !property.writable => {
5817                            return match on_failure {
5818                                DeleteFailure::Throw => {
5819                                    Err(self.type_error(format!("'{text}' is read-only")))
5820                                }
5821                                DeleteFailure::Ignore => Ok(()),
5822                            };
5823                        }
5824                        _ => {}
5825                    }
5826                }
5827                if object.array_set(self.heap, index as usize, value.clone()) {
5828                    return Ok(());
5829                }
5830                // Past the dense limit the slot is too far out to be worth one `Value`
5831                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5832                // constant time by keeping the index as an ordinary property. The store
5833                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5834                // to a legal program.
5835                object.define_key(key, Property::with_attributes(value, true, true));
5836                // Extend, never shorten: the index may be *inside* the current length (a
5837                // huge `length` with a sparse store), and shortening would delete the
5838                // sparse properties above it — including the one just stored.
5839                if index as usize + 1 > object.array_length().unwrap_or(0) {
5840                    object.array_set_length(self.heap, index as usize + 1);
5841                }
5842                return Ok(());
5843            }
5844        }
5845        if text == Some("length") && object.is_array() {
5846            if !object.length_writable() {
5847                return match on_failure {
5848                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5849                    DeleteFailure::Ignore => Ok(()),
5850                };
5851            }
5852            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
5853            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
5854            // answered `NaN`, which left the assignment silently ignored
5855            // (`S15.4.5.2_A3_T2`).
5856            let length = self.to_js_number(&value)?;
5857            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
5858            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
5859            // `RangeError`s; the old code only tested "finite and non-negative" and then
5860            // truncated, so `[].length = 4294967297` quietly produced a length no array can
5861            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
5862            let valid = length.is_finite()
5863                && length >= 0.0
5864                && length.fract() == 0.0
5865                && length <= u32::MAX as f64;
5866            if !valid {
5867                return Err(self.range_error("invalid array length"));
5868            }
5869            {
5870                let length = length as usize;
5871                // `a.length = n` with `n` below a non-configurable element cannot
5872                // drop that element, so the whole assignment fails. The spec makes
5873                // this a `TypeError` rather than a silent no-op, in any mode.
5874                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5875                    // Sloppy mode stops the truncation at the blocking element
5876                    // instead of failing; strict mode raises.
5877                    // Both modes stop at the blocking element; they differ in
5878                    // whether that is reported. The reference truncates *then*
5879                    // throws, so the array is left in the shortened state.
5880                    object.array_truncate(self.heap, blocked + 1);
5881                    return match on_failure {
5882                        DeleteFailure::Throw => {
5883                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5884                        }
5885                        DeleteFailure::Ignore => Ok(()),
5886                    };
5887                }
5888                object.array_set_length(self.heap, length);
5889                return Ok(());
5890            }
5891        }
5892        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
5893        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
5894        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
5895        //
5896        // The prototype step is a dispatch, not a lookup. Walking the chain here and
5897        // applying whatever came back is the same thing for an ordinary prototype and
5898        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
5899        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
5900        // answers "not mine, the receiver is not me" without touching the buffer. This
5901        // code used to find nothing owned by `o`, find no property on the view either,
5902        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
5903        // object and never converted (`key-is-valid-index-prototype-chain-set`,
5904        // `key-is-canonical-invalid-index-prototype-chain-set`).
5905        //
5906        // The read-only and accessor rules of step 1 are what make
5907        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
5908        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
5909        let own = match self.lookup_for_write(object, key)? {
5910            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
5911            _ => None,
5912        };
5913        if let Some(property) = own {
5914            if property.is_accessor() {
5915                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
5916                    Some(setter) => {
5917                        let receiver = Value::Object(object.clone());
5918                        self.call_value(setter, receiver, vec![value])?;
5919                        Ok(())
5920                    }
5921                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5922                    // Sloppy code swallows that refusal, strict code raises — the same
5923                    // rule the read-only *data* property below follows, and skipping it
5924                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5925                    // return silently. The reference answers `TypeError: 'x' is
5926                    // read-only`.
5927                    None => match on_failure {
5928                        DeleteFailure::Throw => {
5929                            Err(self.type_error(format!("'{key}' is read-only")))
5930                        }
5931                        DeleteFailure::Ignore => Ok(()),
5932                    },
5933                };
5934            }
5935            // An own non-writable data property stops here: nothing may change it.
5936            if !property.writable {
5937                return match on_failure {
5938                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5939                    DeleteFailure::Ignore => Ok(()),
5940                };
5941            }
5942            // An existing writable own property keeps its attributes: only the value
5943            // moves. Redefining instead would reset them, which is how a
5944            // non-configurable global `var` used to become deletable.
5945            if object.write_value_key(key, value.clone()) {
5946                return Ok(());
5947            }
5948        }
5949        // Step 2: hand the store to the prototype, with `object` as the receiver.
5950        if let Some(proto) = object.proto() {
5951            let receiver = Value::Object(object.clone());
5952            let accepted =
5953                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5954            return if accepted {
5955                Ok(())
5956            } else {
5957                match on_failure {
5958                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5959                    DeleteFailure::Ignore => Ok(()),
5960                }
5961            };
5962        }
5963        // Step 3: create one, and a non-extensible object cannot.
5964        if !object.is_extensible() {
5965            return match on_failure {
5966                DeleteFailure::Throw => Err(self.type_error(format!(
5967                    "cannot add property {key}, object is not extensible"
5968                ))),
5969                DeleteFailure::Ignore => Ok(()),
5970            };
5971        }
5972        object.define_data_key(key, value);
5973        Ok(())
5974    }
5975
5976    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
5977    ///
5978    /// The distinction the fast path above does not need: it is called with the store's
5979    /// receiver already being the object it writes to. Here `object` is the one whose
5980    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
5981    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
5982    /// and not a write to `object`.
5983    ///
5984    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
5985    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
5986    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
5987    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
5988    /// descriptor on the prototype refuses instead, which is the same rule that keeps
5989    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
5990    ///
5991    /// Answers `false` where the spec says `false`; the caller turns that into the
5992    /// strict-mode `TypeError` or the sloppy-mode silence.
5993    fn ordinary_set_with_receiver(
5994        &mut self,
5995        object: &Gc<JsObject>,
5996        receiver: &Value,
5997        key: &PropertyKey,
5998        value: Value,
5999        on_failure: DeleteFailure,
6000    ) -> JsResult<bool> {
6001        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6002        if object.proxy_state().is_some() {
6003            return Ok(self
6004                .proxy_set(object, key, value, receiver)?
6005                .unwrap_or(true));
6006        }
6007        // A host class decides for itself, with the receiver the caller named.
6008        if let Some(exotic) = object.exotic()
6009            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6010        {
6011            return Ok(accepted);
6012        }
6013        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6014        // rather than the receiver, but the receiver may still *be* the view:
6015        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6016        // itself as receiver, and then the first half applies — convert `V` once, store
6017        // if the index is valid, answer `true` either way. The conversion is the observable
6018        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6019        //
6020        // Only the second half, a view that is *not* the receiver, skips the conversion
6021        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6022        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6023        // below with the value still unconverted.
6024        if object.typed_array_element_type().is_some()
6025            && let Some(numeric) = canonical_numeric_index(key)
6026        {
6027            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6028                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6029                return Ok(true);
6030            }
6031            if !typed_array_index_is_valid(object, numeric) {
6032                return Ok(true);
6033            }
6034        }
6035        let own = self.object_get_own_property(object, key)?;
6036        if let Some(own) = own {
6037            if own.is_accessor() {
6038                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6039                    Some(setter) => {
6040                        self.call_value(setter, receiver.clone(), vec![value])?;
6041                        Ok(true)
6042                    }
6043                    None => Ok(false),
6044                };
6045            }
6046            // A non-writable data descriptor refuses, own or inherited. Either way the
6047            // receiver must not gain a shadowing property.
6048            if !own.writable {
6049                return Ok(false);
6050            }
6051            // Step 1.d: the *receiver's* own descriptor decides whether it can be
6052            // created or written, and it is created as an ordinary data property.
6053            let Some(receiver_object) = receiver.as_object().cloned() else {
6054                return Ok(false);
6055            };
6056            return match self.object_get_own_property(&receiver_object, key)? {
6057                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6058                Some(existing) => self.object_define_own_property(
6059                    &receiver_object,
6060                    key,
6061                    Property {
6062                        value: Some(value),
6063                        ..existing
6064                    },
6065                ),
6066                None => {
6067                    self.object_define_own_property(&receiver_object, key, Property::data(value))
6068                }
6069            };
6070        }
6071        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6072        if let Some(proto) = object.proto() {
6073            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6074        }
6075        // Step 3: nowhere to inherit from, so create on the receiver — if it will take it.
6076        let Some(receiver_object) = receiver.as_object().cloned() else {
6077            return Ok(false);
6078        };
6079        if !self.object_is_extensible(&receiver_object)? {
6080            return Ok(false);
6081        }
6082        self.object_define_own_property(&receiver_object, key, Property::data(value))
6083    }
6084
6085    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6086    ///
6087    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6088    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6089    /// a virtual accessor gets its setter run without implementing `set_property` at all.
6090    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6091    /// the prototype, so the walk resumes above the object.
6092    fn lookup_for_write(
6093        &mut self,
6094        object: &Gc<JsObject>,
6095        key: &PropertyKey,
6096    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6097        let Some(exotic) = object.exotic() else {
6098            return Ok(lookup_key(object, key));
6099        };
6100        Ok(match exotic.get_own_property(self, object, key)? {
6101            Some(Some(property)) => Some((object.clone(), property)),
6102            Some(None) => lookup_key_above(object, key),
6103            None => lookup_key(object, key),
6104        })
6105    }
6106
6107    /// Delete `object[key]`.
6108    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6109        self.delete_property_key(object, &PropertyKey::from(key))
6110    }
6111
6112    /// [`Interp::delete_property`] with a key that may be a symbol.
6113    pub fn delete_property_key(
6114        &mut self,
6115        object: &Gc<JsObject>,
6116        key: &PropertyKey,
6117    ) -> JsResult<bool> {
6118        // A proxy decides for itself, and may even throw; the invariant checks live in
6119        // `proxy_delete`.
6120        if let Some(answer) = self.proxy_delete(object, key)? {
6121            return Ok(answer);
6122        }
6123        // A host class's `delete_property` trap decides; `false` is a refusal, which the
6124        // caller reports as a failed delete.
6125        if let Some(exotic) = object.exotic()
6126            && let Some(answer) = exotic.delete_property(self, object, key)?
6127        {
6128            return Ok(answer);
6129        }
6130        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6131        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6132        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6133        // one answers `false` because the elements are non-configurable. The prototype
6134        // chain is not consulted either, which is what makes a throwing getter on
6135        // `TypedArray.prototype["-1"]` stay unrun.
6136        if object.typed_array_parts().is_some()
6137            && object.proxy_state().is_none()
6138            && let Some(numeric) = canonical_numeric_index(key)
6139        {
6140            return Ok(!typed_array_index_is_valid(object, numeric));
6141        }
6142        let mapped_index = key.as_str().and_then(array_index);
6143        if let Some(index) = mapped_index
6144            && let Some(length) = object.array_length()
6145            && (index as usize) < length
6146        {
6147            // An accessor defined on an index lives in the property table rather than the
6148            // element vector, so both have to be cleared: `delete` after
6149            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6150            object.delete_key(key);
6151            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6152            // index stops answering `in`.
6153            if object.element_is_undeletable(index) {
6154                return Ok(false);
6155            }
6156            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6157            // so a later `defineProperty(arguments, "0", {value})` writes to the object
6158            // and no longer through to the parameter. A refused delete leaves the
6159            // mapping alone.
6160            object.drop_mapped_argument(index as usize);
6161            object.array_set(self.heap, index as usize, Value::Hole);
6162            return Ok(true);
6163        }
6164        // The same for an object that is not an array: only a delete that actually
6165        // removed the property ends the alias.
6166        let deleted = object.delete_key(key);
6167        if deleted && let Some(index) = mapped_index {
6168            object.drop_mapped_argument(index as usize);
6169        }
6170        Ok(deleted)
6171    }
6172
6173    // -- proxy traps --------------------------------------------------------
6174    //
6175    // A proxy's internal methods all look the same: ask the handler for the trap, call it
6176    // with the target and the operation's own arguments, then check the answer against
6177    // the target. The checks are not decoration — they are what stops a proxy from
6178    // reporting a `non-configurable` property as missing, which would let a frozen object
6179    // be rewritten by standing in front of it.
6180
6181    /// The target and handler of `object`, or `None` when it is not a proxy.
6182    ///
6183    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6184    /// one has to fail: the slots the traps would have been read from are gone.
6185    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6186        let Some(state) = object.proxy_state() else {
6187            return Ok(None);
6188        };
6189        let state = state.borrow();
6190        match (&state.target, &state.handler) {
6191            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6192            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6193        }
6194    }
6195
6196    /// Call `handler[name]`, or answer `None` when the trap is absent.
6197    ///
6198    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
6199    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
6200    /// back to the target.
6201    fn proxy_trap(
6202        &mut self,
6203        handler: &Value,
6204        name: &str,
6205        args: Vec<Value>,
6206    ) -> JsResult<Option<Value>> {
6207        let Value::Object(table) = handler else {
6208            return Err(self.type_error("proxy handler is not an object"));
6209        };
6210        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6211        match trap {
6212            Value::Undefined => Ok(None),
6213            Value::Object(function) if function.is_callable() => {
6214                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6215                Ok(Some(answer))
6216            }
6217            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6218        }
6219    }
6220
6221    /// Whether `object`'s own property `key` is one the target refuses to lose.
6222    ///
6223    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6224    /// its value behind the target's back. This goes through
6225    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
6226    /// elements and its `length` — both fixed, both outside the table — are covered.
6227    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
6228        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
6229    }
6230
6231    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6232    fn proxy_get(
6233        &mut self,
6234        object: &Gc<JsObject>,
6235        receiver: &Value,
6236        key: &PropertyKey,
6237    ) -> JsResult<Option<Value>> {
6238        let Some((target, handler)) = self.proxy_parts(object)? else {
6239            return Ok(None);
6240        };
6241        let key_value = self.key_value(key);
6242        let Some(result) = self.proxy_trap(
6243            &handler,
6244            "get",
6245            vec![Value::Object(target.clone()), key_value, receiver.clone()],
6246        )?
6247        else {
6248            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6249            // inherited getter still sees the proxy.
6250            return Ok(Some(
6251                self.get_property_key_for(&target, Some(receiver), key)?
6252                    .unwrap_or(Value::Undefined),
6253            ));
6254        };
6255        if let Some(fixed) = Self::is_fixed_property(&target, key) {
6256            if fixed.is_accessor() {
6257                // A fixed accessor with no getter must read as `undefined`.
6258                let has_getter = fixed
6259                    .getter
6260                    .as_ref()
6261                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
6262                if !has_getter && !matches!(result, Value::Undefined) {
6263                    return Err(self.type_error(format!(
6264                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
6265                    )));
6266                }
6267            } else if !fixed.writable {
6268                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6269                if !fixed_value.same_value(&result) {
6270                    return Err(self.type_error(format!(
6271                        "proxy 'get' disagrees with the non-configurable property '{key}'"
6272                    )));
6273                }
6274            }
6275        }
6276        Ok(Some(result))
6277    }
6278
6279    /// `[[Set]]` on a proxy.
6280    ///
6281    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6282    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6283    /// read-only store has.
6284    fn proxy_set(
6285        &mut self,
6286        object: &Gc<JsObject>,
6287        key: &PropertyKey,
6288        value: Value,
6289        receiver: &Value,
6290    ) -> JsResult<Option<bool>> {
6291        let Some((target, handler)) = self.proxy_parts(object)? else {
6292            return Ok(None);
6293        };
6294        let key_value = self.key_value(key);
6295        let Some(result) = self.proxy_trap(
6296            &handler,
6297            "set",
6298            vec![
6299                Value::Object(target.clone()),
6300                key_value,
6301                value.clone(),
6302                receiver.clone(),
6303            ],
6304        )?
6305        else {
6306            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6307            // given — not the target. `OrdinarySet` step 3 is
6308            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6309            // object whose prototype is a typed array has to reach the proxy's own
6310            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6311            // calls and expects exactly one. Storing on the target instead put the value
6312            // in the target and never consulted the trap.
6313            let accepted = self.ordinary_set_with_receiver(
6314                &target,
6315                receiver,
6316                key,
6317                value,
6318                DeleteFailure::Ignore,
6319            )?;
6320            return Ok(Some(accepted));
6321        };
6322        if !result.to_boolean() {
6323            return Ok(Some(false));
6324        }
6325        if let Some(fixed) = Self::is_fixed_property(&target, key) {
6326            if fixed.is_accessor() {
6327                let has_setter = fixed
6328                    .setter
6329                    .as_ref()
6330                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
6331                if !has_setter {
6332                    return Err(self.type_error(format!(
6333                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6334                    )));
6335                }
6336            } else if !fixed.writable {
6337                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6338                if !fixed_value.same_value(&value) {
6339                    return Err(self.type_error(format!(
6340                        "proxy 'set' changed the non-configurable property '{key}'"
6341                    )));
6342                }
6343            }
6344        }
6345        // A new property cannot appear on a target that refuses new properties.
6346        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
6347            return Err(self.type_error(format!(
6348                "proxy 'set' added '{key}' to a non-extensible target"
6349            )));
6350        }
6351        Ok(Some(true))
6352    }
6353
6354    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6355    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6356        let Some((target, handler)) = self.proxy_parts(object)? else {
6357            return Ok(None);
6358        };
6359        let key_value = self.key_value(key);
6360        let Some(result) = self.proxy_trap(
6361            &handler,
6362            "has",
6363            vec![Value::Object(target.clone()), key_value],
6364        )?
6365        else {
6366            return Ok(Some(self.has_own_or_inherited(&target, key)?));
6367        };
6368        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
6369            return Err(self.type_error(format!(
6370                "proxy 'has' denied the non-configurable property '{key}'"
6371            )));
6372        }
6373        // A non-extensible target cannot grow, so every own property it *has* is fixed.
6374        if !result.to_boolean()
6375            && !target.is_extensible()
6376            && Self::ordinary_own_property(&target, key).is_some()
6377        {
6378            return Err(self.type_error(format!(
6379                "proxy 'has' denied the own property '{key}' of a non-extensible target"
6380            )));
6381        }
6382        Ok(Some(result.to_boolean()))
6383    }
6384
6385    /// `[[Delete]]` on a proxy.
6386    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6387        let Some((target, handler)) = self.proxy_parts(object)? else {
6388            return Ok(None);
6389        };
6390        let key_value = self.key_value(key);
6391        let Some(result) = self.proxy_trap(
6392            &handler,
6393            "deleteProperty",
6394            vec![Value::Object(target.clone()), key_value],
6395        )?
6396        else {
6397            return Ok(Some(self.delete_property_key(&target, key)?));
6398        };
6399        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
6400            return Err(self.type_error(format!(
6401                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6402            )));
6403        }
6404        if result.to_boolean()
6405            && !target.is_extensible()
6406            && Self::ordinary_own_property(&target, key).is_some()
6407        {
6408            return Err(self.type_error(format!(
6409                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6410            )));
6411        }
6412        Ok(Some(result.to_boolean()))
6413    }
6414
6415    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6416    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6417        let Some((target, handler)) = self.proxy_parts(object)? else {
6418            return Ok(None);
6419        };
6420        let Some(result) =
6421            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6422        else {
6423            // No trap: the target's own keys, already in the order an object reports.
6424            return Ok(Some(self.object_own_property_keys(&target)?));
6425        };
6426        // `CreateListFromArrayLike` with the string-or-symbol restriction.
6427        let list = self.list_from_array_like(&result, true)?;
6428        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6429        for value in list {
6430            let key = self.propkey(&value)?;
6431            if keys.contains(&key) {
6432                return Err(self.type_error(format!(
6433                    "proxy 'ownKeys' returned the duplicate key '{key}'"
6434                )));
6435            }
6436            keys.push(key);
6437        }
6438        for (key, property) in target.property_entries() {
6439            if !property.configurable && !keys.contains(&key) {
6440                return Err(self.type_error(format!(
6441                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6442                )));
6443            }
6444            if !target.is_extensible() && !keys.contains(&key) {
6445                return Err(self.type_error(format!(
6446                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6447                )));
6448            }
6449        }
6450        if !target.is_extensible() {
6451            let own = target.property_entries().len();
6452            if keys.len() != own {
6453                return Err(
6454                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6455                );
6456            }
6457        }
6458        Ok(Some(keys))
6459    }
6460
6461    /// `[[GetOwnProperty]]` on a proxy.
6462    fn proxy_get_own_property(
6463        &mut self,
6464        object: &Gc<JsObject>,
6465        key: &PropertyKey,
6466    ) -> JsResult<Option<Option<Property>>> {
6467        let Some((target, handler)) = self.proxy_parts(object)? else {
6468            return Ok(None);
6469        };
6470        let key_value = self.key_value(key);
6471        let Some(result) = self.proxy_trap(
6472            &handler,
6473            "getOwnPropertyDescriptor",
6474            vec![Value::Object(target.clone()), key_value],
6475        )?
6476        else {
6477            // No trap: the target's own descriptor is the answer. This has to go through
6478            // the same synthesis an ordinary object gets, because a proxy's own property
6479            // table is empty by design — reading it directly reported `undefined` for
6480            // every key, including an array's indices and `length`.
6481            return Ok(Some(Self::ordinary_own_property(&target, key)));
6482        };
6483        let answer = if matches!(result, Value::Undefined) {
6484            None
6485        } else {
6486            Some(self.property_from_descriptor(&result)?)
6487        };
6488        let fixed = Self::is_fixed_property(&target, key);
6489        match (&answer, &fixed) {
6490            // A non-configurable property cannot be reported as absent.
6491            (None, Some(_)) => {
6492                return Err(self.type_error(format!(
6493                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6494                )));
6495            }
6496            (Some(descriptor), Some(fixed)) => {
6497                if descriptor.configurable {
6498                    return Err(self.type_error(format!(
6499                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6500                    )));
6501                }
6502                if fixed.is_accessor() != descriptor.is_accessor() {
6503                    return Err(self.type_error(format!(
6504                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6505                    )));
6506                }
6507                if !fixed.is_accessor() && !fixed.writable {
6508                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
6509                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6510                    if !fixed_value.same_value(&reported) {
6511                        return Err(self.type_error(format!(
6512                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6513                        )));
6514                    }
6515                }
6516            }
6517            _ => {}
6518        }
6519        Ok(Some(answer))
6520    }
6521
6522    /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
6523    ///
6524    /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
6525    /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
6526    /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
6527    /// for a data property. `Property` cannot express "this field is absent", so the whole
6528    /// property path is skipped and the descriptor is assembled here field by field.
6529    ///
6530    /// `current` is the property the trap reported, used only to tell a data property from
6531    /// an accessor.
6532    pub fn proxy_seal_property(
6533        &mut self,
6534        object: &Gc<JsObject>,
6535        key: &PropertyKey,
6536        frozen: bool,
6537        current: &Property,
6538    ) -> JsResult<bool> {
6539        let Some((_target, handler)) = self.proxy_parts(object)? else {
6540            return Err(self.type_error("not a proxy"));
6541        };
6542        let descriptor = self.new_object(None);
6543        descriptor.define_data("configurable", Value::Bool(false));
6544        if frozen && !current.is_accessor() {
6545            descriptor.define_data("writable", Value::Bool(false));
6546        }
6547        let key_value = self.key_value(key);
6548        let target = object
6549            .proxy_state()
6550            .and_then(|state| state.borrow().target.clone());
6551        let Some(target) = target else {
6552            return Err(self.type_error("cannot use a proxy that has been revoked"));
6553        };
6554        let Some(result) = self.proxy_trap(
6555            &handler,
6556            "defineProperty",
6557            vec![Value::Object(target), key_value, Value::Object(descriptor)],
6558        )?
6559        else {
6560            // No trap means the definition belongs to the target; `false` is its answer.
6561            return Ok(false);
6562        };
6563        Ok(result.to_boolean())
6564    }
6565
6566    /// `[[DefineOwnProperty]]` on a proxy.
6567    fn proxy_define_property(
6568        &mut self,
6569        object: &Gc<JsObject>,
6570        key: &PropertyKey,
6571        property: Property,
6572    ) -> JsResult<Option<bool>> {
6573        let Some((target, handler)) = self.proxy_parts(object)? else {
6574            return Ok(None);
6575        };
6576        let key_value = self.key_value(key);
6577        let descriptor = self.descriptor_from_property(&property);
6578        let Some(result) = self.proxy_trap(
6579            &handler,
6580            "defineProperty",
6581            vec![Value::Object(target.clone()), key_value, descriptor],
6582        )?
6583        else {
6584            return Ok(None);
6585        };
6586        if !result.to_boolean() {
6587            return Ok(Some(false));
6588        }
6589        let fixed = Self::is_fixed_property(&target, key);
6590        let creating = Self::ordinary_own_property(&target, key).is_none();
6591        if creating && !target.is_extensible() {
6592            return Err(self.type_error(format!(
6593                "proxy 'defineProperty' added '{key}' to a non-extensible target"
6594            )));
6595        }
6596        if let Some(fixed) = fixed {
6597            if property.configurable {
6598                return Err(self.type_error(format!(
6599                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
6600                )));
6601            }
6602            if !fixed.writable && property.writable && !fixed.is_accessor() {
6603                return Err(self.type_error(format!(
6604                    "proxy 'defineProperty' made the read-only '{key}' writable"
6605                )));
6606            }
6607        }
6608        Ok(Some(true))
6609    }
6610
6611    /// `[[GetPrototypeOf]]` on a proxy.
6612    fn proxy_get_prototype_of(
6613        &mut self,
6614        object: &Gc<JsObject>,
6615    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6616        let Some((target, handler)) = self.proxy_parts(object)? else {
6617            return Ok(None);
6618        };
6619        let Some(result) = self.proxy_trap(
6620            &handler,
6621            "getPrototypeOf",
6622            vec![Value::Object(target.clone())],
6623        )?
6624        else {
6625            return Ok(Some(target.proto()));
6626        };
6627        let proto = match &result {
6628            Value::Null => None,
6629            Value::Object(proto) => Some(proto.clone()),
6630            _ => {
6631                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
6632            }
6633        };
6634        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
6635            return Err(self.type_error(
6636                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
6637            ));
6638        }
6639        Ok(Some(proto))
6640    }
6641
6642    /// `[[SetPrototypeOf]]` on a proxy.
6643    fn proxy_set_prototype_of(
6644        &mut self,
6645        object: &Gc<JsObject>,
6646        proto: Option<Gc<JsObject>>,
6647    ) -> JsResult<Option<bool>> {
6648        let Some((target, handler)) = self.proxy_parts(object)? else {
6649            return Ok(None);
6650        };
6651        let proto_value = match &proto {
6652            Some(proto) => Value::Object(proto.clone()),
6653            None => Value::Null,
6654        };
6655        let Some(result) = self.proxy_trap(
6656            &handler,
6657            "setPrototypeOf",
6658            vec![Value::Object(target.clone()), proto_value],
6659        )?
6660        else {
6661            target.set_proto(proto);
6662            return Ok(Some(true));
6663        };
6664        if result.to_boolean()
6665            && !target.is_extensible()
6666            && !same_proto(proto.as_ref(), target.proto().as_ref())
6667        {
6668            return Err(self.type_error(
6669                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6670            ));
6671        }
6672        Ok(Some(result.to_boolean()))
6673    }
6674
6675    /// `[[IsExtensible]]` on a proxy.
6676    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6677        let Some((target, handler)) = self.proxy_parts(object)? else {
6678            return Ok(None);
6679        };
6680        let Some(result) = self.proxy_trap(
6681            &handler,
6682            "isExtensible",
6683            vec![Value::Object(target.clone())],
6684        )?
6685        else {
6686            return Ok(Some(target.is_extensible()));
6687        };
6688        // The answer is not the proxy's to invent: it must agree with the target, or a
6689        // script could learn `false` while the target keeps accepting new properties.
6690        if result.to_boolean() != target.is_extensible() {
6691            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6692        }
6693        Ok(Some(result.to_boolean()))
6694    }
6695
6696    /// `[[PreventExtensions]]` on a proxy.
6697    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6698        let Some((target, handler)) = self.proxy_parts(object)? else {
6699            return Ok(None);
6700        };
6701        let Some(result) = self.proxy_trap(
6702            &handler,
6703            "preventExtensions",
6704            vec![Value::Object(target.clone())],
6705        )?
6706        else {
6707            target.set_extensible(false);
6708            return Ok(Some(true));
6709        };
6710        if result.to_boolean() && target.is_extensible() {
6711            return Err(self.type_error(
6712                "proxy 'preventExtensions' reported success but the target is still extensible",
6713            ));
6714        }
6715        Ok(Some(result.to_boolean()))
6716    }
6717
6718    /// `[[Call]]` on a proxy, through the `apply` trap.
6719    fn proxy_apply(
6720        &mut self,
6721        object: &Gc<JsObject>,
6722        this: Value,
6723        args: Vec<Value>,
6724    ) -> JsResult<Option<Value>> {
6725        let Some((target, handler)) = self.proxy_parts(object)? else {
6726            return Ok(None);
6727        };
6728        // The trap gets the arguments as one array, which is the shape the spec passes
6729        // and the shape `apply` traps are written against (`args[0]` is the first one).
6730        let arguments = self.new_array(args.clone());
6731        let this_for_trap = this.clone();
6732        let Some(result) = self.proxy_trap(
6733            &handler,
6734            "apply",
6735            vec![
6736                Value::Object(target.clone()),
6737                this_for_trap,
6738                Value::Object(arguments),
6739            ],
6740        )?
6741        else {
6742            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6743        };
6744        Ok(Some(result))
6745    }
6746
6747    /// `[[Construct]]` on a proxy, through the `construct` trap.
6748    fn proxy_construct(
6749        &mut self,
6750        object: &Gc<JsObject>,
6751        args: Vec<Value>,
6752        new_target: &Value,
6753    ) -> JsResult<Option<Value>> {
6754        let Some((target, handler)) = self.proxy_parts(object)? else {
6755            return Ok(None);
6756        };
6757        if !target.is_callable() {
6758            return Err(self.type_error("proxy target is not a constructor"));
6759        }
6760        let arguments = self.new_array(args.clone());
6761        let Some(result) = self.proxy_trap(
6762            &handler,
6763            "construct",
6764            vec![
6765                Value::Object(target.clone()),
6766                Value::Object(arguments),
6767                new_target.clone(),
6768            ],
6769        )?
6770        else {
6771            return Ok(Some(self.construct(
6772                Value::Object(target),
6773                new_target.clone(),
6774                args,
6775            )?));
6776        };
6777        if !matches!(result, Value::Object(_)) {
6778            return Err(self.type_error("proxy 'construct' must return an object"));
6779        }
6780        Ok(Some(result))
6781    }
6782
6783    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6784    pub(crate) fn has_own_or_inherited(
6785        &mut self,
6786        object: &Gc<JsObject>,
6787        key: &PropertyKey,
6788    ) -> JsResult<bool> {
6789        // The object itself first: it may be a proxy, and then the answer is its trap's.
6790        if let Some(answer) = self.proxy_has(object, key)? {
6791            return Ok(answer);
6792        }
6793        // An integer-indexed exotic object answers a canonical numeric index from
6794        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
6795        // prototype chain. That is observable twice: a view the buffer has been resized
6796        // away from has no indices, so `2 in view` is `false` even when
6797        // `Object.getPrototypeOf(view)[2]` exists (what
6798        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
6799        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
6800        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
6801        // goes through here, which is why the same rule is repeated in `has_property_key`
6802        // rather than living only there.
6803        if object.typed_array_parts().is_some()
6804            && let Some(numeric) = canonical_numeric_index(key)
6805        {
6806            return Ok(typed_array_index_is_valid(object, numeric));
6807        }
6808        // A host class answers `in` for its own keys, which may live nowhere in a property
6809        // table — `"x" in point` is true because the class says so, not because a property
6810        // exists.
6811        if let Some(exotic) = object.exotic()
6812            && let Some(answer) = exotic.has_property(self, object, key)?
6813        {
6814            return Ok(answer);
6815        }
6816        // `has_own` rather than `own_property_key`: an array's elements and its derived
6817        // `length` are invisible to the property table, and `Array.prototype` is an array.
6818        // A host class's `get_own_property` counts too, because the reference's
6819        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6820        // lives — a class with only `get_own_property` answers `in` through it.
6821        if self.exotic_has_own(object, key)? {
6822            return Ok(true);
6823        }
6824        // A hole is *not* the end of the search: the chain may still have the key, which
6825        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6826        for ancestor in object.chain() {
6827            // A proxy further up the chain answers for itself.
6828            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6829                return Ok(answer);
6830            }
6831            // Same for a host class: a prototype may be one, and `in` reaches it.
6832            if let Some(exotic) = ancestor.exotic()
6833                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6834            {
6835                return Ok(answer);
6836            }
6837            if self.exotic_has_own(&ancestor, key)? {
6838                return Ok(true);
6839            }
6840        }
6841        Ok(false)
6842    }
6843
6844    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6845    /// trap included.
6846    ///
6847    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6848    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6849    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6850        if let Some(exotic) = object.exotic()
6851            && let Some(answer) = exotic.get_own_property(self, object, key)?
6852        {
6853            return Ok(answer.is_some());
6854        }
6855        Ok(has_own(object, key))
6856    }
6857
6858    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6859    ///
6860    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6861    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6862    /// `TypeError` instead of a property named `"1.5"`.
6863    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6864        let object = self.object_from(value)?;
6865        let length = self
6866            .get_property(&object, "length")?
6867            .map(|value| value.to_number())
6868            .unwrap_or(0.0);
6869        if !length.is_finite() || length < 0.0 {
6870            return Err(self.type_error("invalid array-like length"));
6871        }
6872        let length = length as usize;
6873        let mut items = Vec::with_capacity(length.min(1024));
6874        for index in 0..length {
6875            let item = self
6876                .get_property(&object, &index.to_string())?
6877                .unwrap_or(Value::Undefined);
6878            if keys_only && matches!(&item, Value::Symbol(_)) {
6879                items.push(item);
6880                continue;
6881            }
6882            if keys_only && !matches!(&item, Value::String(_)) {
6883                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6884            }
6885            items.push(item);
6886        }
6887        Ok(items)
6888    }
6889
6890    /// A `Property` from the descriptor object a trap returned.
6891    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6892        let object = self.object_from(value)?;
6893        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6894            interp.get_property(&object, name)
6895        };
6896        let getter = field(self, "get")?;
6897        let setter = field(self, "set")?;
6898        let accessor = getter.is_some() || setter.is_some();
6899        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6900            Ok(interp
6901                .get_property(&object, name)?
6902                .is_some_and(|value| value.to_boolean()))
6903        };
6904        let enumerable = boolean(self, "enumerable")?;
6905        let configurable = boolean(self, "configurable")?;
6906        if accessor {
6907            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6908                return Err(
6909                    self.type_error("a descriptor cannot be both a data property and an accessor")
6910                );
6911            }
6912            Ok(Property {
6913                getter: getter.or(Some(Value::Undefined)),
6914                setter: setter.or(Some(Value::Undefined)),
6915                enumerable,
6916                configurable,
6917                writable: false,
6918                value: None,
6919                descriptor_fields: None,
6920            })
6921        } else {
6922            Ok(Property {
6923                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6924                writable: boolean(self, "writable")?,
6925                enumerable,
6926                configurable,
6927                getter: None,
6928                setter: None,
6929                descriptor_fields: None,
6930            })
6931        }
6932    }
6933
6934    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6935    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6936        let object = self.new_object(None);
6937        // A partial descriptor names only some fields, and the trap must see exactly those:
6938        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
6939        // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
6940        // case, where every field is present.
6941        let fields = property.descriptor_fields;
6942        let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
6943            fields.is_none_or(|fields| field(&fields))
6944        };
6945        if property.is_accessor() {
6946            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6947            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6948            object.define_data("get", getter);
6949            object.define_data("set", setter);
6950        } else {
6951            if names(|fields| fields.value) {
6952                let value = property.value.clone().unwrap_or(Value::Undefined);
6953                object.define_data("value", value);
6954            }
6955            if names(|fields| fields.writable) {
6956                object.define_data("writable", Value::Bool(property.writable));
6957            }
6958        }
6959        if names(|fields| fields.enumerable) {
6960            object.define_data("enumerable", Value::Bool(property.enumerable));
6961        }
6962        if names(|fields| fields.configurable) {
6963            object.define_data("configurable", Value::Bool(property.configurable));
6964        }
6965        Value::Object(object)
6966    }
6967
6968    // -- calling ------------------------------------------------------------
6969
6970    /// Call `callee` with `this` and `args`.
6971    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6972        let Value::Object(function) = &callee else {
6973            // `typeof x === "function"` is not enough to make `x()` legal: only a
6974            // callable object is. `null` and `undefined` need no special wording
6975            // here — their `ToString` already reads the way the reference's does.
6976            let what = format!("{} is not a function", callee.to_js_string());
6977            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6978        };
6979        // A proxy of a function is called through its `apply` trap. It has no
6980        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6981        // below, and a proxy of a non-function has nothing to forward to.
6982        if function.proxy_state().is_some() {
6983            return match self.proxy_apply(function, this, args)? {
6984                Some(result) => Ok(result),
6985                None => Err(Signal::Throw(
6986                    self.make_error("TypeError", "proxy target is not callable"),
6987                )),
6988            };
6989        }
6990        let callable = function.with(|data| match &data.kind {
6991            ObjectKind::Function(callable) => match callable {
6992                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6993                // The `Rc` is cloned out so the borrow of this object's data is released
6994                // before the closure runs: the closure may touch the same object.
6995                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6996                Callable::Bound {
6997                    target,
6998                    this,
6999                    args: leading,
7000                } => Some(NativeCall::Bound {
7001                    target: target.clone(),
7002                    this: this.clone(),
7003                    leading: leading.clone(),
7004                }),
7005                Callable::Bytecode { code, env } => {
7006                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
7007                }
7008                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7009                Callable::PromiseResolve(promise) => {
7010                    Some(NativeCall::PromiseResolve(promise.clone()))
7011                }
7012                Callable::PromiseReject(promise) => {
7013                    Some(NativeCall::PromiseReject(promise.clone()))
7014                }
7015                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7016                    state: state.clone(),
7017                }),
7018                Callable::ThenShim {
7019                    handler,
7020                    resolve,
7021                    reject,
7022                    fulfilled,
7023                } => Some(NativeCall::ThenShim {
7024                    handler: handler.clone(),
7025                    resolve: resolve.clone(),
7026                    reject: reject.clone(),
7027                    fulfilled: *fulfilled,
7028                }),
7029                Callable::AwaitResume {
7030                    coroutine,
7031                    promise,
7032                    kind,
7033                } => Some(NativeCall::AwaitResume {
7034                    coroutine: coroutine.clone(),
7035                    promise: promise.clone(),
7036                    kind: *kind,
7037                }),
7038                Callable::CombinatorSettle {
7039                    state,
7040                    index,
7041                    fulfilled,
7042                } => Some(NativeCall::CombinatorSettle {
7043                    state: state.clone(),
7044                    index: *index,
7045                    fulfilled: *fulfilled,
7046                }),
7047                Callable::FinallyShim {
7048                    callback,
7049                    fulfilled,
7050                    constructor,
7051                } => Some(NativeCall::FinallyShim {
7052                    callback: callback.clone(),
7053                    fulfilled: *fulfilled,
7054                    constructor: constructor.clone(),
7055                }),
7056                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7057                Callable::CompletedReturn {
7058                    generator,
7059                    promise,
7060                    rejected,
7061                } => Some(NativeCall::CompletedReturn {
7062                    generator: generator.clone(),
7063                    promise: promise.clone(),
7064                    rejected: *rejected,
7065                }),
7066                Callable::YieldResult {
7067                    generator,
7068                    promise,
7069                    done,
7070                } => Some(NativeCall::YieldResult {
7071                    generator: generator.clone(),
7072                    promise: promise.clone(),
7073                    done: *done,
7074                }),
7075                Callable::DisposeStep {
7076                    remaining,
7077                    promise,
7078                    error,
7079                    rejected,
7080                } => Some(NativeCall::DisposeStep {
7081                    remaining: remaining.clone(),
7082                    promise: promise.clone(),
7083                    error: error.clone(),
7084                    rejected: *rejected,
7085                }),
7086                Callable::GeneratorResume {
7087                    generator,
7088                    promise,
7089                    kind,
7090                } => Some(NativeCall::GeneratorResume {
7091                    generator: generator.clone(),
7092                    promise: promise.clone(),
7093                    kind: *kind,
7094                }),
7095                Callable::SettlePromise {
7096                    promise,
7097                    value,
7098                    rejected,
7099                } => Some(NativeCall::SettlePromise {
7100                    promise: promise.clone(),
7101                    value: value.clone(),
7102                    rejected: *rejected,
7103                }),
7104            },
7105            _ => None,
7106        });
7107        match callable {
7108            Some(NativeCall::Host(func)) => {
7109                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7110                // function by name rather than stopping at the caller.
7111                let frame_less = function
7112                    .own_property("_frame_less")
7113                    .and_then(|property| property.value)
7114                    .is_some_and(|value| value.to_boolean());
7115                let outer = if frame_less {
7116                    None
7117                } else {
7118                    self.native_frames
7119                        .push((function.clone(), self.frames.len()));
7120                    Some(self.current_native.replace(function.clone()))
7121                };
7122                let result = {
7123                    let mut body = func.borrow_mut();
7124                    body(self, this, &args)
7125                };
7126                if !frame_less {
7127                    self.native_frames.pop();
7128                    self.current_native = outer.flatten();
7129                }
7130                result
7131            }
7132            Some(NativeCall::Native(func)) => {
7133                // A function marked `_frame_less` is one the reference implements
7134                // without a call frame — `eval` is the only one so far.
7135                let frame_less = function
7136                    .own_property("_frame_less")
7137                    .and_then(|property| property.value)
7138                    .is_some_and(|value| value.to_boolean());
7139                let outer = if frame_less {
7140                    None
7141                } else {
7142                    self.native_frames
7143                        .push((function.clone(), self.frames.len()));
7144                    Some(self.current_native.replace(function.clone()))
7145                };
7146                let result = func(self, this, &args);
7147                if !frame_less {
7148                    self.native_frames.pop();
7149                    self.current_native = outer.flatten();
7150                }
7151                result
7152            }
7153            Some(NativeCall::Revoker(slots)) => {
7154                // Idempotent: revoking twice answers `undefined` again rather than
7155                // complaining, which is what the spec says and what a `finally` block
7156                // relies on.
7157                let mut state = slots.borrow_mut();
7158                state.target = None;
7159                state.handler = None;
7160                Ok(Value::Undefined)
7161            }
7162            Some(NativeCall::PromiseResolve(promise)) => {
7163                // One-shot: a second call is silently ignored, which
7164                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7165                let value = args.first().cloned().unwrap_or(Value::Undefined);
7166                self.resolve_promise_with(&promise, value)?;
7167                Ok(Value::Undefined)
7168            }
7169            Some(NativeCall::PromiseReject(promise)) => {
7170                let reason = args.first().cloned().unwrap_or(Value::Undefined);
7171                self.reject_promise(&promise, reason);
7172                Ok(Value::Undefined)
7173            }
7174            Some(NativeCall::ThenShim {
7175                handler,
7176                resolve,
7177                reject,
7178                fulfilled,
7179            }) => {
7180                // `PerformPromiseThen` with a capability: run the handler, then settle
7181                // through the capability's own pair. A throw from the handler is the
7182                // rejection, and a throw from the capability's `resolve` is not caught —
7183                // exactly the spec's `?`.
7184                let value = args.first().cloned().unwrap_or(Value::Undefined);
7185                match handler {
7186                    Some(handler) => {
7187                        match self.call_value(handler, Value::Undefined, vec![value]) {
7188                            Ok(result) => {
7189                                self.call_value(resolve, Value::Undefined, vec![result])?;
7190                            }
7191                            Err(Signal::Throw(reason)) => {
7192                                self.call_value(reject, Value::Undefined, vec![reason])?;
7193                            }
7194                            Err(signal) => return Err(signal),
7195                        }
7196                    }
7197                    None => {
7198                        let handler = if fulfilled { resolve } else { reject };
7199                        self.call_value(handler, Value::Undefined, vec![value])?;
7200                    }
7201                }
7202                Ok(Value::Undefined)
7203            }
7204            Some(NativeCall::CapabilityExecutor { state }) => {
7205                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7206                // slot holds a value yet. The test is on the *values*, not on a call count —
7207                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7208                // called-twice`'s first case does exactly that), while a second call after a
7209                // real pair is the `TypeError`.
7210                let defined = |name: &str| {
7211                    state
7212                        .own_property(name)
7213                        .and_then(|property| property.value)
7214                        .is_some_and(|value| !matches!(value, Value::Undefined))
7215                };
7216                if defined("resolve") || defined("reject") {
7217                    return Err(self.type_error("promise capability executor called twice"));
7218                }
7219                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7220                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7221                state.define_data("resolve", resolve);
7222                state.define_data("reject", reject);
7223                Ok(Value::Undefined)
7224            }
7225            Some(NativeCall::CombinatorSettle {
7226                state,
7227                index,
7228                fulfilled,
7229            }) => {
7230                let value = args.first().cloned().unwrap_or(Value::Undefined);
7231                self.settle_combinator(&state, index, fulfilled, value)?;
7232                Ok(Value::Undefined)
7233            }
7234            Some(NativeCall::AwaitResume {
7235                coroutine,
7236                promise,
7237                kind,
7238            }) => {
7239                // Resume *inline*, in the reaction that delivered the value. Deferring it
7240                // by another job inserts a tick between every `await` and its
7241                // continuation, which reorders `await` against unrelated `then` chains —
7242                // `f().then(g)` then runs before `f`'s own next statement.
7243                self.drive_async(
7244                    &coroutine,
7245                    &promise,
7246                    kind,
7247                    args.first().cloned().unwrap_or(Value::Undefined),
7248                )
7249                .map(|()| Value::Undefined)
7250            }
7251            Some(NativeCall::FinallyShim {
7252                callback,
7253                fulfilled,
7254                constructor,
7255            }) => {
7256                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
7257                // that settles with the *original* outcome once the callback's result has
7258                // settled. The callback's own value is discarded — that is the whole
7259                // difference between `finally` and `then`.
7260                let original = args.first().cloned().unwrap_or(Value::Undefined);
7261                let result = match &callback {
7262                    Some(callback) => {
7263                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7264                    }
7265                    None => Value::Undefined,
7266                };
7267                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
7268                // already a promise of this constructor is reused rather than rewrapped.
7269                let resolved = self.promise_resolve_for(&constructor, result)?;
7270                let Value::Object(resolved) = resolved else {
7271                    return Ok(original);
7272                };
7273                // The wait is a chained promise rather than a bare return, so a callback
7274                // that returns a slow promise really does delay the continuation.
7275                let waiting = self.new_promise();
7276                let pass = JsObject::function(
7277                    self.heap,
7278                    Some(self.realm.function_proto.clone()),
7279                    Callable::SettlePromise {
7280                        promise: waiting.clone(),
7281                        value: original,
7282                        rejected: !fulfilled,
7283                    },
7284                );
7285                let pass = Value::Object(pass);
7286                // Whichever way the callback's promise settles, the original outcome wins.
7287                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
7288                Ok(Value::Object(waiting))
7289            }
7290            Some(NativeCall::DisposeStep {
7291                remaining,
7292                promise,
7293                error,
7294                rejected,
7295            }) => {
7296                let error = if rejected {
7297                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
7298                    self.merge_dispose_error(reason, error)
7299                } else {
7300                    error
7301                };
7302                self.dispose_step(&remaining, &promise, error)?;
7303                Ok(Value::Undefined)
7304            }
7305            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7306            Some(NativeCall::CompletedReturn {
7307                generator,
7308                promise,
7309                rejected,
7310            }) => {
7311                let value = args.first().cloned().unwrap_or(Value::Undefined);
7312                let outcome = if rejected {
7313                    AsyncOutcome::Error(value)
7314                } else {
7315                    AsyncOutcome::Value(self.iterator_result(value, true)?)
7316                };
7317                self.settle_async_request(&generator, &promise, outcome)?;
7318                Ok(Value::Undefined)
7319            }
7320            Some(NativeCall::YieldResult {
7321                generator,
7322                promise,
7323                done,
7324            }) => {
7325                let value = args.first().cloned().unwrap_or(Value::Undefined);
7326                let result = self.iterator_result(value, done)?;
7327                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7328                Ok(Value::Undefined)
7329            }
7330            Some(NativeCall::GeneratorResume {
7331                generator,
7332                promise,
7333                kind,
7334            }) => {
7335                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7336                // tick and reorders the generator against other chains.
7337                self.step_async_generator(
7338                    &generator,
7339                    &promise,
7340                    kind,
7341                    args.first().cloned().unwrap_or(Value::Undefined),
7342                )
7343                .map(|()| Value::Undefined)
7344            }
7345            Some(NativeCall::SettlePromise {
7346                promise,
7347                value,
7348                rejected,
7349            }) => {
7350                if rejected {
7351                    self.reject_promise(&promise, value);
7352                } else {
7353                    self.fulfill_promise(&promise, value);
7354                }
7355                Ok(Value::Undefined)
7356            }
7357            Some(NativeCall::Bound {
7358                target,
7359                this: bound_this,
7360                leading,
7361            }) => {
7362                let mut all = leading;
7363                all.extend(args);
7364                self.call_value(target, bound_this, all)
7365            }
7366            Some(NativeCall::Bytecode(code, env)) => {
7367                if code.code.kind.is_generator() {
7368                    return self.new_generator(callee, this, args);
7369                }
7370                if code.code.kind.is_async() {
7371                    // Same coroutine machinery as a generator; the difference is only in
7372                    // what the completion does — see `new_async_function`.
7373                    return self.new_async_function(callee, this, args);
7374                }
7375                self.execute(code, env, this, args, callee)
7376            }
7377            None => Err(Signal::Throw(
7378                self.make_error("TypeError", "not a function"),
7379            )),
7380        }
7381    }
7382
7383    /// Give a freshly built function its own `prototype` object.
7384    ///
7385    /// Every function that can be used with `new` carries one, and its
7386    /// `constructor` points back at the function — a reference cycle, which is
7387    /// exactly what the collector's cycle pass exists to reclaim.
7388    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7389        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
7390        let constructor = Value::Object(function.clone());
7391        prototype.define(
7392            "constructor",
7393            Property::with_attributes(constructor, true, false),
7394        );
7395        let value = Value::Object(prototype);
7396        function.define("prototype", Property::prototype_of(value, true));
7397    }
7398
7399    /// A getter or setter that reads or writes the reference cell behind a mapped
7400    /// `arguments` index.
7401    ///
7402    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
7403    /// count — which is what the collector treats as "a reference from outside the
7404    /// heap". The closure therefore keeps the cell alive for exactly as long as the
7405    /// accessor is reachable, which is the same lifetime the arguments object has.
7406    ///
7407    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
7408    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
7409    /// parameter value and the arguments object reaches the closure, never the other
7410    /// way round. Nothing the collector has to see is hidden.
7411    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
7412        let name = if is_setter { "set" } else { "get" };
7413        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
7414            if is_setter {
7415                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
7416                Ok(Value::Undefined)
7417            } else {
7418                Ok(cell.get())
7419            }
7420        };
7421        self.new_host_function(name, 1, Box::new(func))
7422    }
7423
7424    /// The object `special_object` builds.
7425    ///
7426    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
7427    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
7428    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
7429    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
7430    /// write through `arguments` does not reach the parameter.
7431    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
7432        match magic {
7433            0 | 1 => {
7434                let args = self.frame().passed().to_vec();
7435                let proto = self.realm.object_proto.clone();
7436                let object = self.new_object(Some(proto));
7437                // The marker `Object.prototype.toString` needs: an arguments object is an
7438                // ordinary object apart from reporting `[object Arguments]`, and that has
7439                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
7440                // show up ahead of them in a key listing anyway — it is non-enumerable.
7441                self.internal_set(&object, "_class", self.string("Arguments"));
7442                // `length` is writable and configurable but neither enumerable nor a
7443                // plain data property: `Object.keys(arguments)` lists the indices only,
7444                // which is how `{...arguments}` copies them without the length.
7445                object.define(
7446                    "length",
7447                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
7448                );
7449                // `magic == 1` is sloppy mode, where each index is *mapped* to the
7450                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
7451                // change `a`, and assigning `a` has to change `arguments[0]`.
7452                //
7453                // The shared storage is the parameter's reference cell. The compiler
7454                // gives every parameter of such a function one (see
7455                // `provide_body_arguments`), and the cell outlives the frame, so this
7456                // keeps working after the arguments object escapes.
7457                //
7458                // The index becomes an accessor rather than a data property. A mapped
7459                // index reports as a plain writable/enumerable data property through
7460                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
7461                // the getter/setter pair is only the plumbing underneath.
7462                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
7463                    let frame = self.frame();
7464                    frame
7465                        .code
7466                        .arg_cell
7467                        .iter()
7468                        .map(|cell| {
7469                            (*cell >= 0)
7470                                .then(|| frame.cells.get(*cell as usize).cloned())
7471                                .flatten()
7472                        })
7473                        .collect()
7474                } else {
7475                    Vec::new()
7476                };
7477                // Tell the object which indices are mapped, so
7478                // `Object.getOwnPropertyDescriptor` can report them as the data
7479                // properties the spec describes instead of the accessors that
7480                // implement the aliasing.
7481                if magic == 1 {
7482                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
7483                    for cell in &mapped_cells {
7484                        table.push(cell.clone());
7485                    }
7486                    object.set_mapped_arguments(table);
7487                }
7488                for (index, value) in args.into_iter().enumerate() {
7489                    match mapped_cells.get(index).cloned().flatten() {
7490                        Some(cell) => {
7491                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
7492                            let setter = self.new_mapped_arguments_accessor(cell, true);
7493                            object.define(
7494                                &index.to_string(),
7495                                Property::accessor_with(
7496                                    Some(Value::Object(getter)),
7497                                    Some(Value::Object(setter)),
7498                                    true,
7499                                ),
7500                            );
7501                        }
7502                        None => object.define_data(&index.to_string(), value),
7503                    }
7504                }
7505                // §10.4.4.6: an *unmapped* (strict) arguments object gets a
7506                // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
7507                // non-enumerable and non-configurable. It is not a nicety — it is the only
7508                // documented way to reach `%ThrowTypeError%`:
7509                //
7510                //     Object.getOwnPropertyDescriptor(function(){"use strict";
7511                //         return arguments;}(), "callee").get
7512                //
7513                // and the whole `ThrowTypeError/` directory is written against that
7514                // expression. Without it 13 cases failed with `cannot read property 'get'
7515                // of undefined`, which reads like a test harness bug rather than a missing
7516                // accessor.
7517                //
7518                // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
7519                // writable data property holding the function being called, and
7520                // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
7521                // `hasOwnProperty("callee")` hold there.
7522                if magic == 1 {
7523                    let callee = self.frame().callee.clone();
7524                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
7525                    object.define("callee", Property::with_attributes(callee, true, false));
7526                } else if let Some(thrower) = self.realm.throw_type_error.clone()
7527                    && object.own_property("callee").is_none()
7528                {
7529                    object.define(
7530                        "callee",
7531                        Property {
7532                            getter: Some(Value::Object(thrower.clone())),
7533                            setter: Some(Value::Object(thrower)),
7534                            enumerable: false,
7535                            configurable: false,
7536                            ..Property::default()
7537                        },
7538                    );
7539                }
7540                // An arguments object is iterable: `[...arguments]` and
7541                // `for (const a of arguments)` both work, through the *array* iterator
7542                // because the object is array-like. Without this the whole spread form
7543                // reported "not iterable".
7544                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
7545                let values = self
7546                    .realm
7547                    .array_proto
7548                    .own_property("values")
7549                    .and_then(|property| property.value);
7550                if let Some(values) = values {
7551                    object.define_key(
7552                        &iterator_key,
7553                        Property::with_attributes(values, true, false),
7554                    );
7555                }
7556                Ok(Value::Object(object))
7557            }
7558            // `this.active_func`: the constructor `super()` resolves against.
7559            //
7560            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
7561            // own, so it inherits this from the function it was written in along with `this`
7562            // — and that is a lexical relationship, not a stack one: an arrow that escaped
7563            // the constructor and is called back later (`iter.return = () => super()`) has
7564            // the constructor nowhere on the stack. The compiler therefore reads it out of
7565            // a closure variable of the enclosing function, exactly as the reference does
7566            // with its `this_active_func` local.
7567            2 => Ok(self
7568                .current_callee()
7569                .map_or(Value::Undefined, Value::Object)),
7570            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
7571            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
7572            // its own either, so the lookup walks out to the nearest non-arrow frame for
7573            // the same reason as `this.active_func` above — without that, `super()` inside
7574            // an arrow passed `undefined` as the new target and the parent constructor was
7575            // then rejected for being invoked without `new`.
7576            3 => Ok(self
7577                .eval_new_target
7578                .clone()
7579                .unwrap_or_else(|| self.frame().new_target.clone())),
7580            // `[[HomeObject]]` of the function being run: what `super` is relative to.
7581            // An arrow has none of its own, so the lookup walks out to the enclosing
7582            // method — which is why `super` works inside an arrow inside a method.
7583            4 => Ok(self
7584                .frames
7585                .iter()
7586                .rev()
7587                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7588                .map_or(Value::Undefined, Value::Object)),
7589            // `import.meta`: the innermost module body's meta object. Outside a module
7590            // the compiler never emits this, so an empty fallback is unreachable rather
7591            // than permissive.
7592            6 => {
7593                let name = self.module_stack.last().cloned();
7594                let meta = name
7595                    .and_then(|name| self.modules.get(&name).cloned())
7596                    .and_then(|module| module.with(|r| r.import_meta.clone()));
7597                Ok(meta.map_or(Value::Undefined, Value::Object))
7598            }
7599            other => Err(Signal::Throw(self.make_error(
7600                "InternalError",
7601                &format!("special_object {other} is not implemented yet"),
7602            ))),
7603        }
7604    }
7605
7606    /// `[[HomeObject]]` of the innermost function that has one, if any.
7607    ///
7608    /// An arrow has none, so the search walks out to the enclosing method — the same
7609    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
7610    /// inside a method.
7611    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
7612        self.frames
7613            .iter()
7614            .rev()
7615            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7616    }
7617
7618    /// The dispose method a `using` declaration should snapshot, or an error.
7619    ///
7620    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
7621    /// is what makes a resource that only knows the synchronous protocol usable in both
7622    /// forms.
7623    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
7624        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
7625        if value.is_nullish() {
7626            return Ok(Value::Undefined);
7627        }
7628        let Some(object) = value.as_object() else {
7629            return Err(self.type_error("not an object"));
7630        };
7631        let mut method = if await_form {
7632            let found = self.get_property_key(
7633                object,
7634                &self.realm.well_known_key(WellKnown::AsyncDisposable),
7635            )?;
7636            match found {
7637                Some(found) if !found.is_nullish() => Some(found),
7638                _ => self
7639                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
7640            }
7641        } else {
7642            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
7643        };
7644        let Some(found) = method.take() else {
7645            return Err(self.type_error("value is not disposable"));
7646        };
7647        if found.is_nullish() {
7648            return Err(self.type_error("value is not disposable"));
7649        }
7650        let callable = found.as_object().is_some_and(|object| object.is_callable());
7651        if !callable {
7652            return Err(self.type_error("dispose method is not a function"));
7653        }
7654        Ok(found)
7655    }
7656
7657    /// Call one resource's disposer, folding a failure into `error_state`.
7658    ///
7659    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
7660    /// because a captured `using` binding lives in its reference cell and the local slot is
7661    /// stale — a closure over the resource is legal and must not change what is disposed.
7662    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
7663        let value = self.get_loc(slot);
7664        let method = self.get_loc(slot + 1);
7665        // A resource that was never initialised — its declaration threw — or that is
7666        // `null`/`undefined` has nothing to dispose.
7667        if value.is_nullish() || matches!(value, Value::Uninitialized) {
7668            return Ok(error_state);
7669        }
7670        if matches!(method, Value::Undefined | Value::Uninitialized) {
7671            return Ok(error_state);
7672        }
7673        match self.call_value(method, value, Vec::new()) {
7674            Ok(_) => Ok(error_state),
7675            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
7676            Err(other) => Err(other),
7677        }
7678    }
7679
7680    /// Combine a disposal failure with whatever was already going wrong.
7681    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
7682        if matches!(error_state, Value::Uninitialized) {
7683            return new_error;
7684        }
7685        self.new_suppressed_error(new_error, error_state)
7686    }
7687
7688    /// A `SuppressedError` instance built straight from its prototype.
7689    ///
7690    /// Not through the constructor: a script that rewrites
7691    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
7692    /// error wrapping.
7693    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
7694        let proto = self
7695            .realm
7696            .suppressed_error_proto
7697            .clone()
7698            .unwrap_or_else(|| self.realm.error_proto.clone());
7699        let object = self.new_object(Some(proto));
7700        object.define("error", Property::with_attributes(error, true, true));
7701        object.define(
7702            "suppressed",
7703            Property::with_attributes(suppressed, true, true),
7704        );
7705        object.define(
7706            "message",
7707            Property::with_attributes(self.string("SuppressedError"), true, true),
7708        );
7709        self.internal_set(&object, "_class", self.string("Error"));
7710        self.add_stack(&object);
7711        Value::Object(object)
7712    }
7713
7714    /// Call `callee`, or push its frame and let the main loop run it.
7715    ///
7716    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
7717    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
7718    /// continues, so `function f(){ return f() }` costs heap and stops at
7719    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
7720    /// is entered directly, and natives do not re-enter JavaScript in this
7721    /// milestone.
7722    ///
7723    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
7724    /// because the returning frame will.
7725    /// The elements of an array-like value, as a call argument list.
7726    ///
7727    /// `apply` accepts any array-like, not only a real array: the reference reads
7728    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
7729    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
7730        let Some(object) = value.as_object().cloned() else {
7731            if value.is_nullish() {
7732                // `f.apply(this, null)` passes no arguments at all.
7733                return Ok(Vec::new());
7734            }
7735            return Err(self.type_error("createListFromArrayLike called on non-object"));
7736        };
7737        let length = match self.get_property(&object, "length")? {
7738            Some(length) => length.to_number(),
7739            None => 0.0,
7740        };
7741        if !length.is_finite() || length <= 0.0 {
7742            return Ok(Vec::new());
7743        }
7744        let length = (length as usize).min(1_000_000);
7745        let mut args = Vec::with_capacity(length);
7746        for index in 0..length {
7747            let element = self.get_property(&object, &index.to_string())?;
7748            args.push(element.unwrap_or(Value::Undefined));
7749        }
7750        Ok(args)
7751    }
7752
7753    /// Turn a call to a generator function into a generator object.
7754    ///
7755    /// The frame is built exactly as an ordinary call would build it, then detached and
7756    /// stored in the generator before any body instruction runs — which is what makes
7757    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
7758    /// is `initial_yield`, the first instruction of every suspending body.
7759    pub fn new_generator(
7760        &mut self,
7761        function: Value,
7762        this: Value,
7763        args: Vec<Value>,
7764    ) -> JsResult<Value> {
7765        let Some(object) = function.as_object().cloned() else {
7766            return Err(self.type_error("not a generator function"));
7767        };
7768        let Some((code, env)) = bytecode_of(&object) else {
7769            return Err(self.type_error("not a generator function"));
7770        };
7771        let is_async = code.code.kind.is_async();
7772        self.push_frame(code, env, this, args, function)?;
7773        let frame = self.frames.pop().expect("push_frame just pushed it");
7774        // A fresh generator is *suspended at start*: the body has not run, so a
7775        // `return`/`throw` on it finishes without executing anything.
7776        let mut state = GeneratorState {
7777            frame: Some(frame),
7778            phase: GeneratorPhase::SuspendedStart,
7779            parked_on_await: false,
7780            parked_on_yield_star: false,
7781            requests: std::collections::VecDeque::new(),
7782            async_busy: false,
7783        };
7784        // Run to the first suspension. For a generator that is `initial_yield`, so no
7785        // body code runs; for a malformed body it would be the first `yield`.
7786        // An `async function*` answers an async generator: same coroutine, but its
7787        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7788        let proto = if is_async {
7789            self.realm
7790                .async_generator_proto
7791                .clone()
7792                .unwrap_or_else(|| self.realm.generator_proto.clone())
7793        } else {
7794            self.realm.generator_proto.clone()
7795        };
7796        let generator = self.new_object(Some(proto));
7797        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7798            Ok(_) => {}
7799            Err(error) => return Err(error),
7800        }
7801        generator.with_mut(|data| {
7802            data.kind = ObjectKind::Generator(Box::new(state));
7803        });
7804        Ok(Value::Object(generator))
7805    }
7806
7807    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7808    ///
7809    /// Returns the `{value, done}` object itself rather than the pair, because a
7810    /// `yield*` suspension already has one — the inner iterator's own result — and the
7811    /// protocol says to hand that straight through rather than nest it.
7812    /// Advance a generator and report *why* it parked.
7813    ///
7814    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7815    /// "hand this value to the caller" — but an async generator does: an `await` has to
7816    /// settle before it can answer, while a `yield` is the answer.
7817    fn resume_generator_detailed(
7818        &mut self,
7819        generator: &Gc<JsObject>,
7820        kind: ResumeKind,
7821        value: Value,
7822    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7823        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7824            ObjectKind::Generator(state) => Some(std::mem::replace(
7825                state.as_mut(),
7826                GeneratorState {
7827                    frame: None,
7828                    phase: GeneratorPhase::Executing,
7829                    parked_on_await: false,
7830                    parked_on_yield_star: false,
7831                    requests: std::collections::VecDeque::new(),
7832                    async_busy: false,
7833                },
7834            )),
7835            _ => None,
7836        }) else {
7837            return Err(self.type_error("not a generator"));
7838        };
7839        let result = self.step_generator(&mut state, kind, value);
7840        generator.with_mut(|data| {
7841            data.kind = ObjectKind::Generator(Box::new(state));
7842        });
7843        result
7844    }
7845
7846    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7847    ///
7848    /// Returns the `{value, done}` object itself rather than the pair, because a
7849    /// `yield*` suspension already has one — the inner iterator's own result — and the
7850    /// protocol says to hand that straight through rather than nest it.
7851    pub fn resume_generator(
7852        &mut self,
7853        generator: &Gc<JsObject>,
7854        kind: ResumeKind,
7855        value: Value,
7856    ) -> JsResult<Value> {
7857        let (value, done, ready, _reason) =
7858            self.resume_generator_detailed(generator, kind, value)?;
7859        if ready {
7860            return Ok(value);
7861        }
7862        self.iterator_result(value, done)
7863    }
7864
7865    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7866    ///
7867    /// The body is the same coroutine a sync generator runs; what changes is that an
7868    /// `await` inside it has to settle before the method can answer, so the step is
7869    /// driven off the job queue rather than returning inline.
7870    pub fn resume_async_generator(
7871        &mut self,
7872        generator: &Gc<JsObject>,
7873        kind: ResumeKind,
7874        value: Value,
7875    ) -> JsResult<Value> {
7876        let promise = self.new_promise();
7877        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7878        // that order, and the second value must reach the *second* `yield`.
7879        let idle = generator.with_mut(|data| match &mut data.kind {
7880            ObjectKind::Generator(state) => {
7881                state.requests.push_back(AsyncRequest {
7882                    kind,
7883                    value,
7884                    promise: promise.clone(),
7885                });
7886                !state.async_busy
7887            }
7888            _ => false,
7889        });
7890        if idle {
7891            self.next_async_request(generator)?;
7892        }
7893        Ok(Value::Object(promise))
7894    }
7895
7896    /// Serve the front queued request, if the generator is free to run one.
7897    ///
7898    /// A finished generator answers from the queue without running anything:
7899    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7900    /// first, and `throw(e)` rejects.
7901    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7902        enum Front {
7903            Idle,
7904            Run(ResumeKind, Value, Gc<JsObject>),
7905            Finished(ResumeKind, Value, Gc<JsObject>),
7906        }
7907        let front = generator.with_mut(|data| match &mut data.kind {
7908            ObjectKind::Generator(state) => {
7909                let Some(request) = state.requests.front() else {
7910                    return Front::Idle;
7911                };
7912                // Busy means a request is still in flight — awaiting inside the body, not
7913                // finished. Serving another now would interleave two requests.
7914                if state.async_busy && state.phase != GeneratorPhase::Completed {
7915                    return Front::Idle;
7916                }
7917                let kind = request.kind;
7918                let value = request.value.clone();
7919                let promise = request.promise.clone();
7920                state.async_busy = true;
7921                if state.phase == GeneratorPhase::Completed {
7922                    Front::Finished(kind, value, promise)
7923                } else {
7924                    Front::Run(kind, value, promise)
7925                }
7926            }
7927            _ => Front::Idle,
7928        });
7929        match front {
7930            Front::Idle => Ok(()),
7931            Front::Run(kind, value, promise) => {
7932                self.step_async_generator(generator, &promise, kind, value)
7933            }
7934            Front::Finished(kind, value, promise) => match kind {
7935                ResumeKind::Throw => {
7936                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7937                }
7938                ResumeKind::Next | ResumeKind::Start => {
7939                    let result = self.iterator_result(Value::Undefined, true)?;
7940                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7941                }
7942                ResumeKind::Return => {
7943                    // `js_async_generator_completed_return`: the value is awaited before it
7944                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7945                    // finished generator answers `1`, not a promise.
7946                    let resolved = match self.promise_resolve_value(value) {
7947                        Ok(resolved) => resolved,
7948                        Err(Signal::Throw(reason)) => {
7949                            return self.settle_async_request(
7950                                generator,
7951                                &promise,
7952                                AsyncOutcome::Error(reason),
7953                            );
7954                        }
7955                        Err(other) => return Err(other),
7956                    };
7957                    let done = JsObject::function(
7958                        self.heap,
7959                        Some(self.realm.function_proto.clone()),
7960                        Callable::CompletedReturn {
7961                            generator: generator.clone(),
7962                            promise: promise.clone(),
7963                            rejected: false,
7964                        },
7965                    );
7966                    let failed = JsObject::function(
7967                        self.heap,
7968                        Some(self.realm.function_proto.clone()),
7969                        Callable::CompletedReturn {
7970                            generator: generator.clone(),
7971                            promise: promise.clone(),
7972                            rejected: true,
7973                        },
7974                    );
7975                    let Value::Object(resolved) = resolved else {
7976                        return self.settle_async_request(
7977                            generator,
7978                            &promise,
7979                            AsyncOutcome::Error(Value::Undefined),
7980                        );
7981                    };
7982                    self.perform_then(
7983                        &resolved,
7984                        Some(Value::Object(done)),
7985                        Some(Value::Object(failed)),
7986                    )?;
7987                    Ok(())
7988                }
7989            },
7990        }
7991    }
7992
7993    /// Settle the front request and start the next one.
7994    ///
7995    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7996    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7997    /// generator would strand every later request.
7998    fn settle_async_request(
7999        &mut self,
8000        generator: &Gc<JsObject>,
8001        promise: &Gc<JsObject>,
8002        outcome: AsyncOutcome,
8003    ) -> JsResult<()> {
8004        let settled = generator.with_mut(|data| match &mut data.kind {
8005            ObjectKind::Generator(state) => {
8006                let front = state.requests.front();
8007                debug_assert!(
8008                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8009                    "a request settled outside its turn"
8010                );
8011                state.requests.pop_front();
8012                state.async_busy = false;
8013                true
8014            }
8015            _ => false,
8016        });
8017        if settled {
8018            match outcome {
8019                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8020                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8021            }
8022        }
8023        self.next_async_request(generator)
8024    }
8025
8026    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8027    ///
8028    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8029    /// disposer runs **synchronously** — the reference starts it before returning, which
8030    /// a test can observe by logging after the call — and the rest follow once their
8031    /// predecessor settles.
8032    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8033        let promise = self.new_promise();
8034        let mut pairs = Vec::with_capacity(resources.len());
8035        for (value, method) in resources {
8036            let pair = self.new_array(vec![value, method]);
8037            pairs.push(Value::Object(pair));
8038        }
8039        let remaining = self.new_array(pairs);
8040        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
8041        Ok(Value::Object(promise))
8042    }
8043
8044    /// One link of the `disposeAsync` chain.
8045    ///
8046    /// Loops while the disposers finish synchronously, and parks on the first thenable it
8047    /// meets — pushing itself back in as the continuation, with the accumulated error
8048    /// carried along so a later failure can still be folded into the `SuppressedError`.
8049    fn dispose_step(
8050        &mut self,
8051        remaining: &Gc<JsObject>,
8052        promise: &Gc<JsObject>,
8053        mut error: Value,
8054    ) -> JsResult<()> {
8055        loop {
8056            let length = remaining.array_length().unwrap_or(0);
8057            if length == 0 {
8058                if matches!(error, Value::Uninitialized) {
8059                    self.fulfill_promise(promise, Value::Undefined);
8060                } else {
8061                    self.reject_promise(promise, error);
8062                }
8063                return Ok(());
8064            }
8065            let Some(Value::Object(pair)) = remaining
8066                .array_get(length - 1)
8067                .filter(|v| !matches!(v, Value::Hole))
8068            else {
8069                remaining.array_truncate(self.heap, length - 1);
8070                continue;
8071            };
8072            remaining.array_truncate(self.heap, length - 1);
8073            let value = pair.array_get(0).unwrap_or(Value::Undefined);
8074            let Some(Value::Object(method)) = pair.array_get(1) else {
8075                continue;
8076            };
8077            if !method.is_callable() {
8078                continue;
8079            }
8080            match self.call_value(Value::Object(method), value, Vec::new()) {
8081                Ok(result) => {
8082                    if !self.is_thenable(&result)? {
8083                        // Finished synchronously; the next disposer is the next iteration.
8084                        continue;
8085                    }
8086                    let awaited = match self.promise_resolve_value(result) {
8087                        Ok(awaited) => awaited,
8088                        Err(Signal::Throw(reason)) => {
8089                            self.reject_promise(promise, reason);
8090                            return Ok(());
8091                        }
8092                        Err(other) => return Err(other),
8093                    };
8094                    let Value::Object(awaited) = awaited else {
8095                        continue;
8096                    };
8097                    let ok = JsObject::function(
8098                        self.heap,
8099                        Some(self.realm.function_proto.clone()),
8100                        Callable::DisposeStep {
8101                            remaining: remaining.clone(),
8102                            promise: promise.clone(),
8103                            error: error.clone(),
8104                            rejected: false,
8105                        },
8106                    );
8107                    let failed = JsObject::function(
8108                        self.heap,
8109                        Some(self.realm.function_proto.clone()),
8110                        Callable::DisposeStep {
8111                            remaining: remaining.clone(),
8112                            promise: promise.clone(),
8113                            error,
8114                            rejected: true,
8115                        },
8116                    );
8117                    self.perform_then(
8118                        &awaited,
8119                        Some(Value::Object(ok)),
8120                        Some(Value::Object(failed)),
8121                    )?;
8122                    return Ok(());
8123                }
8124                Err(Signal::Throw(thrown)) => {
8125                    error = self.merge_dispose_error(thrown, error);
8126                }
8127                Err(other) => return Err(other),
8128            }
8129        }
8130    }
8131
8132    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8133    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8134        let Value::Object(object) = value else {
8135            return Ok(false);
8136        };
8137        Ok(matches!(
8138            self.get_property(object, "then")?,
8139            Some(Value::Object(then)) if then.is_callable()
8140        ))
8141    }
8142
8143    /// One step of an async generator, settling `promise` with an `{value, done}` result.
8144    fn step_async_generator(
8145        &mut self,
8146        generator: &Gc<JsObject>,
8147        promise: &Gc<JsObject>,
8148        kind: ResumeKind,
8149        value: Value,
8150    ) -> JsResult<()> {
8151        let stepped = self.resume_generator_detailed(generator, kind, value);
8152        let (value, done, ready, reason) = match stepped {
8153            Ok(stepped) => stepped,
8154            Err(Signal::Throw(reason)) => {
8155                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8156            }
8157            Err(other) => return Err(other),
8158        };
8159        // Only an `await` has to wait before the method can answer.
8160        if !done && reason == Some(SuspendKind::Await) {
8161            let awaited = match self.promise_resolve_value(value) {
8162                Ok(awaited) => awaited,
8163                Err(Signal::Throw(reason)) => {
8164                    return self.settle_async_request(
8165                        generator,
8166                        promise,
8167                        AsyncOutcome::Error(reason),
8168                    );
8169                }
8170                Err(other) => return Err(other),
8171            };
8172            let Value::Object(awaited) = awaited else {
8173                return Ok(());
8174            };
8175            let resumed = JsObject::function(
8176                self.heap,
8177                Some(self.realm.function_proto.clone()),
8178                Callable::GeneratorResume {
8179                    generator: generator.clone(),
8180                    promise: promise.clone(),
8181                    kind: ResumeKind::Next,
8182                },
8183            );
8184            let raised = JsObject::function(
8185                self.heap,
8186                Some(self.realm.function_proto.clone()),
8187                Callable::GeneratorResume {
8188                    generator: generator.clone(),
8189                    promise: promise.clone(),
8190                    kind: ResumeKind::Throw,
8191                },
8192            );
8193            self.perform_then(
8194                &awaited,
8195                Some(Value::Object(resumed)),
8196                Some(Value::Object(raised)),
8197            )?;
8198            return Ok(());
8199        }
8200        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8201        // completes it — both arrive as the settled value rather than as the promise
8202        // object. A plain value skips the round trip, which is also what keeps `yield 1`
8203        // from costing an extra tick.
8204        let awaits_value = self.is_thenable(&value)?;
8205        if awaits_value {
8206            let awaited = match self.promise_resolve_value(value) {
8207                Ok(awaited) => awaited,
8208                Err(Signal::Throw(reason)) => {
8209                    return self.settle_async_request(
8210                        generator,
8211                        promise,
8212                        AsyncOutcome::Error(reason),
8213                    );
8214                }
8215                Err(other) => return Err(other),
8216            };
8217            let Value::Object(awaited) = awaited else {
8218                return Ok(());
8219            };
8220            // A rejected yield throws *at the yield* inside the body, so the rejection
8221            // resumes the generator rather than the method's promise.
8222            let answer = JsObject::function(
8223                self.heap,
8224                Some(self.realm.function_proto.clone()),
8225                Callable::YieldResult {
8226                    generator: generator.clone(),
8227                    promise: promise.clone(),
8228                    done,
8229                },
8230            );
8231            let raise = JsObject::function(
8232                self.heap,
8233                Some(self.realm.function_proto.clone()),
8234                Callable::GeneratorResume {
8235                    generator: generator.clone(),
8236                    promise: promise.clone(),
8237                    kind: ResumeKind::Throw,
8238                },
8239            );
8240            self.perform_then(
8241                &awaited,
8242                Some(Value::Object(answer)),
8243                Some(Value::Object(raise)),
8244            )?;
8245            return Ok(());
8246        }
8247        let result = if ready {
8248            // `yield*` handed back the inner iterator's own result object.
8249            value
8250        } else {
8251            self.iterator_result(value, done)?
8252        };
8253        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8254    }
8255
8256    /// The `{value, done}` object an iterator method answers with.
8257    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8258        let result = self.new_object(Some(self.realm.object_proto.clone()));
8259        result.define_data("value", value);
8260        result.define_data("done", Value::Bool(done));
8261        Ok(Value::Object(result))
8262    }
8263
8264    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8265    fn step_generator(
8266        &mut self,
8267        state: &mut GeneratorState,
8268        kind: ResumeKind,
8269        value: Value,
8270    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8271        match state.phase {
8272            GeneratorPhase::Executing => {
8273                return Err(self.type_error("cannot invoke a running generator"));
8274            }
8275            GeneratorPhase::Completed => {
8276                // A finished generator answers every resumption without running.
8277                return Ok(match kind {
8278                    ResumeKind::Throw => return Err(Signal::Throw(value)),
8279                    ResumeKind::Return => (value, true, false, None),
8280                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8281                });
8282            }
8283            GeneratorPhase::SuspendedStart => {
8284                if kind != ResumeKind::Next && kind != ResumeKind::Start {
8285                    // The body never started, so there is nothing to unwind or return
8286                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8287                    state.frame = None;
8288                    state.phase = GeneratorPhase::Completed;
8289                    return Ok(match kind {
8290                        ResumeKind::Throw => return Err(Signal::Throw(value)),
8291                        _ => (value, true, false, None),
8292                    });
8293                }
8294            }
8295            GeneratorPhase::SuspendedYield => {}
8296        }
8297
8298        let Some(mut frame) = state.frame.take() else {
8299            return Ok((Value::Undefined, true, false, None));
8300        };
8301        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
8302        // number that says which method resumed it; the emitted `if_false` branches on
8303        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
8304        let mut raised = None;
8305        match kind {
8306            ResumeKind::Next | ResumeKind::Start => {
8307                if state.phase == GeneratorPhase::SuspendedYield {
8308                    frame.stack.push(value);
8309                    // An `await` resumes with its value alone; only a `yield` gets the
8310                    // magic number that says which of `next`/`return` resumed it.
8311                    if !state.parked_on_await {
8312                        frame.stack.push(Value::Int(RESUME_NEXT));
8313                    }
8314                }
8315            }
8316            ResumeKind::Return => {
8317                // A `return` on a not-yet-started generator is handled above, so this is
8318                // always a real resumption.
8319                frame.stack.push(value);
8320                frame.stack.push(Value::Int(RESUME_RETURN));
8321            }
8322            ResumeKind::Throw => {
8323                // At a `yield*` the exception is *data* for the delegation: the compiled
8324                // code resumes with the value and magic `2` and calls the inner iterator's
8325                // `throw`. Everywhere else it is raised at the suspension point, so the
8326                // body's own handler sees it.
8327                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
8328                    frame.stack.push(value);
8329                    frame.stack.push(Value::Int(RESUME_THROW));
8330                } else {
8331                    raised = Some(value);
8332                }
8333            }
8334        }
8335        state.phase = GeneratorPhase::Executing;
8336
8337        let depth = self.frames.len();
8338        self.frames.push(frame);
8339        // A `throw` unwinds from where the frame parked, exactly as if the exception had
8340        // happened at the `yield`.
8341        if let Some(exception) = raised {
8342            if self.catch_here(exception.clone()).is_none() {
8343                self.pop_frame();
8344                state.phase = GeneratorPhase::Completed;
8345                return Err(Signal::Throw(exception));
8346            }
8347        }
8348
8349        // Only the generator's *own* frame ends the generator. The body may call ordinary
8350        // functions, and those push frames of their own: a `Step::Return` from one of them
8351        // is a nested call finishing, not the generator completing. Miscounting that is
8352        // silent — the generator reports the callee's value as its own result and marks
8353        // itself done — so the depth comparison is load-bearing, not defensive.
8354        let own_frame = depth + 1;
8355        loop {
8356            match self.step() {
8357                Ok(Step::Continue) => {}
8358                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
8359                    let mut frame = self.frames.pop().expect("a frame is live");
8360                    // `yield` left the value on the stack; `initial_yield` left nothing.
8361                    let yielded = if reason == SuspendKind::Initial {
8362                        Value::Undefined
8363                    } else {
8364                        frame.stack.pop().unwrap_or(Value::Undefined)
8365                    };
8366                    state.frame = Some(frame);
8367                    state.parked_on_await = reason == SuspendKind::Await;
8368                    state.parked_on_yield_star =
8369                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
8370                    state.phase = if reason == SuspendKind::Initial {
8371                        GeneratorPhase::SuspendedStart
8372                    } else {
8373                        GeneratorPhase::SuspendedYield
8374                    };
8375                    // `yield*` hands the inner iterator's own result object straight
8376                    // back, so the caller sees one `{value, done}` rather than a nested
8377                    // one — which is why the third field says "already a result".
8378                    return Ok((
8379                        yielded,
8380                        false,
8381                        reason == SuspendKind::YieldStar,
8382                        Some(reason),
8383                    ));
8384                }
8385                Ok(Step::Suspend(_)) => {
8386                    // A `yield` in a frame other than the generator's would mean a
8387                    // generator body entered as an ordinary call, which
8388                    // `call_or_push` prevents.
8389                    self.unwind_to(depth);
8390                    state.phase = GeneratorPhase::Completed;
8391                    return Err(Signal::Throw(self.make_error(
8392                        "InternalError",
8393                        "a generator body ran as an ordinary call",
8394                    )));
8395                }
8396                Ok(Step::Return(value)) => {
8397                    self.pop_frame();
8398                    if self.frames.len() > depth {
8399                        // A nested call finished: hand the value back to its caller and
8400                        // keep running the generator body.
8401                        self.frames
8402                            .last_mut()
8403                            .expect("a caller is live")
8404                            .stack
8405                            .push(value);
8406                        continue;
8407                    }
8408                    state.phase = GeneratorPhase::Completed;
8409                    // The reference closes the generator's closure variables here; ours
8410                    // live in cells the frame owned, which the drop below releases.
8411                    return Ok((value, true, false, None));
8412                }
8413                Err(Signal::Throw(exception)) => {
8414                    // The frame that threw gets the first chance to catch, exactly as in
8415                    // the ordinary call loop; a frame above the generator's is popped and
8416                    // the exception carries on down.
8417                    let exception = exception;
8418                    loop {
8419                        if self.frames.len() <= depth {
8420                            // The generator's own frame is gone, so nothing here caught it.
8421                            state.phase = GeneratorPhase::Completed;
8422                            return Err(Signal::Throw(exception));
8423                        }
8424                        if self.catch_here(exception.clone()).is_some() {
8425                            break;
8426                        }
8427                        self.pop_frame();
8428                    }
8429                }
8430                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
8431            }
8432        }
8433    }
8434
8435    /// Pop frames until `depth` are left, keeping their buffers.
8436    fn unwind_to(&mut self, depth: usize) {
8437        while self.frames.len() > depth {
8438            self.pop_frame();
8439        }
8440    }
8441    fn call_or_push(
8442        &mut self,
8443        callee: Value,
8444        this: Value,
8445        args: Vec<Value>,
8446    ) -> JsResult<Option<Value>> {
8447        if let Value::Object(function) = &callee
8448            && let Some((code, env)) = bytecode_of(function)
8449        {
8450            // Calling a generator function does not run anything: it captures the
8451            // arguments in a frame and hands back the generator object.
8452            if code.code.kind.is_generator() {
8453                return self.new_generator(callee, this, args).map(Some);
8454            }
8455            // An async function answers a promise and runs its body as a coroutine, so it
8456            // takes the same path as a plain call into it.
8457            if code.code.kind.is_async() {
8458                return self.new_async_function(callee, this, args).map(Some);
8459            }
8460            self.push_frame(code, env, this, args, callee)?;
8461            return Ok(None);
8462        }
8463        self.call_value(callee, this, args).map(Some)
8464    }
8465
8466    /// `new callee(args)`.
8467    ///
8468    /// A constructor differs from a plain call in three ways: it gets a fresh object
8469    /// as `this` whose prototype is the constructor's `prototype` property, its
8470    /// return value is *replaced* by that object unless it returns an object itself,
8471    /// and a native constructor is expected to initialise the object it is given
8472    /// rather than build one.
8473    pub fn construct(
8474        &mut self,
8475        callee: Value,
8476        new_target: Value,
8477        args: Vec<Value>,
8478    ) -> JsResult<Value> {
8479        // `new` on a bound function constructs its *target*, prepending the arguments
8480        // the bind fixed and ignoring the bound `this` — a bound function is a
8481        // constructor only when its target is one, and `new` always makes a fresh
8482        // object of the target's prototype rather than reusing the bound receiver.
8483        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
8484        // ran the body with `this === null` and threw on `this.x = a`.
8485        let mut callee = callee;
8486        let mut new_target = new_target;
8487        let mut args = args;
8488        loop {
8489            let Some(object) = callee.as_object().cloned() else {
8490                return Err(Signal::Throw(
8491                    self.make_error("TypeError", "not a constructor"),
8492                ));
8493            };
8494            // A proxy of a function constructs through its `construct` trap, and the
8495            // trap's answer is the result directly — no fresh object is made here.
8496            if object.proxy_state().is_some() {
8497                return match self.proxy_construct(&object, args, &new_target)? {
8498                    Some(result) => Ok(result),
8499                    None => Err(Signal::Throw(
8500                        self.make_error("TypeError", "proxy target is not a constructor"),
8501                    )),
8502                };
8503            }
8504            // A generator function has no `[[Construct]]`, and the reference names it in
8505            // the message: `new (function* G(){})()` reports "G is not a constructor".
8506            if object.with(|data| match &data.kind {
8507                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
8508                    code.code.kind.is_generator()
8509                }
8510                _ => false,
8511            }) {
8512                let name = object
8513                    .own_property("name")
8514                    .and_then(|property| property.value)
8515                    .map(|value| value.to_js_string())
8516                    .unwrap_or_default();
8517                return Err(Signal::Throw(
8518                    self.make_error("TypeError", &format!("{name} is not a constructor")),
8519                ));
8520            }
8521            let bound = object.with(|data| match &data.kind {
8522                ObjectKind::Function(Callable::Bound {
8523                    target,
8524                    args: leading,
8525                    ..
8526                }) => Some((target.clone(), leading.clone())),
8527                _ => None,
8528            });
8529            let Some((target, leading)) = bound else {
8530                // Not a bound function, so this object is the callee. §7.2.4
8531                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
8532                // refusals above cover only the built-ins the reference also refuses by
8533                // name. Everything else — a method, an arrow, an async function — has no
8534                // `[[Construct]]` either, and answering "yes" here made
8535                // `new (Array.prototype.map)` build an object instead of throwing.
8536                if !object.is_constructor() {
8537                    let name = object
8538                        .own_property("name")
8539                        .and_then(|property| property.value)
8540                        .map(|value| value.to_js_string())
8541                        .unwrap_or_default();
8542                    return Err(Signal::Throw(
8543                        self.make_error("TypeError", &format!("{name} is not a constructor")),
8544                    ));
8545                }
8546                break;
8547            };
8548            let mut all = leading;
8549            all.extend(args);
8550            args = all;
8551            // A bound function that is its own `new.target` stands in for its target:
8552            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
8553            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
8554            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
8555                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
8556                _ => false,
8557            };
8558            if same_wrapper {
8559                new_target = target.clone();
8560            }
8561            callee = target;
8562        }
8563        let Value::Object(function) = &callee else {
8564            unreachable!("the loop above only breaks on an object");
8565        };
8566        // The fresh object's prototype comes from `new.target`, not from the callee: a
8567        // derived constructor reaches here through `super()`, and the instance must be a
8568        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
8569        // an object inheriting `D.prototype` rather than `C.prototype`.
8570        let prototype_source = match new_target.as_object() {
8571            Some(target) => target.clone(),
8572            None => function.clone(),
8573        };
8574        // A native constructor builds its own instance, through `new_ctor_instance`, once it
8575        // has validated its arguments. Pre-building one here would read
8576        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
8577        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
8578        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
8579        let is_native = function.native_creates_own_instance();
8580        let this = if is_native {
8581            Value::Undefined
8582        } else {
8583            let prototype = self.get_property(&prototype_source, "prototype")?;
8584            let prototype = match prototype {
8585                Some(Value::Object(proto)) => Some(proto),
8586                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
8587                // object, the answer is the realm's *intrinsic* prototype for this
8588                // constructor, not `%Object.prototype%`.
8589                _ => {
8590                    let fallback = self.get_property(function, "prototype")?;
8591                    match fallback {
8592                        Some(Value::Object(proto)) => Some(proto),
8593                        _ => Some(self.realm.object_proto.clone()),
8594                    }
8595                }
8596            };
8597            Value::Object(self.new_object(prototype))
8598        };
8599        // `new.target` inside the body is the constructor that was written, so a bound
8600        // function's target sees itself rather than the bound wrapper.
8601        //
8602        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
8603        // `?`, so assigning `None` after the call would be skipped and the failed
8604        // `new.target` would stay visible to every later native call. The symptom was a
8605        // native constructor refusing a plain call — `var s = Symbol(); new
8606        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
8607        // "FinalizationRegistry is not a constructor".
8608        let outer_new_target = self.pending_new_target.replace(new_target);
8609        let result = self.call_value(callee, this.clone(), args);
8610        self.pending_new_target = outer_new_target;
8611        let result = result?;
8612        // A constructor that returns an object overrides `this`; any other return
8613        // value (including `undefined`) is ignored.
8614        Ok(match result {
8615            Value::Object(_) => result,
8616            _ => this,
8617        })
8618    }
8619
8620    /// `new.target` for the call currently being made.
8621    ///
8622    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
8623    /// it as `this`), but a *host* constructor that builds its own instance is handed
8624    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
8625    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
8626    /// it here.
8627    ///
8628    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
8629    /// receives for a plain call.
8630    pub fn current_new_target(&self) -> Value {
8631        self.pending_new_target.clone().unwrap_or(Value::Undefined)
8632    }
8633
8634    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
8635    ///
8636    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
8637    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
8638    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
8639        let constructor = self.realm.errors.get("AggregateError").cloned();
8640        let Some(constructor) = constructor else {
8641            return self.make_error("AggregateError", message);
8642        };
8643        let list = self.new_array(errors);
8644        match self.construct(
8645            Value::Object(constructor.clone()),
8646            Value::Object(constructor),
8647            vec![Value::Object(list), self.string(message)],
8648        ) {
8649            Ok(value) => value,
8650            // A user could have replaced `AggregateError` with something that throws; the
8651            // engine still owes the caller a rejection, so it falls back rather than
8652            // turning `Promise.any`'s rejection into a throw.
8653            Err(_) => self.make_error("AggregateError", message),
8654        }
8655    }
8656
8657    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
8658    ///
8659    /// The error classes themselves arrive with the builtins milestone; what
8660    /// matters here is that the thrown value stringifies the way a script printing
8661    /// the caught value expects.
8662    ///
8663    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
8664    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
8665    /// rely on when they print a caught value.
8666    pub fn make_error(&self, name: &str, message: &str) -> Value {
8667        let proto = self
8668            .realm
8669            .errors
8670            .get(name)
8671            .map(|constructor| self.prototype_of(constructor))
8672            .unwrap_or_else(|| self.realm.error_proto.clone());
8673        let error = self.new_object(Some(proto));
8674        // `name` and `message` are own properties of the instance, which is what
8675        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
8676        // `Error`.
8677        error.define(
8678            "name",
8679            Property::with_attributes(self.string(name), true, false),
8680        );
8681        error.define(
8682            "message",
8683            Property::with_attributes(self.string(message), true, false),
8684        );
8685        // The internal class, which is what tells a printer this is an error rather than a
8686        // plain object with `name` and `message` properties. The constructor path sets it
8687        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
8688        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
8689        // literally `"Error"` in both places — the *name* is read from `name`, which is why
8690        // a `RangeError` still prints as `RangeError`.
8691        self.internal_set(&error, "_class", self.string("Error"));
8692        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
8693        // answered `false` from `Error.isError` while a constructed one answered `true`,
8694        // because only the constructor set the slot. The reference answers `true` for both
8695        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
8696        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
8697        // tests `typeof stack === "string"` to decide on a trailing newline, so every
8698        // engine-thrown error lost its blank line.
8699        self.internal_set(&error, "_error_data", Value::Bool(true));
8700        // The trace is captured where the error is *made*, which is where the reference
8701        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
8702        // way out, so a caught engine error already has its stack even if the handler
8703        // never rethrows it.
8704        self.add_stack(&error);
8705        Value::Object(error)
8706    }
8707
8708    /// Give an error object its `stack` property, from the current frame stack.
8709    ///
8710    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
8711    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
8712    /// `stack` a script set, is not rewritten.
8713    pub fn add_stack(&self, object: &Gc<JsObject>) {
8714        self.add_stack_skipping(object, 0);
8715    }
8716
8717    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
8718    ///
8719    /// An `Error` constructor passes 1: the reference builds those traces with
8720    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
8721    /// constructor itself, while a `RangeError` raised inside `toISOString` does
8722    /// report `at toISOString (native)`.
8723    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
8724        if object.has_own("stack") {
8725            return;
8726        }
8727        // The trace is *captured* here but not installed as a property: `stack` is an
8728        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
8729        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
8730        // is kept in a hidden slot and the getter materialises it on first read.
8731        //
8732        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
8733        // shows it — this is the same discipline `_error_data` and `_class` follow.
8734        let trace = self.stack_trace_skipping(skip);
8735        let text = self.string(trace);
8736        self.internal_set(object, "_stack_trace", text);
8737    }
8738
8739    /// The function object currently being called, if any.
8740    ///
8741    /// A native function is a bare `fn` pointer, so it cannot capture which class
8742    /// it belongs to; it reads that from the callee instead. This is also what a
8743    /// stack trace would use.
8744    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
8745        match &self.frames.last()?.callee {
8746            Value::Object(object) => Some(object.clone()),
8747            _ => None,
8748        }
8749    }
8750
8751    /// The `prototype` property of a constructor, falling back to
8752    /// `Object.prototype` for anything that is not shaped like one.
8753    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
8754        constructor
8755            .own_property("prototype")
8756            .and_then(|property| property.value)
8757            .and_then(|value| value.as_object().cloned())
8758            .unwrap_or_else(|| self.realm.object_proto.clone())
8759    }
8760
8761    /// Throw a `TypeError` carrying `message`.
8762    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
8763        Signal::Throw(self.make_error("TypeError", message.as_ref()))
8764    }
8765
8766    /// Throw a `RangeError` carrying `message`.
8767    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
8768        Signal::Throw(self.make_error("RangeError", message.as_ref()))
8769    }
8770
8771    /// The `ReferenceError` a read of an uninitialised binding raises.
8772    /// The name of the binding `slot` refers to, for an error message.
8773    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
8774        match kind {
8775            VarSlot::Loc => self
8776                .frame()
8777                .code
8778                .code
8779                .vars
8780                .get(slot)
8781                .map(|v| v.name.clone()),
8782            VarSlot::Closure => self
8783                .frame()
8784                .code
8785                .code
8786                .closure_vars
8787                .get(slot)
8788                .map(|c| c.name.clone()),
8789        }
8790        .unwrap_or_default()
8791    }
8792
8793    /// Whether `slot` names a `const` binding, which rejects every store after its
8794    /// initialiser.
8795    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8796        match kind {
8797            VarSlot::Loc => self
8798                .frame()
8799                .code
8800                .code
8801                .vars
8802                .get(slot)
8803                .is_some_and(|v| v.is_const),
8804            VarSlot::Closure => self
8805                .frame()
8806                .code
8807                .code
8808                .closure_vars
8809                .get(slot)
8810                .is_some_and(|c| c.is_const),
8811        }
8812    }
8813
8814    /// The `TypeError` a store to a `const` binding raises.
8815    ///
8816    /// `const` is enforced here rather than at compile time because the binding can be
8817    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8818    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8819    /// both halves of what "checked store" means: the dead zone is over, and the
8820    /// binding is writable.
8821    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8822        let name = self.binding_name(slot, kind);
8823        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8824    }
8825
8826    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8827        let name = match kind {
8828            VarSlot::Loc => self
8829                .frame()
8830                .code
8831                .code
8832                .vars
8833                .get(slot)
8834                .map(|v| v.name.clone()),
8835            VarSlot::Closure => self
8836                .frame()
8837                .code
8838                .code
8839                .closure_vars
8840                .get(slot)
8841                .map(|c| c.name.clone()),
8842        }
8843        .unwrap_or_default();
8844        Signal::Throw(self.make_error(
8845            "ReferenceError",
8846            &format!("cannot access '{name}' before initialization"),
8847        ))
8848    }
8849
8850    fn throw_reference(&self, name: &str) -> Signal {
8851        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8852    }
8853
8854    // -- the instruction loop -----------------------------------------------
8855
8856    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8857    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8858    // measured at 16% of a tight arithmetic loop's total time.
8859    #[inline(always)]
8860    fn step(&mut self) -> JsResult<Step> {
8861        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8862        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8863        // borrow lives across the boundary; nothing is cloned.
8864        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8865        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8866        // write, and once more inside the handler), and each is a bounds check plus an
8867        // `Option` unwrap — on the one path every instruction takes.
8868        let Some((insn, next)) = ({
8869            let frame = self
8870                .frames
8871                .last_mut()
8872                .expect("step() is only called with a live frame");
8873            // Past the last instruction is a normal return: the compiler ends a function
8874            // with `return`, and a jump to the end of a block lands here.
8875            let insn = frame.insns().get(frame.pc).copied();
8876            match insn {
8877                None => None,
8878                Some(insn) => {
8879                    // A fused record stands for the next few instructions, so the next
8880                    // `pc` is its width ahead — the instructions it replaces are never
8881                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8882                    // an offset because the line table is keyed by bytes.
8883                    frame.at = insn.offset as usize;
8884                    frame.pc += insn.width();
8885                    Some((insn, frame.pc))
8886                }
8887            }
8888        }) else {
8889            return Ok(Step::Return(Value::Undefined));
8890        };
8891        self.check_memory()?;
8892        self.check_interrupt()?;
8893        if insn.fused == crate::insn::Fused::None {
8894            self.execute_instruction(insn.op, insn.a, insn.b, next)
8895        } else {
8896            self.execute_fused(insn)
8897        }
8898    }
8899
8900    /// Run a fused instruction: several bytecode instructions in one dispatch.
8901    ///
8902    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8903    /// it cannot throw and cannot allocate — and anything else falls back to the real
8904    /// instructions, in their real order, so an exception leaves the operand stack
8905    /// exactly as it would have been.
8906    #[inline]
8907    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8908        use crate::insn::Fused;
8909        let slot = insn.a as usize;
8910        match insn.fused {
8911            // `x = k`: `push k; put_loc x`.
8912            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8913            // `x += k`: `get_loc x; push k; add; put_loc x`.
8914            Fused::AddImmLoc => {
8915                let delta = insn.b as i32;
8916                match self.get_loc(slot) {
8917                    Value::Int(left) => {
8918                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8919                        // that built two `Value`s, called a function, and matched on them
8920                        // again to reach this same `checked_add`. It is the innermost
8921                        // operation of every accumulator in every program.
8922                        let answer = match left.checked_add(delta) {
8923                            Some(sum) => Value::Int(sum),
8924                            None => Value::Float(left as f64 + delta as f64),
8925                        };
8926                        self.put_loc(slot, answer);
8927                    }
8928                    other => {
8929                        self.push(other);
8930                        self.push(Value::Int(delta));
8931                        self.binary_add()?;
8932                        let value = self.pop();
8933                        self.put_loc(slot, value);
8934                    }
8935                }
8936            }
8937            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8938            Fused::AddAtomLoc => {
8939                let text = self.atom_wtf8(insn.b as usize);
8940                let right = self.string_wtf8(text);
8941                self.add_into_loc(slot, right)?;
8942            }
8943            Fused::AddLocLoc => {
8944                let source = (insn.a & 0xFFFF) as usize;
8945                let target = (insn.a >> 16) as usize;
8946                let right = self.get_loc(source);
8947                self.add_into_loc(target, right)?;
8948            }
8949            Fused::AddArgLoc => {
8950                let source = (insn.a & 0xFFFF) as usize;
8951                let target = (insn.a >> 16) as usize;
8952                let right = self.get_arg(source);
8953                self.add_into_loc(target, right)?;
8954            }
8955            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8956            Fused::PostIncLoc => match self.get_loc(slot) {
8957                Value::Int(left) => {
8958                    let answer = match left.checked_add(1) {
8959                        Some(sum) => Value::Int(sum),
8960                        None => Value::Float(left as f64 + 1.0),
8961                    };
8962                    self.put_loc(slot, answer);
8963                }
8964                other => {
8965                    self.push(other);
8966                    let raw = self.pop();
8967                    let (old, updated) = self.advance_numeric(raw, true)?;
8968                    self.push(old);
8969                    self.push(updated);
8970                    let value = self.pop();
8971                    self.put_loc(slot, value);
8972                    self.pop();
8973                }
8974            },
8975            // `if (!(x < arg)) goto target`: a loop header.
8976            //
8977            // The comparison is computed rather than replayed on the operand stack. That
8978            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8979            // that throws: the effects happen in the same order, and a handler truncates
8980            // the stack down to its marker, so the intermediate values are unobservable.
8981            Fused::LtLocArgJump => {
8982                let loc = (insn.a >> 16) as usize;
8983                let arg = (insn.a & 0xFFFF) as usize;
8984                let left = self.get_loc(loc);
8985                let right = self.get_arg(arg);
8986                let taken = match (&left, &right) {
8987                    (Value::Int(left), Value::Int(right)) => !(left < right),
8988                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8989                };
8990                if taken {
8991                    self.frame_mut().pc = insn.b as usize;
8992                }
8993            }
8994            // `i < k` in a loop header, where `k` is an integer literal.
8995            Fused::LtLocImmJump => {
8996                let left = self.get_loc(insn.a as usize);
8997                let right = Value::Int(insn.imm as i32);
8998                let taken = match &left {
8999                    Value::Int(left) => !(*left < insn.imm as i32),
9000                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9001                };
9002                if taken {
9003                    self.frame_mut().pc = insn.b as usize;
9004                }
9005            }
9006            Fused::None => unreachable!("only called for a fused record"),
9007        }
9008        Ok(Step::Continue)
9009    }
9010
9011    /// Run records that cannot call script, cannot throw and cannot change frames.
9012    ///
9013    /// Returns `Some(value)` when the function ran off the end of its instructions (a
9014    /// normal return), and `None` when it stopped in front of an instruction the slow path
9015    /// has to handle — `pc` is written back either way, so `step` resumes at the right
9016    /// place.
9017    ///
9018    /// **The invariant is the whole point.** Every arm here is restricted to work that
9019    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9020    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9021    /// that the memory limit has to see. An opcode whose operands turn out to need any of
9022    /// that **stops the loop** instead of trying, so the slow path gets the instruction
9023    /// untouched and with its operands still on the stack. That is why the fallback is a
9024    /// `break` and not a duplicated slow arm: a second implementation of the same
9025    /// semantics is how a wrong answer gets in with no test noticing.
9026    ///
9027    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9028    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9029    fn run_fast(&mut self) -> JsResult<Option<Value>> {
9030        use crate::insn::Fused;
9031        // The outer loop exists only so a `Call` can come back through here: once a
9032        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9033        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9034        // frame. Re-entering re-reads both from whichever frame is now on top. Every
9035        // other exit from the inner loop returns, so this costs one loop per call.
9036        'outer: loop {
9037            // One reference-count bump per *slow* instruction (a call, an allocation, a
9038            // property access), never one per instruction — that distinction is worth
9039            // two orders of magnitude and was measured as such.
9040            let (code, mut pc) = {
9041                let frame = self.frame();
9042                (frame.code.clone(), frame.pc)
9043            };
9044            let insns = &code.insns;
9045            loop {
9046                let Some(insn) = insns.get(pc).copied() else {
9047                    self.frame_mut().pc = pc;
9048                    return Ok(Some(Value::Undefined));
9049                };
9050                match insn.fused {
9051                    // `x = k`
9052                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9053                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9054                    // object — stops the loop so `binary_add` can decide.
9055                    Fused::AddImmLoc => {
9056                        let slot = insn.a as usize;
9057                        let delta = insn.b as i32;
9058                        let Value::Int(left) = self.get_loc(slot) else {
9059                            return Ok(self.stop(pc));
9060                        };
9061                        let sum = match left.checked_add(delta) {
9062                            Some(sum) => Value::Int(sum),
9063                            None => Value::Float(left as f64 + delta as f64),
9064                        };
9065                        self.put_loc(slot, sum);
9066                    }
9067                    // `x += "literal"` / `x += y`: the operand is a string, so the append
9068                    // either allocates one or grows one. Both are the slow path's business;
9069                    // the fusion's job is only to make the *slot* the sole owner, which is what
9070                    // `execute_fused` needs and what `get_loc` alone destroys.
9071                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9072                        return Ok(self.stop(pc));
9073                    }
9074                    // `x++` on an integer, old value dropped.
9075                    Fused::PostIncLoc => {
9076                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9077                        // value is read in place and overwritten in place, so the reference
9078                        // count it held is released by the same assignment that stores the
9079                        // new one. `get_loc` plus `put_loc` did two borrows, two table
9080                        // lookups and a clone, and this arm is the whole body of a counting
9081                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9082                        let slot = insn.a as usize;
9083                        let frame = self.frames.last_mut().expect("a frame is live");
9084                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9085                        let target = if cell < 0 {
9086                            frame.locals.get_mut(slot)
9087                        } else {
9088                            None
9089                        };
9090                        let Some(target) = target else {
9091                            return Ok(self.stop(pc));
9092                        };
9093                        let Value::Int(left) = *target else {
9094                            return Ok(self.stop(pc));
9095                        };
9096                        *target = match left.checked_add(1) {
9097                            Some(sum) => Value::Int(sum),
9098                            None => Value::Float(left as f64 + 1.0),
9099                        };
9100                    }
9101                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
9102                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9103                    // bound stayed small integers.
9104                    Fused::LtLocArgJump => {
9105                        let loc = (insn.a >> 16) as usize;
9106                        let arg = (insn.a & 0xFFFF) as usize;
9107                        // One borrow for both slots: this arm *is* the whole loop of a
9108                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
9109                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
9110                        // `dispatch:empty-loop`.
9111                        let (left, right) = {
9112                            let frame = self.frame();
9113                            (frame.read_loc(loc), frame.read_arg(arg))
9114                        };
9115                        // Heavily measured: the bound is very often a `Float` even when the
9116                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9117                        // `JSON.parse` or a division is one — so requiring both sides to be
9118                        // `Int` sent every iteration of those loops down the slow path. The
9119                        // comparison below is the same one `relational` makes for two numbers.
9120                        if !is_number(&left) || !is_number(&right) {
9121                            return Ok(self.stop(pc));
9122                        }
9123                        // `if_false` branches on the comparison being false, which is **not**
9124                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9125                        // `>=` is also false and would keep it running forever. Clippy wants the
9126                        // negation folded; that would be a wrong answer.
9127                        let ordered = left.to_number() < right.to_number();
9128                        let take_branch = !ordered;
9129                        if take_branch {
9130                            pc = insn.b as usize;
9131                            continue;
9132                        }
9133                    }
9134                    // The same header with a literal bound: `if (!(x < k)) goto target`.
9135                    // The bound is an immediate, so only the counter needs a type test.
9136                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
9137                    Fused::LtLocImmJump => {
9138                        let left = self.get_loc(insn.a as usize);
9139                        if !is_number(&left) {
9140                            return Ok(self.stop(pc));
9141                        }
9142                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9143                        if take_branch {
9144                            pc = insn.b as usize;
9145                            continue;
9146                        }
9147                    }
9148                    Fused::None => match insn.op {
9149                        // -- branches ---------------------------------------------------
9150                        // A jump is an assignment now, because the target is an instruction
9151                        // index. No arithmetic, no resolution table.
9152                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9153                            let target = insn.a as usize;
9154                            // A **back-edge** is a loop, and it is the only place an
9155                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
9156                            // to a jump to itself and never leaves this loop, so the
9157                            // per-instruction checks in `step` never run. That is exactly the
9158                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
9159                            // nothing to a `for(;;){}` until it did, which is what
9160                            // `tests/c/embed.c` is for.
9161                            //
9162                            // Polling here rather than on every instruction in this loop is
9163                            // also the reference's choice (`OP_goto` calls
9164                            // `js_poll_interrupts`), and it costs one compare per branch
9165                            // instead of one decrement per instruction.
9166                            if target <= pc {
9167                                self.frame_mut().pc = target;
9168                                self.check_memory()?;
9169                                self.check_interrupt()?;
9170                            }
9171                            pc = target;
9172                            continue;
9173                        }
9174                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9175                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9176                            let taken = self.pop().to_boolean();
9177                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9178                            if taken == want {
9179                                pc = insn.a as usize;
9180                                continue;
9181                            }
9182                        }
9183                        // -- slot access -------------------------------------------------
9184                        // A load's slot is already an operand (see `insn::implicit_operand`);
9185                        // a captured one goes through its cell, which runs no script.
9186                        Opcode::GetLoc
9187                        | Opcode::GetLoc8
9188                        | Opcode::GetLoc0
9189                        | Opcode::GetLoc1
9190                        | Opcode::GetLoc2
9191                        | Opcode::GetLoc3 => {
9192                            let value = self.get_loc(insn.a as usize);
9193                            self.push(value);
9194                        }
9195                        Opcode::PutLoc
9196                        | Opcode::PutLoc8
9197                        | Opcode::PutLoc0
9198                        | Opcode::PutLoc1
9199                        | Opcode::PutLoc2
9200                        | Opcode::PutLoc3 => {
9201                            let value = self.pop();
9202                            self.put_loc(insn.a as usize, value);
9203                        }
9204                        Opcode::GetArg
9205                        | Opcode::GetArg0
9206                        | Opcode::GetArg1
9207                        | Opcode::GetArg2
9208                        | Opcode::GetArg3 => {
9209                            let value = self.get_arg(insn.a as usize);
9210                            self.push(value);
9211                        }
9212                        Opcode::PutArg
9213                        | Opcode::PutArg0
9214                        | Opcode::PutArg1
9215                        | Opcode::PutArg2
9216                        | Opcode::PutArg3 => {
9217                            let value = self.pop();
9218                            self.put_arg(insn.a as usize, value);
9219                        }
9220                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
9221                        // for why a non-hole own element is exactly the slow path's answer.
9222                        // The two operands are *peeked*, so a miss leaves the stack as the
9223                        // slow path expects to find it.
9224                        Opcode::GetArrayEl => {
9225                            // One lookup, not two. The guard used `if …is_some()` and the arm
9226                            // then called it again to get the value — two `peek`s, two
9227                            // `array_get`s and two `Value` clones for one element.
9228                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
9229                            // double call was the first version of the `get_field` fast path.
9230                            let Some(value) = self.fast_array_get() else {
9231                                return Ok(self.stop(pc));
9232                            };
9233                            // `a[i]` consumes both operands and leaves the element in their
9234                            // place: one `truncate` and one write, no `pop`/`push` pair.
9235                            let frame = self.frame_mut();
9236                            frame.stack.truncate(frame.stack.len() - 2);
9237                            frame.stack.push(value);
9238                        }
9239                        // `a[i] = v` on a dense array with an integer index: see
9240                        // `fast_array_set` for why the whole store is one step.
9241                        Opcode::PutArrayEl if self.fast_array_set() => {}
9242                        // `o.x` resolved from the inline cache without leaving the loop.
9243                        //
9244                        // The cache is keyed by `(receiver identity, atom, site)` and a
9245                        // monomorphic read re-validates the same chain every iteration, so
9246                        // each one used to cost a `stop(pc)` — a write of `pc` into the
9247                        // frame, a return out of this loop, a re-dispatch through `step` and
9248                        // a re-entry. `property:monomorphic` spent 18% in
9249                        // `read_field_cached` and 21% in `push`, both across that boundary.
9250                        //
9251                        // The site is `pc + width`, which is exactly the `next` the slow arm
9252                        // passes — the two must agree or every fast lookup misses and
9253                        // re-records the same entry forever.
9254                        //
9255                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9256                        // slow arm finds the receiver where it expects it.
9257                        // `name` resolved from the global-variable cache inside the loop.
9258                        //
9259                        // Same shape as `get_field` above and for the same reason: `get_var`
9260                        // was not in the fast loop, so reading a global — which `fib` does
9261                        // once per recursive call, for its own name — cost a `stop(pc)`, a
9262                        // return out of the loop, a `step` re-dispatch and a re-entry, before
9263                        // `get_global` even started its `scopes_are_plain` checks.
9264                        //
9265                        // Everything here is exactly `get_global`'s first branch: not lexical,
9266                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
9267                        // and lets the slow arm decide.
9268                        Opcode::GetVar => {
9269                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9270                                return Ok(self.stop(pc));
9271                            };
9272                            self.push(value);
9273                        }
9274                        Opcode::GetField | Opcode::GetField2 => {
9275                            let Some(value) =
9276                                self.fast_field_get(insn.a as usize, pc + insn.width())
9277                            else {
9278                                return Ok(self.stop(pc));
9279                            };
9280                            if insn.op == Opcode::GetField2 {
9281                                // `get_field2` keeps the receiver for the `call_method` that
9282                                // follows.
9283                                self.push(value);
9284                            } else {
9285                                // `get_field` replaces the receiver, so this is one store over
9286                                // the top slot rather than a `pop` and a `push`: the length
9287                                // never changes, so neither `Vec` arm has a capacity check or a
9288                                // drop to run beyond the one the overwrite itself does.
9289                                let frame = self.frame_mut();
9290                                match frame.stack.last_mut() {
9291                                    Some(slot) => *slot = value,
9292                                    None => return Ok(self.stop(pc)),
9293                                }
9294                            }
9295                        }
9296                        // -- constants ---------------------------------------------------
9297                        Opcode::PushMinus1
9298                        | Opcode::Push0
9299                        | Opcode::Push1
9300                        | Opcode::Push2
9301                        | Opcode::Push3
9302                        | Opcode::Push4
9303                        | Opcode::Push5
9304                        | Opcode::Push6
9305                        | Opcode::Push7
9306                        | Opcode::PushI8
9307                        | Opcode::PushI16
9308                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
9309                        // -- stack shuffling ---------------------------------------------
9310                        Opcode::Drop => {
9311                            self.pop();
9312                        }
9313                        // -- arithmetic on two integers ----------------------------------
9314                        //
9315                        // The operands are *looked at* before they are popped, so a non-integer
9316                        // pair leaves the stack exactly as the slow path expects to find it.
9317                        Opcode::Add if self.numeric_pair() => {
9318                            let right = self.pop();
9319                            let left = self.pop();
9320                            // Exactly [`add_numbers`], which is what the slow arm reaches.
9321                            let answer = match (&left, &right) {
9322                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9323                                    Some(sum) => Value::Int(sum),
9324                                    None => Value::Float(*a as f64 + *b as f64),
9325                                },
9326                                _ => Value::Float(left.to_number() + right.to_number()),
9327                            };
9328                            self.push(answer);
9329                        }
9330                        Opcode::Sub
9331                        | Opcode::And
9332                        | Opcode::Or
9333                        | Opcode::Xor
9334                        | Opcode::Shl
9335                        | Opcode::Sar
9336                        | Opcode::Shr
9337                            if self.numeric_pair() =>
9338                        {
9339                            let right = self.pop();
9340                            let left = self.pop();
9341                            let answer =
9342                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
9343                            self.push(answer);
9344                        }
9345                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
9346                            if self.numeric_pair() =>
9347                        {
9348                            let right = self.pop();
9349                            let left = self.pop();
9350                            let answer = self
9351                                .relational(insn.op, left, right)
9352                                .expect("numbers cannot throw");
9353                            self.push(answer);
9354                        }
9355                        // -- calls -------------------------------------------------------
9356                        //
9357                        // A plain call: `callee(arg0, …, argN) -> result`.
9358                        //
9359                        // This arm exists because of one measurement. `call:recursion` had
9360                        // **20.4% of its profile in `execute_instruction`** — the *slow*
9361                        // executor — and `fib`'s recursive call is the only thing in that
9362                        // function which is not a fast arm. Every call therefore left this
9363                        // loop via `stop()`, went through `step()`'s dispatch and
9364                        // `execute_instruction`'s match over every opcode, and came back here
9365                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
9366                        //
9367                        // Two things make it safe to do here rather than only in the slow path:
9368                        //
9369                        // * the caller's `pc` is stored *before* the call, which is what
9370                        //   `step` does too — so when the callee returns, the caller resumes
9371                        //   after the call and not at it;
9372                        // * `check_memory` runs, because `step` calls it once per instruction
9373                        //   and a call allocates a frame, its locals and its cells. Skipping
9374                        //   the checkpoint here would let a `--memory-limit` script overshoot
9375                        //   by one call per instruction.
9376                        Opcode::Call
9377                        | Opcode::Call0
9378                        | Opcode::Call1
9379                        | Opcode::Call2
9380                        | Opcode::Call3 => {
9381                            let argc = self.argc_operand(insn.op, insn.a);
9382                            let next = pc + insn.width();
9383                            {
9384                                let frame = self
9385                                    .frames
9386                                    .last_mut()
9387                                    .expect("run_fast() is only called with a live frame");
9388                                // `at` is what a stack trace reports for this frame, so a throw
9389                                // inside the callee has to see the call site and not whatever
9390                                // the last `stop()` left there.
9391                                frame.at = insn.offset as usize;
9392                                frame.pc = next;
9393                            }
9394                            self.check_memory()?;
9395                            self.check_interrupt()?;
9396                            let args = self.pop_n(argc);
9397                            let callee = self.pop();
9398                            // A plain call has no receiver; the callee decides what to do with
9399                            // `undefined` (a sloppy function substitutes the global object).
9400                            if let Some(result) =
9401                                self.call_or_push(callee, Value::Undefined, args)?
9402                            {
9403                                // Native, host, generator, async, bound — no frame was pushed,
9404                                // so this loop is still describing the right function. `pc`
9405                                // is advanced by the loop tail like every other arm; only the
9406                                // frame's copy had to be written here, and it already was.
9407                                self.push(result);
9408                            } else {
9409                                // A bytecode callee: its frame is on top now, and `insns` and
9410                                // `pc` both belong to the caller. Start over on the new frame.
9411                                continue 'outer;
9412                            }
9413                        }
9414                        // -- return ------------------------------------------------------
9415                        Opcode::Return => {
9416                            let value = self.pop();
9417                            self.frame_mut().pc = pc + insn.width();
9418                            return Ok(Some(value));
9419                        }
9420                        Opcode::ReturnUndef => {
9421                            self.frame_mut().pc = pc + insn.width();
9422                            return Ok(Some(Value::Undefined));
9423                        }
9424                        // Everything else needs the slow path.
9425                        _ => return Ok(self.stop(pc)),
9426                    },
9427                }
9428                pc += insn.width();
9429            }
9430        }
9431    }
9432
9433    /// Whether the top two operand-stack values are both numbers.
9434    ///
9435    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
9436    /// cannot run script, so the arm may not throw and may not change frames.
9437    fn numeric_pair(&self) -> bool {
9438        is_number(&self.peek(0)) && is_number(&self.peek(1))
9439    }
9440
9441    /// `a[i]` for a dense array and an integer index, without the string round trip.
9442    ///
9443    /// The slow path answers this by turning `i` into a string (`propkey` →
9444    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
9445    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
9446    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
9447    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
9448    /// without even the cheap `Int` formatting.
9449    ///
9450    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
9451    /// unambiguously the one the slow path would give:
9452    ///
9453    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
9454    ///   `2^32-1` is the length, not an index),
9455    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
9456    ///   typed array or an ordinary object, all of which have their own rules),
9457    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
9458    ///   starts walking the prototype chain, and `a[i]` on a hole must find
9459    ///   `Array.prototype[i]` if it exists rather than `undefined`.
9460    ///
9461    /// The last condition is the one that makes this safe rather than merely fast: an own
9462    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
9463    /// `get_var` answered from the global-variable cache, or `None`.
9464    ///
9465    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
9466    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
9467    /// records nothing — the slow arm is about to walk the chain and record it.
9468    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
9469        let frame = self.frame();
9470        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
9471        // "Lexical" is presence in the realm's table, not the closure var's flag: a
9472        // `GlobalRef` forwarded through a nested function has its flags cleared.
9473        if self.realm.globals.contains_key(name) {
9474            return None;
9475        }
9476        if !self.scopes_are_plain() {
9477            return None;
9478        }
9479        let object = &self.realm.global;
9480        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
9481        let cached = self.global_cache[site].as_ref()?;
9482        if !object.upgrades_to(&cached.object) {
9483            return None;
9484        }
9485        object.data_property_at(cached.index, name)
9486    }
9487
9488    /// `o.x` answered entirely from the inline cache, or `None`.
9489    ///
9490    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
9491    /// about to do exactly that and recording it twice would rebuild the chain for every
9492    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
9493    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
9494    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
9495        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
9496        // an object receiver is a reference-count bump that the answer never needs.
9497        let frame = self.frame();
9498        let object = frame.stack.last()?;
9499        let Value::Object(target) = object else {
9500            return None;
9501        };
9502        // A proxy traps the lookup, so no cache entry ever describes it.
9503        if target.proxy_state().is_some() {
9504            return None;
9505        }
9506        let key = frame.code.atom_keys.get(atom)?;
9507        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
9508        if cached.key != *key {
9509            return None;
9510        }
9511        Self::cached_hit(target, cached)
9512    }
9513
9514    fn fast_array_get(&self) -> Option<Value> {
9515        let Value::Int(index) = self.peek(0) else {
9516            return None;
9517        };
9518        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
9519        // set for an `i32`.
9520        if index < 0 {
9521            return None;
9522        }
9523        let Value::Object(object) = self.peek(1) else {
9524            return None;
9525        };
9526        match object.array_get(index as usize) {
9527            Some(value) if !matches!(value, Value::Hole) => Some(value),
9528            _ => None,
9529        }
9530    }
9531
9532    /// `a[i] = v` on a dense array with an integer index, as one store.
9533    ///
9534    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
9535    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
9536    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
9537    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
9538    /// reference at the time it was measured (14.7x).
9539    ///
9540    /// Every condition here is one the slow path would also have to satisfy before
9541    /// storing into the element vector:
9542    ///
9543    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
9544    ///   accepts as an index;
9545    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
9546    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
9547    ///   one inside a recorded descriptor, reports `false` and the caller stops.
9548    ///
9549    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
9550    /// writes the own element too once `array_set` says it did.
9551    fn fast_array_set(&mut self) -> bool {
9552        // Every test runs *before* anything is popped: a refusal has to leave the stack
9553        // exactly as the slow path expects to find it. Popping first and reporting the
9554        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
9555        // then ran the slow path with nothing to write.
9556        let Value::Int(index) = self.peek(1) else {
9557            return false;
9558        };
9559        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
9560        if index < 0 {
9561            return false;
9562        }
9563        // Only a real array: a typed array's elements live in its buffer, a string-like
9564        // object has no element vector, and `array_set` on either does nothing.
9565        let Value::Object(object) = self.peek(2) else {
9566            return false;
9567        };
9568        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
9569            return false;
9570        }
9571        // A non-extensible array reports `false` here, but the *slow* path has to decide
9572        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
9573        // that with the key and the stack still intact.
9574        if !object.is_extensible() {
9575            return false;
9576        }
9577        // Inside the logical length, so the store cannot change `length`. Combined with
9578        // extensibility above, the only growth left for `array_set` is filling a hole in
9579        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
9580        // shape this fast path exists for. A store past the length would grow the array,
9581        // and whether that is allowed is the slow path's question.
9582        if index as usize >= object.array_length().unwrap_or(0) {
9583            return false;
9584        }
9585        // The bound `array_set` refuses past. Checking it here keeps that arm from having
9586        // to report a failure after the operands are gone.
9587        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
9588            return false;
9589        }
9590        let value = self.pop();
9591        self.pop();
9592        self.pop();
9593        object.array_store(self.heap, index as usize, value)
9594    }
9595
9596    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
9597    fn stop(&mut self, pc: usize) -> Option<Value> {
9598        self.frame_mut().pc = pc;
9599        None
9600    }
9601
9602    fn push(&mut self, value: Value) {
9603        self.frame_mut().stack.push(value);
9604    }
9605
9606    fn pop(&mut self) -> Value {
9607        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
9608    }
9609
9610    fn pop_n(&mut self, count: usize) -> Vec<Value> {
9611        let frame = self.frame_mut();
9612        let start = frame.stack.len().saturating_sub(count);
9613        frame.stack.split_off(start)
9614    }
9615
9616    fn peek(&self, back: usize) -> Value {
9617        let frame = self.frame();
9618        frame
9619            .stack
9620            .get(frame.stack.len().wrapping_sub(1 + back))
9621            .cloned()
9622            .unwrap_or(Value::Undefined)
9623    }
9624
9625    #[allow(clippy::too_many_lines)]
9626    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
9627        use Opcode::*;
9628        match op {
9629            // -- constants and stack shuffling -----------------------------
9630            Nop => {}
9631            PushMinus1 => self.push(Value::Int(-1)),
9632            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
9633                let value = match op {
9634                    Push0 => 0,
9635                    Push1 => 1,
9636                    Push2 => 2,
9637                    Push3 => 3,
9638                    Push4 => 4,
9639                    Push5 => 5,
9640                    Push6 => 6,
9641                    _ => 7,
9642                };
9643                self.push(Value::Int(value));
9644            }
9645            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
9646            PushBigintI32 => {
9647                // The immediate form of a `BigInt` literal; the reference has the same
9648                // split between this and a constant-pool entry.
9649                let value = crate::bigint::BigInt::from_i64(a as i64);
9650                self.push(self.bigint(value));
9651            }
9652            PushTrue => self.push(Value::Bool(true)),
9653            PushFalse => self.push(Value::Bool(false)),
9654            PushEmptyString => self.push(self.string("")),
9655            Undefined => self.push(Value::Undefined),
9656            Null => self.push(Value::Null),
9657            Object => {
9658                let proto = self.realm.object_proto.clone();
9659                self.push(Value::Object(self.new_object(Some(proto))));
9660            }
9661            PushThis => {
9662                let this = self.frame().this.clone();
9663                self.push(this);
9664            }
9665            PushConst | PushConst8 => {
9666                let value = self.constant(a as usize)?;
9667                self.push(value);
9668            }
9669            PushAtomValue => {
9670                let text = self.atom_wtf8(a as usize);
9671                self.push(self.string_wtf8(text));
9672            }
9673            Dup => {
9674                let value = self.peek(0);
9675                self.push(value);
9676            }
9677            Dup2 => {
9678                // `a b -> a b a b`
9679                let b = self.peek(0);
9680                let a = self.peek(1);
9681                self.push(a);
9682                self.push(b);
9683            }
9684            Dup3 => {
9685                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
9686                // prototype and key while reading the current value through them.
9687                let c = self.peek(0);
9688                let b = self.peek(1);
9689                let a = self.peek(2);
9690                self.push(a);
9691                self.push(b);
9692                self.push(c);
9693            }
9694            Swap => {
9695                // `a b -> b a`
9696                let bottom = self.pop();
9697                let top = self.pop();
9698                self.push(bottom);
9699                self.push(top);
9700            }
9701            Perm3 => {
9702                // `a b c -> b a c`, the reference's reordering for a spread method
9703                // call: `obj func array` becomes the `func this array` that `apply`
9704                // takes.
9705                let c = self.pop();
9706                let b = self.pop();
9707                let a = self.pop();
9708                self.push(b);
9709                self.push(a);
9710                self.push(c);
9711            }
9712            Dup1 => {
9713                let value = self.peek(1);
9714                self.push(value);
9715            }
9716            Drop => {
9717                self.pop();
9718            }
9719            Nip => {
9720                // `a b -> b`
9721                let top = self.pop();
9722                self.pop();
9723                self.push(top);
9724            }
9725            Perm4 => {
9726                // `obj prop a b -> a obj prop b`, the reference's reordering for a
9727                // postfix update of a computed element: it puts the *old* value
9728                // underneath the receiver and key so `put_array_el` can consume them
9729                // and leave the old value as the expression's result.
9730                let d = self.pop();
9731                let c = self.pop();
9732                let b = self.pop();
9733                let a = self.pop();
9734                self.push(c);
9735                self.push(a);
9736                self.push(b);
9737                self.push(d);
9738            }
9739            Insert2 => {
9740                // `obj a -> a obj a`
9741                let value = self.pop();
9742                let object = self.pop();
9743                self.push(value.clone());
9744                self.push(object);
9745                self.push(value);
9746            }
9747            Insert3 => {
9748                // `obj prop a -> a obj prop a`
9749                let value = self.pop();
9750                let key = self.pop();
9751                let object = self.pop();
9752                self.push(value.clone());
9753                self.push(object);
9754                self.push(key);
9755                self.push(value);
9756            }
9757            Insert4 => {
9758                // `this obj prop a -> a this obj prop a`
9759                //
9760                // `put_super_value` consumes all four and yields nothing, so the copy
9761                // underneath is what leaves the assignment an expression value.
9762                let value = self.pop();
9763                let key = self.pop();
9764                let object = self.pop();
9765                let receiver = self.pop();
9766                self.push(value.clone());
9767                self.push(receiver);
9768                self.push(object);
9769                self.push(key);
9770                self.push(value);
9771            }
9772            Swap2 => {
9773                // `a b c d -> c d a b`
9774                let d = self.pop();
9775                let c = self.pop();
9776                let b = self.pop();
9777                let a = self.pop();
9778                self.push(c);
9779                self.push(d);
9780                self.push(a);
9781                self.push(b);
9782            }
9783            Rot3l => {
9784                // `x a b -> a b x`
9785                let b = self.pop();
9786                let a = self.pop();
9787                let x = self.pop();
9788                self.push(a);
9789                self.push(b);
9790                self.push(x);
9791            }
9792            Rot3r => {
9793                // `a b c -> c a b`
9794                let c = self.pop();
9795                let b = self.pop();
9796                let a_value = self.pop();
9797                self.push(c);
9798                self.push(a_value);
9799                self.push(b);
9800            }
9801
9802            Rest => {
9803                // `...rest` in a parameter list: the arguments from index `a` on, as a
9804                // real array. It takes nothing off the stack — the arguments are in the
9805                // frame, not on it.
9806                let frame = self.frame();
9807                let from = a as usize;
9808                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9809                let array = self.new_array(collected);
9810                self.push(Value::Object(array));
9811            }
9812
9813            // -- slots ------------------------------------------------------
9814            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9815                let slot = self.slot_operand(op, a);
9816                let value = self.get_loc(slot);
9817                self.push(value);
9818            }
9819            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9820                let slot = self.slot_operand(op, a);
9821                let value = self.pop();
9822                self.put_loc(slot, value);
9823            }
9824            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9825                let slot = self.slot_operand(op, a);
9826                let value = self.pop();
9827                self.put_loc(slot, value.clone());
9828                self.push(value);
9829            }
9830            // The `_check` forms are the temporal dead zone: they throw when the
9831            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9832            // *reads*, so only the two writes may pop — mishandling that quietly
9833            // consumes the value the caller pushed just before.
9834            GetLocCheck => {
9835                let slot = self.slot_operand(op, a);
9836                let value = self.get_loc(slot);
9837                if matches!(value, Value::Uninitialized) {
9838                    return Err(self.dead_zone(slot, VarSlot::Loc));
9839                }
9840                self.push(value);
9841            }
9842            PutLocCheck | SetLocCheck => {
9843                let slot = self.slot_operand(op, a);
9844                let value = self.pop();
9845                if matches!(value, Value::Uninitialized) {
9846                    return Err(self.dead_zone(slot, VarSlot::Loc));
9847                }
9848                // The initialiser goes through `put_loc`, not this, so any store that
9849                // reaches here is a later assignment — which a `const` refuses.
9850                if self.is_read_only(slot, VarSlot::Loc) {
9851                    return Err(self.read_only(slot, VarSlot::Loc));
9852                }
9853                if op == SetLocCheck {
9854                    self.put_loc(slot, value.clone());
9855                    self.push(value);
9856                } else {
9857                    self.put_loc(slot, value);
9858                }
9859            }
9860            PutLocCheckInit => {
9861                // The one store that *initialises* a lexical slot: `this` in a derived
9862                // constructor, which only exists after `super()` has run. A second
9863                // initialisation is the error the reference reports as
9864                // "'this' can be initialized only once".
9865                let slot = self.slot_operand(op, a);
9866                let value = self.pop();
9867                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9868                    return Err(Signal::Throw(self.make_error(
9869                        "ReferenceError",
9870                        "'this' can be initialized only once",
9871                    )));
9872                }
9873                self.put_loc(slot, value);
9874            }
9875            CheckCtor => {
9876                // A class constructor may only run under `new`, which is what makes
9877                // `class A {}; A()` a TypeError.
9878                if matches!(self.frame().new_target, Value::Undefined) {
9879                    return Err(Signal::Throw(self.make_error(
9880                        "TypeError",
9881                        "class constructors must be invoked with 'new'",
9882                    )));
9883                }
9884            }
9885            InitCtor => {
9886                // The body a derived class gets when it declares no constructor:
9887                // forward every argument to the parent constructor, keeping `new.target`.
9888                if matches!(self.frame().new_target, Value::Undefined) {
9889                    return Err(Signal::Throw(self.make_error(
9890                        "TypeError",
9891                        "class constructors must be invoked with 'new'",
9892                    )));
9893                }
9894                let Some(callee) = self.current_callee() else {
9895                    return Err(Signal::Throw(
9896                        self.make_error("TypeError", "no constructor to inherit from"),
9897                    ));
9898                };
9899                let parent = callee.proto().map_or(Value::Null, Value::Object);
9900                let new_target = self.frame().new_target.clone();
9901                let args = self.frame().passed().to_vec();
9902                let result = self.construct(parent, new_target, args)?;
9903                self.push(result);
9904            }
9905            SetLocUninitialized => {
9906                let slot = self.slot_operand(op, a);
9907                self.put_loc(slot, Value::Uninitialized);
9908            }
9909            CloseLoc => {
9910                // "Close" a binding: give it a *fresh* cell holding the current
9911                // value. Closures created before this point keep the old cell and the
9912                // ones created after see the new one, which is what makes every
9913                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9914                // a block-scoped binding when the block ends.
9915                //
9916                // Clearing the slot instead (which this used to do) broke both: a
9917                // closure over a captured block variable read `undefined`, and a loop
9918                // terminated after one iteration.
9919                let slot = self.slot_operand(op, a);
9920                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9921                if index >= 0 {
9922                    let current = self.frame().cells[index as usize].get();
9923                    let fresh = self.new_cell(current);
9924                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9925                        *cell = fresh;
9926                    }
9927                }
9928            }
9929            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9930                let slot = self.slot_operand(op, a);
9931                let value = self.get_arg(slot);
9932                self.push(value);
9933            }
9934            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9935                let slot = self.slot_operand(op, a);
9936                let value = self.pop();
9937                self.put_arg(slot, value);
9938            }
9939            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9940                let slot = self.slot_operand(op, a);
9941                let value = self.pop();
9942                self.put_arg(slot, value.clone());
9943                self.push(value);
9944            }
9945
9946            // -- closure variables ------------------------------------------
9947            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9948                let slot = self.slot_operand(op, a);
9949                // A name a direct `eval` created shadows the binding the compiler chose.
9950                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9951                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9952                // and only a runtime lookup can know that.
9953                if let Some(cell) = self.eval_created_local(slot) {
9954                    self.push(cell.get());
9955                    return self.step();
9956                }
9957                let value = self.cell_value(slot)?;
9958                self.push(value);
9959            }
9960            GetVarRefCheck => {
9961                let slot = self.slot_operand(op, a);
9962                let value = self.cell_value(slot)?;
9963                if matches!(value, Value::Uninitialized) {
9964                    return Err(self.dead_zone(slot, VarSlot::Closure));
9965                }
9966                self.push(value);
9967            }
9968            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9969                let slot = self.slot_operand(op, a);
9970                let value = self.pop();
9971                if let Some(cell) = self.eval_created_local(slot) {
9972                    cell.set(value);
9973                    return self.step();
9974                }
9975                // Same rule as `PutLocCheck`: a checked store to a captured binding
9976                // refuses a `const` once its initialiser has run.
9977                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9978                    return Err(self.read_only(slot, VarSlot::Closure));
9979                }
9980                self.set_cell(slot, value)?;
9981            }
9982            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9983                let slot = self.slot_operand(op, a);
9984                let value = self.pop();
9985                if let Some(cell) = self.eval_created_local(slot) {
9986                    cell.set(value.clone());
9987                    self.push(value);
9988                    return self.step();
9989                }
9990                self.set_cell(slot, value.clone())?;
9991                self.push(value);
9992            }
9993
9994            // -- globals ----------------------------------------------------
9995            GetVar => {
9996                let value = self.get_global(a as usize)?;
9997                self.push(value);
9998            }
9999            GetVarUndef => {
10000                let value = self
10001                    .get_global(a as usize)
10002                    .or_else(|_| Ok(Value::Undefined))?;
10003                self.push(value);
10004            }
10005            DeleteVar => {
10006                // `delete name` for a name that is not a declared binding. A lexical
10007                // global lives in the reference table and cannot be deleted; anything
10008                // reachable only as a property of the global object is *implicit* —
10009                // `x = 1` with no declaration — and goes away if it is configurable,
10010                // which is what `delete` on an implicit global answers.
10011                let name = self.atom_text(a as usize);
10012                let global = self.realm.global.clone();
10013                let deleted = if self.realm.globals.contains_key(&name) {
10014                    false
10015                } else if global.own_property(&name).is_some() {
10016                    self.delete_property(&global, &name)?
10017                } else {
10018                    true
10019                };
10020                self.push(Value::Bool(deleted));
10021            }
10022            PutVar => {
10023                let value = self.pop();
10024                self.put_global(a as usize, value)?;
10025            }
10026            PutVarInit => {
10027                let slot = a as usize;
10028                let value = self.pop();
10029                self.init_global(slot, value)?;
10030            }
10031
10032            // -- arithmetic -------------------------------------------------
10033            Add => self.binary_add()?,
10034            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10035                let raw_right = self.pop();
10036                let raw_left = self.pop();
10037                // BigInt arithmetic is a separate path, and not only for the type of the
10038                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10039                // rather than a silent conversion.
10040                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10041                    let left = self.primitive_of(raw_left)?;
10042                    let right = self.primitive_of(raw_right)?;
10043                    let value = self.bigint_arithmetic(op, left, right)?;
10044                    self.push(value);
10045                } else {
10046                    let right = self.numeric(raw_right)?;
10047                    let left = self.numeric(raw_left)?;
10048                    self.push(arithmetic(op, left, right)?);
10049                }
10050            }
10051            Neg => {
10052                let raw = self.pop();
10053                match raw {
10054                    // A bigint negates exactly, however wide it is.
10055                    Value::BigInt(big) => {
10056                        let negated = big.negate();
10057                        self.push(self.bigint(negated));
10058                    }
10059                    other => {
10060                        let value = self.numeric(other)?;
10061                        self.push(negate(value));
10062                    }
10063                }
10064            }
10065            Plus => {
10066                let value = self.pop();
10067                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10068                // unary plus is defined to produce a *number*, which a bigint cannot
10069                // become without loss. It used to fall through to `NaN`.
10070                if matches!(value, Value::BigInt(_)) {
10071                    return Err(self.type_error("cannot convert bigint to number"));
10072                }
10073                let numeric = self.numeric_of(value)?;
10074                self.push(numeric);
10075            }
10076            Inc => {
10077                let raw = self.pop();
10078                let (_, updated) = self.advance_numeric(raw, true)?;
10079                self.push(updated);
10080            }
10081            Dec => {
10082                let raw = self.pop();
10083                let (_, updated) = self.advance_numeric(raw, false)?;
10084                self.push(updated);
10085            }
10086            PostInc | PostDec => {
10087                // `x -> x x+1`: the *new* value ends up on top, so the store the
10088                // compiler emits right after (`put_var`) writes the incremented
10089                // one, while the old value stays underneath for the expression's
10090                // own result. Getting this backwards makes `i++` a no-op, which
10091                // turns `while (i < 3)` into an infinite loop.
10092                let raw = self.pop();
10093                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10094                self.push(old);
10095                self.push(updated);
10096            }
10097            Not => {
10098                let raw = self.pop();
10099                match raw {
10100                    // `~x` on a bigint is `-x - 1`, exact at any width.
10101                    Value::BigInt(big) => {
10102                        let inverted = big.bitnot();
10103                        self.push(self.bigint(inverted));
10104                    }
10105                    other => {
10106                        let value = self.numeric(other)?;
10107                        self.push(Value::Int(!value.to_int32()));
10108                    }
10109                }
10110            }
10111            Lnot => {
10112                let value = self.pop();
10113                self.push(Value::Bool(!value.to_boolean()));
10114            }
10115
10116            // -- comparison -------------------------------------------------
10117            Lt | Lte | Gt | Gte => {
10118                let right = self.pop();
10119                let left = self.pop();
10120                let answer = self.relational(op, left, right)?;
10121                self.push(answer);
10122            }
10123            Eq | Neq => {
10124                let right = self.pop();
10125                let left = self.pop();
10126                let equal = self.abstract_equals(left, right)?;
10127                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10128            }
10129            StrictEq => {
10130                let right = self.pop();
10131                let left = self.pop();
10132                self.push(Value::Bool(left.strict_equals(&right)));
10133            }
10134            StrictNeq => {
10135                let right = self.pop();
10136                let left = self.pop();
10137                self.push(Value::Bool(!left.strict_equals(&right)));
10138            }
10139            IsUndefined => {
10140                // `=== undefined`, which is what a destructuring default tests. It is
10141                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10142                let value = self.pop();
10143                self.push(Value::Bool(matches!(value, Value::Undefined)));
10144            }
10145            IsUndefinedOrNull => {
10146                let value = self.pop();
10147                self.push(Value::Bool(value.is_nullish()));
10148            }
10149            Typeof => {
10150                let value = self.pop();
10151                self.push(self.string(value.type_of()));
10152            }
10153            ToObject => {
10154                // A destructuring *object* pattern starts here, which is why
10155                // `var {} = null` throws. Only `undefined` and `null` are refused; a
10156                // primitive is boxed.
10157                let value = self.pop();
10158                let object = self.object_from(&value)?;
10159                self.push(Value::Object(object));
10160            }
10161            Instanceof => {
10162                let constructor = self.pop();
10163                let object = self.pop();
10164                let answer = self.instance_of(&object, &constructor)?;
10165                self.push(Value::Bool(answer));
10166            }
10167            In => {
10168                let object = self.pop();
10169                let key = self.pop();
10170                let answer = self.has_property(&key, &object)?;
10171                self.push(Value::Bool(answer));
10172            }
10173
10174            // -- control flow -----------------------------------------------
10175            Goto | Goto8 | Goto16 => {
10176                self.frame_mut().pc = a as usize;
10177            }
10178            IfTrue | IfTrue8 => {
10179                let value = self.pop();
10180                if value.to_boolean() {
10181                    self.frame_mut().pc = a as usize;
10182                }
10183            }
10184            IfFalse | IfFalse8 => {
10185                let value = self.pop();
10186                if !value.to_boolean() {
10187                    self.frame_mut().pc = a as usize;
10188                }
10189            }
10190            Catch => {
10191                // Pushes the handler target onto the value stack; `unwind` finds it.
10192                self.push(Value::CatchOffset(a));
10193            }
10194            Gosub => {
10195                self.push(Value::ReturnAddress(next as u32));
10196                self.frame_mut().pc = a as usize;
10197            }
10198            Ret => {
10199                let value = self.pop();
10200                match value {
10201                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10202                    _ => {
10203                        return Err(Signal::Throw(
10204                            self.make_error("InternalError", "invalid return address"),
10205                        ));
10206                    }
10207                }
10208            }
10209            NipCatch => {
10210                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10211                // including the marker, keeping the top value.
10212                let top = self.pop();
10213                loop {
10214                    match self.pop() {
10215                        Value::CatchOffset(_) | Value::Undefined => break,
10216                        _ => {}
10217                    }
10218                    if self.frame().stack.is_empty() {
10219                        break;
10220                    }
10221                }
10222                self.push(top);
10223            }
10224            Throw => {
10225                let value = self.pop();
10226                return Err(Signal::Throw(value));
10227            }
10228            ThrowError => {
10229                let name = self.atom_text(a as usize);
10230                let (class, message) = match b {
10231                    0 => ("TypeError", format!("'{name}' is read-only")),
10232                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10233                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
10234                    // `delete super.x` is a syntax-level mistake the reference reports
10235                    // with this wording, not a property-access failure.
10236                    3 => (
10237                        "ReferenceError",
10238                        "unsupported reference to 'super'".to_string(),
10239                    ),
10240                    4 => (
10241                        "TypeError",
10242                        "iterator does not have a throw method".to_string(),
10243                    ),
10244                    5 => (
10245                        "ReferenceError",
10246                        "invalid assignment left-hand side".to_string(),
10247                    ),
10248                    _ => ("TypeError", format!("invalid operation on '{name}'")),
10249                };
10250                return Err(Signal::Throw(self.make_error(class, &message)));
10251            }
10252            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10253            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10254            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10255            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10256            Await => return Ok(Step::Suspend(SuspendKind::Await)),
10257            ReturnAsync => {
10258                // The reference's `return_async` returns `undefined` and lets the resume
10259                // machinery pick the real value off `sp[-1]`, which is how it tells a
10260                // completion from a suspension. Carrying the value explicitly says the
10261                // same thing without the implicit stack slot.
10262                let value = self.pop();
10263                return Ok(Step::Return(value));
10264            }
10265            Return => {
10266                let value = self.pop();
10267                return Ok(Step::Return(value));
10268            }
10269            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10270
10271            // -- calls ------------------------------------------------------
10272            Call | Call0 | Call1 | Call2 | Call3 => {
10273                let argc = self.argc_operand(op, a);
10274                let args = self.pop_n(argc);
10275                let callee = self.pop();
10276                // A plain call has no receiver; the callee decides what to do with
10277                // `undefined` (a sloppy function substitutes the global object).
10278                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
10279                    self.push(result);
10280                }
10281            }
10282            CallConstructor => {
10283                // `constructor this_obj args… -> object`. The duplicated
10284                // constructor is `new.target`; this milestone does not expose it,
10285                // so the extra copy is simply consumed here.
10286                let argc = a as usize;
10287                let args = self.pop_n(argc);
10288                let new_target = self.pop();
10289                let callee = self.pop();
10290                let result = self.construct(callee, new_target, args)?;
10291                self.push(result);
10292            }
10293            CallMethod => {
10294                let argc = a as usize;
10295                let args = self.pop_n(argc);
10296                let callee = self.pop();
10297                let this = self.pop();
10298                if let Some(result) = self.call_or_push(callee, this, args)? {
10299                    self.push(result);
10300                }
10301            }
10302            Apply => {
10303                // `func this array -> result`, the spread-call form: the compiler
10304                // builds one array of arguments, and all that is left here is to
10305                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
10306                let array = self.pop();
10307                let this = self.pop();
10308                let callee = self.pop();
10309                let args = self.array_like_to_args(&array)?;
10310                if a & 1 != 0 {
10311                    let result = self.construct(callee, this, args)?;
10312                    self.push(result);
10313                } else if let Some(result) = self.call_or_push(callee, this, args)? {
10314                    self.push(result);
10315                }
10316            }
10317            TailCall | TailCallMethod => {
10318                // `tail_call` is `call` whose result is returned immediately — the
10319                // reference jumps straight to `done` instead of storing the value and
10320                // running on. The callee still gets its own frame, so deep tail
10321                // recursion hits the stack limit exactly like plain recursion does;
10322                // marking this frame lets the return path unwind without needing
10323                // instructions after the call.
10324                let argc = if op == TailCallMethod {
10325                    a as usize
10326                } else {
10327                    self.argc_operand(op, a)
10328                };
10329                let args = self.pop_n(argc);
10330                let callee = self.pop();
10331                let this = if op == TailCallMethod {
10332                    self.pop()
10333                } else {
10334                    Value::Undefined
10335                };
10336                if let Value::Object(function) = &callee
10337                    && let Some((code, env)) = bytecode_of(function)
10338                {
10339                    // A generator or async body is not run here at all: calling it only
10340                    // *creates* the generator/coroutine, so it must not inherit this
10341                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
10342                    // onto `f`'s frame, and the first `yield`/`await` then reported
10343                    // "a generator body ran as an ordinary call".
10344                    if code.code.kind.is_generator() || code.code.kind.is_async() {
10345                        let value = self.call_value(callee, this, args)?;
10346                        return Ok(Step::Return(value));
10347                    }
10348                    self.frame_mut().tail = true;
10349                    self.push_frame(code, env, this, args, callee)?;
10350                    return Ok(Step::Continue);
10351                }
10352                // A native callee has no frame to reuse, so its value is simply
10353                // returned.
10354                let value = self.call_value(callee, this, args)?;
10355                return Ok(Step::Return(value));
10356            }
10357
10358            // -- objects ----------------------------------------------------
10359            SpecialObject => {
10360                let value = self.special_object(a)?;
10361                self.push(value);
10362            }
10363            PrivateSymbol => {
10364                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
10365                // symbol each time it is evaluated, which is why the compiler evaluates it
10366                // once (at class definition) and stores it in a class-scope binding.
10367                let name = self.atom_text(a as usize);
10368                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
10369                self.push(Value::Symbol(symbol));
10370            }
10371            GetPrivateField => {
10372                // `obj symbol -> value`. A missing private field is a TypeError, which is what
10373                // makes `#x` inaccessible on any object not built by this class.
10374                let symbol = self.pop();
10375                let object = self.pop();
10376                let value = self.read_private_field(&object, &symbol)?;
10377                self.push(value);
10378            }
10379            PutPrivateField => {
10380                // `obj value symbol ->`, and the store is a plain assignment to a property the
10381                // class already created, so there is no setter to consult.
10382                let symbol = self.pop();
10383                let value = self.pop();
10384                let object = self.pop();
10385                self.write_private_field(&object, &symbol, value)?;
10386            }
10387            DefinePrivateField => {
10388                // `obj symbol value -> obj`: a field initialiser creates the property, and
10389                // redefining one is a TypeError ("already exists").
10390                let value = self.pop();
10391                let symbol = self.pop();
10392                let object = self.pop();
10393                self.define_private_field(&object, &symbol, value)?;
10394                self.push(object);
10395            }
10396            PrivateIn => {
10397                // `obj key -> bool`: `#x in o`. The second operand decides which question is
10398                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
10399                // is a field, so this is an own-property test; a *function* is a method or
10400                // accessor, so this is a brand check.
10401                let key = self.pop();
10402                let object = self.pop();
10403                let Some(target) = object.as_object() else {
10404                    return Err(Signal::Throw(
10405                        self.make_error("TypeError", "invalid 'in' operand"),
10406                    ));
10407                };
10408                let present = match &key {
10409                    Value::Object(_) => self.check_brand(target, &key)?,
10410                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
10411                };
10412                self.push(Value::Bool(present));
10413            }
10414            AddBrand => {
10415                // `obj home ->`: create the class brand on `home` if it has none, then give
10416                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
10417                // class definition: only the prototype's copy of the symbol is wanted.
10418                let home = self.pop();
10419                let object = self.pop();
10420                self.add_brand(&object, &home)?;
10421            }
10422            CheckBrand => {
10423                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
10424                // Both stay, because the caller needs them — `nip` halves a read into its
10425                // value and `call_method` uses the pair as receiver and callee.
10426                let function = self.peek(0);
10427                let object = self.peek(1);
10428                let Some(target) = object.as_object() else {
10429                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10430                };
10431                if !self.check_brand(target, &function)? {
10432                    return Err(Signal::Throw(
10433                        self.make_error("TypeError", "invalid brand on object"),
10434                    ));
10435                }
10436            }
10437            GetLength => {
10438                // `get_length` is the `.length` read; an array and a string answer
10439                // from their own length, anything else from the property.
10440                let target = self.pop();
10441                let value = match &target {
10442                    Value::Object(object) => match object.array_length() {
10443                        Some(length) => crate::object::length_value(length),
10444                        None => self.read_field(&target, "length")?,
10445                    },
10446                    Value::String(text) => Value::Int(text.utf16_len() as i32),
10447                    _ => self.read_field(&target, "length")?,
10448                };
10449                self.push(value);
10450            }
10451            GetField | GetField2 => {
10452                let object = self.pop();
10453                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
10454                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
10455                // just below is what lets the borrow outlive the `&mut self` the lookup
10456                // needs — one refcount bump instead of a key clone plus its drop, on the
10457                // hottest property path there is: every `o.x` and every `o.m()` receiver.
10458                let code = self.frame().code.clone();
10459                let key = &code.atom_keys[a as usize];
10460                let value = self.read_field_cached(&object, key, next)?;
10461                if op == GetField2 {
10462                    self.push(object);
10463                }
10464                self.push(value);
10465            }
10466            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
10467                let key = self.pop();
10468                let object = self.pop();
10469                let key = self.propkey(&key)?;
10470                let value = self.read_field_key(&object, &key)?;
10471                if matches!(op, GetArrayEl2 | GetArrayEl3) {
10472                    self.push(object);
10473                }
10474                if op == GetArrayEl3 {
10475                    // The key goes back in its *value* form, which the compiler stores
10476                    // into the target of a destructuring assignment.
10477                    self.push(match &key {
10478                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
10479                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
10480                    });
10481                }
10482                self.push(value);
10483            }
10484            PutField => {
10485                let value = self.pop();
10486                let object = self.pop();
10487                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
10488                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
10489                // only reads. `this.value = …` is the write half of the hottest loop in
10490                // `property:method-call`, and `own_property_key` was 4.8% of the case.
10491                let code = self.frame().code.clone();
10492                let key = &code.atom_keys[a as usize];
10493                self.write_field_key(&object, key, value)?;
10494            }
10495            PutArrayEl => {
10496                let value = self.pop();
10497                let key = self.pop();
10498                let object = self.pop();
10499                let key = self.propkey(&key)?;
10500                self.write_field_key(&object, &key, value)?;
10501            }
10502            DefineField => {
10503                let value = self.pop();
10504                let object = self.pop();
10505                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
10506                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
10507                // three U+FFFD — a property under a different name from the one
10508                // `o["\uD800"]` reads.
10509                let code = self.frame().code.clone();
10510                let key = code.atom_keys[a as usize].clone();
10511                // No naming here. `{m: function(){}}` is named by the *compiler*, which
10512                // emits `set_name` — and only where `NamedEvaluation` applies, so
10513                // `{m: (0, function(){})}` stays anonymous. Naming every function that
10514                // reaches a property definition got that case wrong, and the compiler is
10515                // the only place that can tell the two apart.
10516                if let Some(target) = object.as_object() {
10517                    // Only an *array* stores into the element vector. A numeric key
10518                    // on an ordinary object is an ordinary property, which is what
10519                    // makes `{1: 'a'}` iterate as a key rather than disappear.
10520                    let stored = target.is_array()
10521                        && key.as_str().and_then(array_index).is_some_and(|index| {
10522                            target.array_set(self.heap, index as usize, value.clone())
10523                        });
10524                    if !stored {
10525                        target.define_data_key(&key, value);
10526                    }
10527                }
10528                self.push(object);
10529            }
10530            DefineArrayEl => {
10531                // `obj key value -> obj key`. The *value* form of the key is what goes
10532                // back on the stack — the compiler stores it into the pattern's binding —
10533                // so the symbol is not stringified on the way through.
10534                let value = self.pop();
10535                let key_value = self.pop();
10536                let object = self.peek(0);
10537                let key = self.propkey(&key_value)?;
10538                self.write_field_key(&object, &key, value)?;
10539                self.push(key_value);
10540            }
10541            SetHomeObject => {
10542                // `obj func -> obj func`: records the object a method was defined on so
10543                // `super` inside it resolves against that object's prototype.
10544                let function = self.peek(0);
10545                let home = self.peek(1);
10546                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
10547                    function.set_home_object(Some(home.clone()));
10548                }
10549            }
10550            Regexp => {
10551                // `pattern flags -> regexp`. A literal compiles here rather than through the
10552                // constructor, which is both what the reference's dedicated opcode is for
10553                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
10554                let flags = self.pop();
10555                let pattern = self.pop();
10556                let pattern = self.to_js_string(&pattern)?;
10557                let flags = self.to_js_string(&flags)?;
10558                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
10559                self.push(Value::Object(object));
10560            }
10561            UsingDisposeInit => {
10562                // The error state a disposal accumulates into. Uninitialised means "no
10563                // failure yet"; anything else is the exception being propagated.
10564                self.push(Value::Uninitialized);
10565            }
10566            UsingCheck => {
10567                // `value -> value, method`: validate and snapshot the disposer now, so a
10568                // later change to `Symbol.dispose` cannot change what gets called, and so a
10569                // value that is not disposable fails before the body runs.
10570                let value = self.pop();
10571                let method = self.using_method_for(&value, a as u8 == 1)?;
10572                self.push(value);
10573                self.push(method);
10574            }
10575            UsingDispose => {
10576                // `error_state -> error_state'`: dispose the variable at `slot` — its value
10577                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
10578                // the pending error.
10579                let slot = self.slot_operand(op, a);
10580                let error_state = self.pop();
10581                let merged = self.using_dispose_once(slot, error_state)?;
10582                self.push(merged);
10583            }
10584            UsingDisposeMerge => {
10585                let new_error = self.pop();
10586                let error_state = self.pop();
10587                let merged = self.merge_dispose_error(new_error, error_state);
10588                self.push(merged);
10589            }
10590            UsingDisposeEnd => {
10591                // A disposal that failed replaces the block's normal completion, so the
10592                // error state becomes a real throw here rather than at the call site.
10593                let error_state = self.pop();
10594                if !matches!(error_state, Value::Uninitialized) {
10595                    return Err(Signal::Throw(error_state));
10596                }
10597            }
10598            UsingDisposeAsync => {
10599                // `await using` needs a promise to await and this runtime has no
10600                // `Promise` builtin, so the disposer is called synchronously and its result
10601                // discarded. That is correct for a disposer that returns nothing and is
10602                // reported as a gap rather than silently skipped.
10603                let slot = self.slot_operand(op, a);
10604                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
10605                self.push(error_state);
10606            }
10607            GetSuper => {
10608                // `obj -> obj's prototype`: the starting point of a `super` lookup.
10609                let object = self.pop();
10610                let proto = match &object {
10611                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
10612                    _ => Value::Null,
10613                };
10614                self.push(proto);
10615            }
10616            GetSuperValue => {
10617                // `receiver proto key -> value`, searching from `proto` but reporting to
10618                // `receiver`, which is what `super.g` must do for a getter to see `this`.
10619                //
10620                // Three values in, one out: the receiver is *consumed*, not left under the
10621                // result. Leaving it there was invisible for `super.x` in `return` or
10622                // statement position (the result is what gets popped) and corrupted the
10623                // frame everywhere else — `print(super.x)` left the class where the call
10624                // opcode looks for the receiver and called the class itself.
10625                let key = self.pop();
10626                let proto = self.pop();
10627                let receiver = self.pop();
10628                let value = self.super_read(&receiver, &proto, &key)?;
10629                self.push(value);
10630            }
10631            PutSuperValue => {
10632                // `receiver proto key value ->`: a store that starts at `proto` but
10633                // assigns to `receiver`.
10634                let value = self.pop();
10635                let key = self.pop();
10636                let proto = self.pop();
10637                let receiver = self.pop();
10638                self.super_write(&receiver, &proto, &key, value)?;
10639            }
10640            DefineClass => {
10641                // `parent ctor -> ctor proto`: the constructor becomes the class and a
10642                // fresh prototype object lands on top for the methods to go on.
10643                let name = self.atom_text(a as usize);
10644                let (ctor, proto) = self.define_class(&name, b)?;
10645                self.push(ctor);
10646                self.push(Value::Object(proto));
10647            }
10648            DefineClassComputed => {
10649                // `parent ctor key -> ctor proto key`: the computed name stays put so
10650                // `define_field`-style consumers can still read it.
10651                let key = self.pop();
10652                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10653                let (ctor, proto) = self.define_class(&name, b)?;
10654                self.push(ctor);
10655                self.push(Value::Object(proto));
10656                self.push(key);
10657            }
10658            DefineMethod => {
10659                let function = self.pop();
10660                let object = self.pop();
10661                // The exact key, like `define_field`: a quoted method key may hold an
10662                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
10663                // that `o["\uD800"]` finds.
10664                let code = self.frame().code.clone();
10665                let key = code.atom_keys[a as usize].clone();
10666                // A method's `[[HomeObject]]` is the object it was defined on, which is
10667                // what `super` inside it resolves against.
10668                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10669                    function.set_home_object(Some(object.clone()));
10670                }
10671                if let Some(text) = key.as_wtf8() {
10672                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
10673                } else {
10674                    self.set_function_name(
10675                        &function,
10676                        &key_with_accessor_prefix(&key.to_string(), b),
10677                    );
10678                }
10679                if let Some(array) = object.as_object() {
10680                    define_function_property(array, &key, function, b);
10681                }
10682                self.push(object);
10683            }
10684            DefineMethodComputed => {
10685                let function = self.pop();
10686                let key = self.pop();
10687                let object = self.pop();
10688                let key = self.propkey(&key)?;
10689                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
10690                // the name: `super` inside a computed method resolves through it. Without
10691                // this, `class B extends A { [k]() { return super.m() } }` read the
10692                // home object as null and threw.
10693                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10694                    function.set_home_object(Some(object.clone()));
10695                }
10696                match key.as_wtf8() {
10697                    Some(text) => {
10698                        let name = accessor_prefixed(text, a);
10699                        self.set_function_name_wtf8(&function, &name);
10700                    }
10701                    None => self.set_function_name(
10702                        &function,
10703                        &key_with_accessor_prefix(&key.to_string(), a),
10704                    ),
10705                }
10706                if let Some(array) = object.as_object() {
10707                    define_function_property(array, &key, function, a);
10708                }
10709                self.push(object);
10710            }
10711            SetProto => {
10712                let proto = self.pop();
10713                let object = self.pop();
10714                if let Some(target) = object.as_object() {
10715                    target.set_proto(proto.as_object().cloned());
10716                }
10717                self.push(object);
10718            }
10719            CopyDataProperties => {
10720                let exclusion = self.pop();
10721                let source = self.pop();
10722                let target = self.peek(0);
10723                self.copy_properties(&target, &source, &exclusion)?;
10724                self.push(source);
10725                self.push(exclusion);
10726            }
10727            ToPropkey => {
10728                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
10729                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
10730                // ordinary `"Symbol(b)"` property.
10731                let value = self.pop();
10732                let key = match self.propkey(&value)? {
10733                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
10734                    PropertyKey::String(text) => self.string_wtf8(text),
10735                };
10736                self.push(key);
10737            }
10738            SetName => {
10739                let function = self.peek(0);
10740                let name = self.atom_wtf8(a as usize);
10741                self.set_function_name_wtf8(&function, &name);
10742            }
10743            SetNameComputed => {
10744                let key = self.peek(1);
10745                let function = self.peek(0);
10746                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10747                self.set_function_name(&function, &name);
10748            }
10749
10750            // -- arrays -----------------------------------------------------
10751            ArrayFrom => {
10752                let count = a as usize;
10753                let elements = self.pop_n(count);
10754                let array = self.new_array(elements);
10755                self.push(Value::Object(array));
10756            }
10757            Append => {
10758                // `array index iterable -> array new_index`
10759                let iterable = self.pop();
10760                self.pop();
10761                let array = self.peek(0);
10762                let added = self.append_enumerate(&array, &iterable)?;
10763                self.push(Value::Int(added));
10764            }
10765
10766            // -- iteration --------------------------------------------------
10767            ForInStart => {
10768                let value = self.pop();
10769                let record = self.for_in_record(&value)?;
10770                self.push(Value::Object(record));
10771            }
10772            ForInNext => {
10773                // `record -> record key done`. The flag is *done*, not "found":
10774                // the compiler tests it with `if_false` to jump back into the body,
10775                // so reporting `true` while keys remain would end the loop at once.
10776                let record = self.peek(0);
10777                match self.for_in_advance(&record)? {
10778                    Some(key) => {
10779                        let text = self.string(key);
10780                        self.push(text);
10781                        self.push(Value::Bool(false));
10782                    }
10783                    None => {
10784                        self.push(Value::Undefined);
10785                        self.push(Value::Bool(true));
10786                    }
10787                }
10788            }
10789            ForOfStart => {
10790                let value = self.pop();
10791                let iterator = self.get_iterator(&value)?;
10792                self.push(iterator.object);
10793                self.push(iterator.next);
10794                self.push(Value::CatchOffset(0));
10795            }
10796            ForOfNext => {
10797                // `iter next catch_offset -> iter next catch_offset value done`.
10798                //
10799                // The operand is how many values sit *above* the iterator triple: a
10800                // destructuring rest element keeps its target array and running index
10801                // there while draining the iterator, so the triple is not at the top.
10802                let extra = a as usize;
10803                let iterator_slot = 2 + extra;
10804                // An exhausted iterator is replaced by `undefined` (see below), so a
10805                // second step must not call `next` again — `Array.from` and a
10806                // destructuring pattern both keep stepping past the end.
10807                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10808                    (Value::Undefined, true)
10809                } else {
10810                    let iterator = Iterator {
10811                        object: self.peek(iterator_slot),
10812                        next: self.peek(1 + extra),
10813                    };
10814                    self.iterator_step(&iterator)?
10815                };
10816                if done {
10817                    // The result's `value` is meaningless once the iterator is done:
10818                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10819                    // rather than binding the generator's return value.
10820                    let top = self.frame().stack.len() - 1 - iterator_slot;
10821                    self.frame_mut().stack[top] = Value::Undefined;
10822                    self.push(Value::Undefined);
10823                    self.push(Value::Bool(true));
10824                } else {
10825                    self.push(value);
10826                    self.push(Value::Bool(false));
10827                }
10828            }
10829            IteratorNext => {
10830                // `iter next catch val -> iter next catch val'`: replace the argument with
10831                // the result of `next(val)`. The triple below stays put, which is why the
10832                // three instructions of the `yield*` loop all address the stack the same way.
10833                let value = self.pop();
10834                let object = self.peek(2);
10835                let next = self.peek(1);
10836                let result = self.call_value(next, object, vec![value])?;
10837                self.push(result);
10838            }
10839            IteratorCall => {
10840                // `iter next catch val -> iter next catch val' flag`.
10841                //
10842                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10843                // The flag is `true` when the method was missing, which is how the
10844                // caller learns that the inner iterator cannot take part in the
10845                // unwinding.
10846                let value = self.pop();
10847                let object = self.peek(2);
10848                let key = if a & 1 != 0 { "throw" } else { "return" };
10849                let method = self.read_field(&object, key)?;
10850                if matches!(method, Value::Undefined | Value::Null) {
10851                    self.push(value);
10852                    self.push(Value::Bool(true));
10853                } else {
10854                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10855                    let result = self.call_value(method, object, argument)?;
10856                    self.push(result);
10857                    self.push(Value::Bool(false));
10858                }
10859            }
10860            IteratorCheckObject => {
10861                if !matches!(self.peek(0), Value::Object(_)) {
10862                    return Err(Signal::Throw(
10863                        self.make_error("TypeError", "iterator must return an object"),
10864                    ));
10865                }
10866            }
10867            IteratorClose => {
10868                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10869                // calling the iterator's `return` so it can release whatever it holds.
10870                //
10871                // The catch offset goes first, so an exception from `return` is not caught
10872                // by the loop being abandoned. This used to pop the three operands and call
10873                // nothing at all, which made `break` out of a `for of` invisible to an
10874                // iterator with a `return` method.
10875                self.pop();
10876                self.pop();
10877                let iterator = self.pop();
10878                if !matches!(iterator, Value::Undefined) {
10879                    let method = self.read_field(&iterator, "return")?;
10880                    if !matches!(method, Value::Undefined | Value::Null) {
10881                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10882                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10883                        if !matches!(result, Value::Object(_)) {
10884                            return Err(Signal::Throw(
10885                                self.make_error("TypeError", "iterator must return an object"),
10886                            ));
10887                        }
10888                    }
10889                }
10890            }
10891            Import => {
10892                // `import(specifier)`: the options slot is on top and is not read yet.
10893                let _options = self.pop();
10894                let specifier = self.pop();
10895                let promise = self.dynamic_import(specifier)?;
10896                self.push(promise);
10897            }
10898            ForAwaitOfStart => {
10899                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10900                // `Symbol.iterator` fallback.
10901                let value = self.pop();
10902                let iterator = self.get_async_iterator(&value)?;
10903                self.push(iterator.object);
10904                self.push(iterator.next);
10905                self.push(Value::CatchOffset(0));
10906            }
10907            ForAwaitOfNext => {
10908                // `for await` steps the iterator and leaves the *result* wrapped in a
10909                // promise, so the `await` the compiler emits right after this can suspend
10910                // on it. Unwrapping happens in `iterator_get_value_done`.
10911                let extra = a as usize;
10912                let iterator_slot = 2 + extra;
10913                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10914                    Value::Undefined
10915                } else {
10916                    let iterator = Iterator {
10917                        object: self.peek(iterator_slot),
10918                        next: self.peek(1 + extra),
10919                    };
10920                    let next = iterator.next.clone();
10921                    self.call_value(next, iterator.object, Vec::new())?
10922                };
10923                let promise = self.promise_resolve_value(result)?;
10924                self.push(promise);
10925            }
10926            IteratorGetValueDone => {
10927                // `result -> value done`. A missing result object means the iterator was
10928                // already exhausted, which the loop treats as `done`.
10929                let result = self.pop();
10930                let done = match &result {
10931                    Value::Object(object) => self
10932                        .get_property(object, "done")?
10933                        .is_some_and(|value| value.to_boolean()),
10934                    _ => true,
10935                };
10936                if done {
10937                    // Clear the iterator object so the `iterator_close` the loop emits on
10938                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10939                    // on normal completion, and this is where a normal completion is
10940                    // recognised — the same trick `for_of_next` uses, which also replaces
10941                    // the slot with `undefined`.
10942                    //
10943                    // The layout is fixed because only `for await` emits this opcode:
10944                    // `iter next catch [result]`, so the iterator is three below the top.
10945                    let depth = self.frame().stack.len();
10946                    if depth >= 3 {
10947                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10948                    }
10949                    self.push(Value::Undefined);
10950                    self.push(Value::Bool(true));
10951                } else {
10952                    let Value::Object(object) = &result else {
10953                        self.push(Value::Undefined);
10954                        self.push(Value::Bool(true));
10955                        return Ok(Step::Continue);
10956                    };
10957                    let value = self
10958                        .get_property(object, "value")?
10959                        .unwrap_or(Value::Undefined);
10960                    self.push(value);
10961                    self.push(Value::Bool(false));
10962                }
10963            }
10964
10965            Delete => {
10966                // `delete obj[key]`, where the key was just pushed. Deleting an array
10967                // index leaves a *hole* rather than closing the gap, and a
10968                // non-configurable property answers `false` and stays.
10969                let key = self.pop();
10970                let target = self.pop();
10971                let key = self.propkey(&key)?;
10972                let text_label = key.as_str().unwrap_or("").to_string();
10973                let deleted = match &target {
10974                    Value::Object(object) => {
10975                        let object = object.clone();
10976                        self.delete_property_key(&object, &key)?
10977                    }
10978                    // A string's `length` and its index properties are
10979                    // non-configurable, so deleting one answers `false`.
10980                    Value::String(text) => {
10981                        !(text_label == "length"
10982                            || array_index(&text_label)
10983                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10984                    }
10985                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10986                    // object to delete from, and only a *boxable* primitive has one.
10987                    Value::Undefined | Value::Null => {
10988                        return Err(Signal::Throw(
10989                            self.make_error("TypeError", "cannot convert to object"),
10990                        ));
10991                    }
10992                    // Any other primitive has no own properties; deleting nothing
10993                    // succeeds.
10994                    _ => true,
10995                };
10996                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
10997                // `TypeError` rather than a `false` result. Sloppy mode silently reports
10998                // the refusal, which is why the same statement throws here but not there.
10999                if !deleted && self.current_strict() {
11000                    return Err(Signal::Throw(
11001                        self.make_error("TypeError", "cannot delete property"),
11002                    ));
11003                }
11004                self.push(Value::Bool(deleted));
11005            }
11006
11007            // -- exceptions and bookkeeping ---------------------------------
11008            Fclosure | Fclosure8 => {
11009                let value = self.closure(a as usize)?;
11010                self.push(value);
11011            }
11012
11013            other => {
11014                let name = other.info().name;
11015                return Err(Signal::Throw(self.make_error(
11016                    "InternalError",
11017                    &format!("{name} is not implemented yet"),
11018                )));
11019            }
11020        }
11021        Ok(Step::Continue)
11022    }
11023
11024    // -- operand helpers ----------------------------------------------------
11025
11026    /// The slot index an operand names, taking short forms into account.
11027    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11028        use Opcode::*;
11029        match op {
11030            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11031            | SetVarRef0 => 0,
11032            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11033            | SetVarRef1 => 1,
11034            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11035            | SetVarRef2 => 2,
11036            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11037            | SetVarRef3 => 3,
11038            _ => a as usize,
11039        }
11040    }
11041
11042    /// The argument count of a call, taking `call0`…`call3` into account.
11043    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11044        use Opcode::*;
11045        match op {
11046            Call0 => 0,
11047            Call1 => 1,
11048            Call2 => 2,
11049            Call3 => 3,
11050            _ => a as usize,
11051        }
11052    }
11053
11054    /// The atom's name as a property key.
11055    ///
11056    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11057    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11058    /// `String::clone` was a heap allocation and a copy — per property access.
11059    /// The atom at `index`, as a property key.
11060    ///
11061    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11062    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11063    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11064    /// 5.3% of `property:monomorphic`.
11065    /// The atom's text, exactly — including an unpaired surrogate.
11066    ///
11067    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11068    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11069    /// `atom_text` below is for the other kind of use, where the atom is a key in the
11070    /// engine's own tables.
11071    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11072        self.frame()
11073            .code
11074            .code
11075            .atoms
11076            .get(index)
11077            .map(|atom| match atom {
11078                Atom::Str(text) => text.clone(),
11079                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11080                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11081                Atom::Null => crate::value::Wtf8::new(String::new()),
11082            })
11083            .unwrap_or_default()
11084    }
11085
11086    fn atom_text(&self, index: usize) -> String {
11087        self.frame()
11088            .code
11089            .code
11090            .atoms
11091            .get(index)
11092            .map(|atom| match atom {
11093                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11094                // compare it to an identifier, and a surrogate-bearing name is reachable
11095                // through `atom_wtf8` where it matters.
11096                Atom::Str(text) => text.to_string_lossy().into_owned(),
11097                Atom::Index(value) => value.to_string(),
11098                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11099                // `throw_error`, `delete super.x`) never read it.
11100                Atom::Null => String::new(),
11101            })
11102            .unwrap_or_default()
11103    }
11104
11105    fn constant(&mut self, index: usize) -> JsResult<Value> {
11106        let constant = self.frame().code.code.cpool.get(index).cloned();
11107        Ok(match &constant {
11108            Some(Constant::Number(number)) => Value::Float(*number),
11109            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11110            Some(Constant::BigInt { digits, radix }) => {
11111                match crate::bigint::BigInt::from_radix(digits, *radix) {
11112                    Some(big) => self.bigint(big),
11113                    // A literal the parser accepted is always parseable; a failure here
11114                    // would be a compiler bug, so it reads as an `InternalError`.
11115                    None => {
11116                        return Err(Signal::Throw(
11117                            self.make_error("InternalError", "unparseable bigint literal"),
11118                        ));
11119                    }
11120                }
11121            }
11122            Some(Constant::Function(_)) => {
11123                return Err(Signal::Throw(
11124                    self.make_error("InternalError", "a bare function constant"),
11125                ));
11126            }
11127            // A tagged template's call site: a frozen array of the cooked chunks with a
11128            // frozen `raw` array beside it, which is what `String.raw` reads back.
11129            Some(Constant::Template { cooked, raw }) => {
11130                let cooked_values: Vec<Value> = cooked
11131                    .iter()
11132                    .map(|chunk| match chunk {
11133                        Some(text) => self.string_wtf8(text.clone()),
11134                        None => Value::Undefined,
11135                    })
11136                    .collect();
11137                let raw_values: Vec<Value> =
11138                    raw.iter().map(|text| self.string(text.clone())).collect();
11139                let raw_array = self.new_array(raw_values);
11140                raw_array.set_extensible(false);
11141                let template = self.new_array(cooked_values);
11142                template.define(
11143                    "raw",
11144                    Property::with_attributes(Value::Object(raw_array), false, false),
11145                );
11146                template.set_extensible(false);
11147                Value::Object(template)
11148            }
11149            _ => Value::Undefined,
11150        })
11151    }
11152
11153    /// The reference cell a closure-variable slot names.
11154    ///
11155    /// Two kinds of binding share this addressing: a genuine closure variable
11156    /// (captured from an enclosing function) lives in this frame's environment,
11157    /// while a *declared global* lives in the realm so that a script, a function
11158    /// declaration and their uses all see one binding. A plain `Global` — an
11159    /// undeclared name that may be satisfied by the global object — has no cell at
11160    /// all, which is how `typeof x` still works for a name that does not exist.
11161    /// The reference cell a closure-variable slot names.
11162    ///
11163    /// The environment is resolved once, when the closure is built, and this is
11164    /// just the lookup afterwards. A *declared global* is in there too, pointing at
11165    /// the realm's cell, so a script, a hoisted function declaration and their uses
11166    /// all share one binding. A plain `Global` — a name the script never declared —
11167    /// is read and written through `get_var`/`put_var` by name instead, which is
11168    /// what lets the global object satisfy it.
11169    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11170        self.frame().env.cells.get(slot).cloned()
11171    }
11172
11173    /// Whether `slot` refers to a global binding through the reference table.
11174    ///
11175    /// A global's cell in the closure environment only exists so the slot has
11176    /// something to point at; the binding itself lives on the global object (a `var`)
11177    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11178    /// be routed, not performed on the placeholder.
11179    fn is_global_slot(&self, slot: usize) -> bool {
11180        self.frame()
11181            .code
11182            .code
11183            .closure_vars
11184            .get(slot)
11185            .is_some_and(|c| {
11186                // A module's declarations and imports are *not* globals: their cells are
11187                // the module environment's, filled by the host, so the placeholder routing
11188                // must not apply to them.
11189                matches!(
11190                    c.closure_type,
11191                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11192                )
11193            })
11194    }
11195
11196    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11197        if self.is_global_slot(slot) {
11198            return self.get_global(slot);
11199        }
11200        Ok(self
11201            .var_ref_cell(slot)
11202            .map(|cell| cell.get())
11203            .unwrap_or(Value::Undefined))
11204    }
11205
11206    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11207        // A function declaration is hoisted by storing into a global reference before
11208        // the body runs, so this path is also what puts it on the global object.
11209        if self.is_global_slot(slot) {
11210            return self.put_global(slot, value);
11211        }
11212        if let Some(cell) = self.var_ref_cell(slot) {
11213            cell.set(value);
11214        }
11215        Ok(())
11216    }
11217
11218    // -- closures -----------------------------------------------------------
11219
11220    /// Build the closure for the function constant `index`.
11221    ///
11222    /// Every entry in the child's closure table names where its binding lives in
11223    /// *this* frame: a local or argument slot that was marked captured, or a cell
11224    /// this frame is itself holding. That is how a variable three functions deep
11225    /// stays one binding.
11226    fn closure(&mut self, index: usize) -> JsResult<Value> {
11227        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11228        else {
11229            return Err(Signal::Throw(
11230                self.make_error("InternalError", "fclosure of a non-function"),
11231            ));
11232        };
11233        let mut cells = Vec::with_capacity(function.closure_vars.len());
11234        for closure_var in &function.closure_vars {
11235            let cell = match closure_var.closure_type {
11236                ClosureType::Arg => {
11237                    let slot = closure_var.var_idx as usize;
11238                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11239                }
11240                ClosureType::Local => {
11241                    let slot = closure_var.var_idx as usize;
11242                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11243                }
11244                ClosureType::Ref | ClosureType::GlobalRef => {
11245                    // A `Ref` names a cell in this frame's own closure table; a
11246                    // `GlobalRef` also starts there, then resolves by name below.
11247                    let slot = closure_var.var_idx as usize;
11248                    if let Some(cell) = self.frame().env.cells.get(slot) {
11249                        cells.push(cell.clone());
11250                        continue;
11251                    }
11252                    -1
11253                }
11254                _ => -1,
11255            };
11256            if cell >= 0 {
11257                let cell = self.frame().cells[cell as usize].clone();
11258                cells.push(cell);
11259                continue;
11260            }
11261            // A global: the cell is created on demand and shared through the realm,
11262            // so every function sees one binding.
11263            let name = closure_var.name.clone();
11264            let cell = match self.realm.globals.get(&name) {
11265                Some(cell) => cell.clone(),
11266                None => {
11267                    let cell = self.new_cell(Value::Undefined);
11268                    self.realm.globals.insert(name.clone(), cell.clone());
11269                    cell
11270                }
11271            };
11272            cells.push(cell);
11273        }
11274        let name = function.name.clone();
11275        // `.length` is the arity before any default or rest parameter, not the number
11276        // of slots a pattern parameter needs.
11277        let length = function.defined_args;
11278        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
11279        // function and an arrow function do not. A *method* also does not, but that is not
11280        // known here — the method is marked when the `[[HomeObject]]` is attached (see
11281        // `set_home_object`), which is the moment it becomes a method.
11282        let function_kind = function.kind;
11283        let constructible =
11284            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
11285        let code = Gc::new(self.heap, CompiledCode::new(*function));
11286        // A closure built inside an `eval` inherits the eval's view of the enclosing
11287        // bindings, so it can still read them once the eval has returned.
11288        let eval_scope = self
11289            .active_eval_scope
11290            .clone()
11291            .or_else(|| self.frame().env.eval_scope.clone());
11292        // A closure sees the variables a direct `eval` declared in the frame it was
11293        // created in — the ones declared before *and after* it, so the same object is
11294        // shared; only the phase bounds which of them are visible.
11295        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
11296        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
11297        let env = Gc::new(
11298            self.heap,
11299            ClosureEnv {
11300                cells,
11301                eval_scope,
11302                local_vars,
11303                local_phase,
11304            },
11305        );
11306        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
11307        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
11308        // the only thing that carries `Symbol.toStringTag`, so without it
11309        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
11310        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
11311        let proto = match function_kind {
11312            js_compile::bytecode::FunctionKind::AsyncGenerator => self
11313                .realm
11314                .async_generator_function_proto
11315                .clone()
11316                .or_else(|| self.realm.function_proto.clone().into()),
11317            js_compile::bytecode::FunctionKind::Generator => self
11318                .realm
11319                .generator_function_proto
11320                .clone()
11321                .or_else(|| self.realm.function_proto.clone().into()),
11322            js_compile::bytecode::FunctionKind::Async => self
11323                .realm
11324                .async_function_proto
11325                .clone()
11326                .or_else(|| self.realm.function_proto.clone().into()),
11327            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
11328        };
11329        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
11330        object.set_constructible(constructible);
11331        object.define(
11332            "length",
11333            Property::name_or_length(Value::Int(length as i32)),
11334        );
11335        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
11336        // that checks the own-property descriptor fails if the property is missing.
11337        object.define("name", Property::name_or_length(self.string(name)));
11338        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
11339        // when `[[Construct]]` is created, so a generator, an async function and an arrow
11340        // function have none of their own. Installing it unconditionally gave
11341        // `Array.fromAsync` (an async function) an own `prototype` property, which
11342        // `builtin.js` checks for absence.
11343        if constructible {
11344            self.install_function_prototype(&object);
11345        }
11346        Ok(Value::Object(object))
11347    }
11348
11349    // -- conversions used by the operators ----------------------------------
11350
11351    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
11352        // `+x` is `ToNumber`, which for a string parses it and for an object runs
11353        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
11354        // string, which then behaves differently in every later comparison.
11355        match value {
11356            Value::Int(_) | Value::Float(_) => Ok(value),
11357            other => Ok(Value::Float(self.to_js_number(&other)?)),
11358        }
11359    }
11360
11361    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
11362    ///
11363    /// Returns the *converted* old value and the new one, because the two callers need
11364    /// different halves: `++x` yields the new value, while `x++` yields the old one and
11365    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
11366    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
11367    /// boolean.
11368    ///
11369    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
11370    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
11371    /// a bigint algorithm then ran exactly once.
11372    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
11373        if let Value::BigInt(big) = &value {
11374            let one = crate::bigint::BigInt::from_i64(1);
11375            let next = if up { big.add(&one) } else { big.sub(&one) };
11376            return Ok((value, self.bigint(next)));
11377        }
11378        let old = self.numeric(value)?;
11379        let new = if up {
11380            increment(old.clone())
11381        } else {
11382            decrement(old.clone())
11383        };
11384        Ok((old, new))
11385    }
11386
11387    fn numeric(&mut self, value: Value) -> JsResult<Value> {
11388        // `ToNumber` on an object runs `ToPrimitive` first, which is how
11389        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
11390        // heard at all. Reading the object's own tag instead (`other.to_number()`)
11391        // turned the whole operand into `NaN` and swallowed the exception.
11392        match value {
11393            Value::Int(_) | Value::Float(_) => Ok(value),
11394            other => Ok(Value::Float(self.to_js_number(&other)?)),
11395        }
11396    }
11397
11398    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
11399    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
11400        match value {
11401            Value::BigInt(big) => Ok((**big).clone()),
11402            // The reference words this the same way for every operator, so a failing
11403            // script reads identically; the operator itself adds nothing a caller can use.
11404            _ => Err(Signal::Throw(
11405                self.make_error("TypeError", "cannot convert bigint to number"),
11406            )),
11407        }
11408    }
11409
11410    /// Arithmetic where at least one operand is a `BigInt`.
11411    ///
11412    /// The two numeric types never mix, so a bigint paired with anything else is an error
11413    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
11414    /// that the relational operators handle it separately.
11415    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11416        use Opcode::*;
11417        let a = self.bigint_operand(&left)?;
11418        let b = self.bigint_operand(&right)?;
11419        let result = match op {
11420            Add => a.add(&b),
11421            Sub => a.sub(&b),
11422            Mul => a.mul(&b),
11423            Div | Mod => {
11424                let Some((quotient, remainder)) = a.div_rem(&b) else {
11425                    return Err(Signal::Throw(
11426                        self.make_error("RangeError", "division by zero"),
11427                    ));
11428                };
11429                if op == Div { quotient } else { remainder }
11430            }
11431            Pow => {
11432                let Some(value) = a.pow(&b) else {
11433                    return Err(Signal::Throw(self.make_error(
11434                        "RangeError",
11435                        "BigInt exponent must be non-negative and not absurdly large",
11436                    )));
11437                };
11438                value
11439            }
11440            And => a.bitand(&b),
11441            Or => a.bitor(&b),
11442            Xor => a.bitxor(&b),
11443            Shl | Sar => {
11444                // A shift count is a `BigInt` here, and both directions are exact; a
11445                // negative count would be the other direction, which the spec forbids.
11446                let Some(count) = b.to_i64() else {
11447                    return Err(Signal::Throw(
11448                        self.make_error("RangeError", "BigInt shift count is too large"),
11449                    ));
11450                };
11451                if count < 0 {
11452                    return Err(Signal::Throw(self.make_error(
11453                        "RangeError",
11454                        "BigInt shift count must be non-negative",
11455                    )));
11456                }
11457                if op == Shl {
11458                    a.shl(count as u64)
11459                } else {
11460                    a.shr(count as u64)
11461                }
11462            }
11463            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
11464            _ => {
11465                return Err(Signal::Throw(self.make_error(
11466                    "TypeError",
11467                    "BigInts have no unsigned right shift, use >> instead",
11468                )));
11469            }
11470        };
11471        Ok(self.bigint(result))
11472    }
11473
11474    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
11475    ///
11476    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
11477    /// is on the mathematical values, and nothing is rounded first.
11478    /// `<`, `<=`, `>`, `>=`.
11479    ///
11480    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
11481    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
11482    /// It is a `?`-returning function for exactly that reason: an object operand can run
11483    /// script, and script can throw. The old version compared `to_number` of the raw
11484    /// values, which answered `false` for every object instead of calling `valueOf` —
11485    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
11486    /// never ran.
11487    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11488        // The hot arm first: `i < n` with both sides already integers. No conversion, no
11489        // call, nothing that can throw.
11490        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11491            let ordering = Some(left.cmp(right));
11492            return Ok(ordering_answer(op, ordering));
11493        }
11494        // Anything that can run script has to be converted first, in this order.
11495        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
11496        {
11497            (
11498                self.to_primitive(left, Hint::Number)?,
11499                self.to_primitive(right, Hint::Number)?,
11500            )
11501        } else {
11502            (left, right)
11503        };
11504        let ordering = match (&left, &right) {
11505            // The loop condition `i < n` is integer against integer, and it runs once
11506            // per iteration of every loop in every program. Without this arm it took the
11507            // `to_number` path twice, which is a `match` plus a conversion each.
11508            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
11509            (Value::String(a), Value::String(b)) => {
11510                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
11511            }
11512            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
11513            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
11514            // is true even though `2.5` has no bigint form.
11515            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
11516                let b = other.to_number();
11517                if b.is_nan() {
11518                    None
11519                } else {
11520                    compare_bigint_and_f64(a, b)
11521                }
11522            }
11523            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
11524                let a = other.to_number();
11525                if a.is_nan() {
11526                    None
11527                } else {
11528                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
11529                }
11530            }
11531            _ => left.to_number().partial_cmp(&right.to_number()),
11532        };
11533        Ok(ordering_answer(op, ordering))
11534    }
11535
11536    fn binary_add(&mut self) -> JsResult<()> {
11537        let right = self.pop();
11538        let left = self.pop();
11539        // Two integers add without any of the machinery below: no `ToPrimitive` (an
11540        // `Int` is already primitive), no string check, no bigint check, no allocation.
11541        // `x += 1` in a loop is the single most common instruction sequence in real
11542        // script, and it used to walk every one of those checks before reaching the
11543        // same `checked_add`.
11544        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11545            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
11546            return Ok(());
11547        }
11548        let left = self.primitive_of(left)?;
11549        let right = self.primitive_of(right)?;
11550        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
11551        // that check comes before the bigint one: `"" + 1n` is a string, not a
11552        // mixed-type error.
11553        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
11554            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
11555            // `TypeError`, the one place a symbol and a string do not mix.
11556            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
11557            // between a copy and a rope from their lengths, and a rope is what turns
11558            // `text += "abc"` in a loop from quadratic into linear.
11559            if let (Value::String(left), Value::String(right)) = (&left, &right) {
11560                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
11561                // reports as `InternalError: string too long`.
11562                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
11563                    return Err(Signal::Throw(
11564                        self.make_error("InternalError", "string too long"),
11565                    ));
11566                };
11567                self.push(Value::String(Gc::new(self.heap, joined)));
11568                return Ok(());
11569            }
11570            // At least one operand was not a string, so `ToString` it. This rejects a
11571            // symbol, which is the one place a symbol and a string do not mix.
11572            let left = self.checked_to_wtf8(&left)?;
11573            let right = self.checked_to_wtf8(&right)?;
11574            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
11575            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
11576            let text = left.concat(&right);
11577            self.push(self.string_wtf8(text));
11578            return Ok(());
11579        }
11580        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
11581        // not a conversion.
11582        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11583            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
11584            self.push(value);
11585            return Ok(());
11586        }
11587        let left = self.numeric(left)?;
11588        let right = self.numeric(right)?;
11589        self.push(add_numbers(left, right));
11590        Ok(())
11591    }
11592
11593    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
11594        self.to_primitive(value, Hint::Default)
11595    }
11596
11597    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
11598    ///
11599    /// The order depends on the hint: the "number" order tries `valueOf` first and
11600    /// `toString` second, the "string" order the other way round, and the default
11601    /// hint uses the number order. A result that is still an object is a `TypeError`,
11602    /// because no built-in `valueOf`/`toString` returns one.
11603    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
11604        let Value::Object(object) = &value else {
11605            return Ok(value);
11606        };
11607        // A Date overrides the default hint to mean "string", which is what
11608        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
11609        // this, `"" + new Date()` would print the milliseconds, not the date.
11610        let hint = if hint == Hint::Default && is_date_object(self, object) {
11611            Hint::String
11612        } else {
11613            hint
11614        };
11615        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
11616        // handed the hint as a string. This is the hook a Date uses for its default hint
11617        // and a script uses to take over conversion entirely.
11618        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
11619        // `GetMethod`, not "is it a callable object": the property has to be read and then
11620        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
11621        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
11622        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
11623        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
11624        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
11625        // callable.
11626        match self.get_property_key(object, &key)? {
11627            None | Some(Value::Undefined) | Some(Value::Null) => {}
11628            Some(Value::Object(function)) if function.is_callable() => {
11629                let hint = match hint {
11630                    Hint::String => "string",
11631                    Hint::Number => "number",
11632                    Hint::Default => "default",
11633                };
11634                let hint = self.string(hint);
11635                let result = self.call_value(
11636                    Value::Object(function),
11637                    Value::Object(object.clone()),
11638                    vec![hint],
11639                )?;
11640                if !matches!(result, Value::Object(_)) {
11641                    return Ok(result);
11642                }
11643                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
11644            }
11645            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
11646        }
11647        let order: [&str; 2] = match hint {
11648            Hint::String => ["toString", "valueOf"],
11649            Hint::Number | Hint::Default => ["valueOf", "toString"],
11650        };
11651        let receiver = object.clone();
11652        for method in order {
11653            if let Some(function) = self.get_property(&receiver, method)?
11654                && matches!(&function, Value::Object(object) if object.is_callable())
11655            {
11656                let result =
11657                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
11658                if !matches!(result, Value::Object(_)) {
11659                    return Ok(result);
11660                }
11661            }
11662        }
11663        Err(self.type_error("cannot convert object to primitive value"))
11664    }
11665
11666    /// `ToString` with the object case going through `ToPrimitive`.
11667    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
11668        if matches!(value, Value::Object(_)) {
11669            let primitive = self.to_primitive(value.clone(), Hint::String)?;
11670            return Ok(primitive.to_js_string());
11671        }
11672        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
11673        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
11674        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
11675        // check here broke `String(Symbol())` and 45 cases that print a symbol.
11676        Ok(value.to_js_string())
11677    }
11678
11679    /// `ToString(value)`, with §7.1.19's symbol refusal.
11680    ///
11681    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
11682    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
11683    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
11684    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
11685        if matches!(value, Value::Symbol(_)) {
11686            return Err(self.type_error("cannot convert a Symbol to a string"));
11687        }
11688        if matches!(value, Value::Object(_)) {
11689            let primitive = self.to_primitive(value.clone(), Hint::String)?;
11690            if matches!(primitive, Value::Symbol(_)) {
11691                return Err(self.type_error("cannot convert a Symbol to a string"));
11692            }
11693            return Ok(primitive.to_js_string());
11694        }
11695        Ok(value.to_js_string())
11696    }
11697
11698    /// `ToString` that keeps the string's code units instead of flattening them.
11699    ///
11700    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
11701    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
11702    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11703        if matches!(value, Value::Symbol(_)) {
11704            return Err(Signal::Throw(
11705                self.make_error("TypeError", "cannot convert symbol to string"),
11706            ));
11707        }
11708        // An object runs `ToPrimitive` first, which may itself produce a symbol.
11709        let value = self.to_primitive(value.clone(), Hint::String)?;
11710        match value {
11711            Value::Symbol(_) => Err(Signal::Throw(
11712                self.make_error("TypeError", "cannot convert symbol to string"),
11713            )),
11714            Value::String(text) => Ok(text.wtf8().clone()),
11715            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
11716        }
11717    }
11718
11719    /// `ToNumber` with the object case going through `ToPrimitive`.
11720    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
11721        let value = if matches!(value, Value::Object(_)) {
11722            self.to_primitive(value.clone(), Hint::Number)?
11723        } else {
11724            value.clone()
11725        };
11726        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
11727        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
11728        // `NaN` to stay total, and the operators check for the bigint themselves — but
11729        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
11730        // refuse, and answering `NaN` made them silently wrong instead.
11731        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
11732        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
11733        match value {
11734            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
11735            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
11736            other => Ok(other.to_number()),
11737        }
11738    }
11739
11740    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
11741    /// [`ElementType::write`].
11742    ///
11743    /// This is separated from the write because both conversions are observable script —
11744    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
11745    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
11746    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
11747    /// setters, and a plain `a[i] = v`.
11748    pub(crate) fn element_value(
11749        &mut self,
11750        element: crate::builtins::typedarray::ElementType,
11751        value: Value,
11752    ) -> JsResult<Value> {
11753        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
11754        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
11755        let primitive = match &value {
11756            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
11757            _ => value,
11758        };
11759        if element.is_bigint() {
11760            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
11761            Ok(Value::BigInt(Gc::new(self.heap, big)))
11762        } else {
11763            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
11764            Ok(Value::Float(self.to_js_number(&primitive)?))
11765        }
11766    }
11767
11768    /// `ToPropertyKey`: what a computed member access uses as its key.
11769    ///
11770    /// A symbol is returned as itself, never stringified — that is what keeps
11771    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
11772    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
11773        match value {
11774            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
11775            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
11776            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
11777            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
11778            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11779                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
11780                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
11781                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
11782                    other.to_js_string(),
11783                ))),
11784            },
11785            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
11786        }
11787    }
11788
11789    /// `ToPropertyKey` for the callers that can only use a string key.
11790    ///
11791    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
11792    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
11793    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
11794    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
11795    /// program continues with a value nobody asked for.
11796    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11797        use crate::value::Wtf8;
11798        Ok(match value {
11799            // A string key keeps its code units. Going through a lossy `String` would make
11800            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
11801            Value::String(text) => text.wtf8().clone(),
11802            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
11803            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
11804            // falling back to its `ToString` would print `[object Object]`.
11805            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11806                Value::String(text) => text.wtf8().clone(),
11807                other => Wtf8::new(other.to_js_string()),
11808            },
11809            other => Wtf8::new(other.to_js_string()),
11810        })
11811    }
11812
11813    // -- object operations used by instructions -----------------------------
11814
11815    /// Read `object[key]`, returning `undefined` when the property is missing.
11816    ///
11817    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
11818    /// primitive (looking through its prototype) as well as an object — which is what
11819    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
11820    /// argument needs too.
11821    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
11822        self.read_field_key(object, &PropertyKey::from(key))
11823    }
11824
11825    /// [`Interp::read_field`] with a key that may be a symbol.
11826    ///
11827    /// A symbol key never reaches the string shortcuts: a string's `length` and its
11828    /// indices are string properties, and a symbol named `length` is a different
11829    /// property that a string primitive cannot have.
11830    /// [`Interp::read_field_key`], with an inline cache in front of it.
11831    ///
11832    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11833    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11834    /// without this the engine walked the chain and compared ~40 property names on each
11835    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11836    ///
11837    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11838    /// missing property. Those answers depend on running code or on state the guard below
11839    /// does not cover, and a wrong answer here is far more expensive than a lookup.
11840    ///
11841    /// A hit is re-validated against the *whole* walked chain, not just the level that
11842    /// answered: the receiver and every prototype down to that level must still be the same
11843    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11844    /// property-table *lengths* — which is what catches a property appearing on an
11845    /// intermediate prototype and shadowing the cached one.
11846    pub fn read_field_cached(
11847        &mut self,
11848        object: &Value,
11849        key: &PropertyKey,
11850        slot: usize,
11851    ) -> JsResult<Value> {
11852        let index = Self::field_cache_slot(object, key, slot);
11853        let Value::Object(target) = object else {
11854            return self.read_field_key(object, key);
11855        };
11856        if target.proxy_state().is_some() {
11857            return self.read_field_key(object, key);
11858        }
11859        if let Some(cached) = &self.field_cache[index]
11860            && cached.key == *key
11861            && let Some(value) = Self::cached_hit(target, cached)
11862        {
11863            return Ok(value);
11864        }
11865        let value = self.read_field_key(object, key)?;
11866        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11867        Ok(value)
11868    }
11869
11870    /// Whether a cache entry still describes this lookup, and if so the value.
11871    ///
11872    /// The guard is the whole point of the entry: identity plus property-table length for
11873    /// every level walked. Re-checked per level rather than once at the receiving end,
11874    /// because a shadowing property can appear anywhere along the chain.
11875    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11876        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11877        // starts with: a clone is a reference-count bump and a drop, and for
11878        // `property:monomorphic` every single hit takes only this arm.
11879        let (weak, len) = cached.chain[0].as_ref()?;
11880        if !target.upgrades_to(weak) {
11881            return None;
11882        }
11883        if cached.level == 0 {
11884            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11885            return target.cached_property_at(cached.index, &cached.key, *len);
11886        }
11887        if target.props_len() != *len {
11888            return None;
11889        }
11890        let mut level = 1;
11891        let mut current = target.proto()?;
11892        loop {
11893            let (weak, len) = cached.chain[level].as_ref()?;
11894            if !current.upgrades_to(weak) || current.props_len() != *len {
11895                return None;
11896            }
11897            if level == cached.level as usize {
11898                // The level that answered: the value is only reusable while the key is
11899                // still there and still a plain data property.
11900                return current.cached_data_property(cached.index, &cached.key);
11901            }
11902            current = current.proto()?;
11903            level += 1;
11904        }
11905    }
11906
11907    /// Build a cache entry for a lookup that just went through the slow path.
11908    ///
11909    /// Records the chain only when the answer came from a plain data property at a level
11910    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11911    /// costs the next lookup the walk it would have cost anyway.
11912    fn record_field_lookup(
11913        target: &Gc<JsObject>,
11914        key: &PropertyKey,
11915        _value: Value,
11916    ) -> Option<FieldCache> {
11917        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11918            [None, None, None];
11919        let mut current = target.clone();
11920        for level in 0..MAX_CACHED_CHAIN {
11921            chain[level] = Some((current.downgrade(), current.props_len()));
11922            if let Some((found, _)) = current.own_property_index(key) {
11923                // `own_property_index` declines an accessor and a hole, which is exactly
11924                // the set that must not be cached.
11925                return Some(FieldCache {
11926                    key: key.clone(),
11927                    index: found,
11928                    level: level as u8,
11929                    chain,
11930                });
11931            }
11932            current = current.proto()?;
11933        }
11934        None
11935    }
11936
11937    /// Which cache slot a lookup uses.
11938    ///
11939    /// Mixes the object's address, the name and the site, so that two properties of one
11940    /// object, and one property of two objects, land in different slots — which is what lets
11941    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11942    /// other iteration.
11943    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11944        let mut hash = match object {
11945            Value::Object(object) => object.address(),
11946            _ => 0,
11947        };
11948        hash = hash
11949            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11950            .rotate_left(17)
11951            .wrapping_add(key.hash_code());
11952        hash = hash.wrapping_add(site.wrapping_mul(31));
11953        // The table is a power of two, so the low bits are the slot.
11954        hash & (FIELD_CACHE_SLOTS - 1)
11955    }
11956
11957    /// Read `key` from `object`, without the inline cache.
11958    ///
11959    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11960    /// prototype chain, while the cached form answers an own data property from memory.
11961    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11962        let text = key.as_str().unwrap_or("");
11963        let Value::Object(object) = object else {
11964            // Reading a property of `undefined`/`null` is the classic TypeError.
11965            if object.is_nullish() {
11966                return Err(Signal::Throw(self.make_error(
11967                    "TypeError",
11968                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11969                )));
11970            }
11971            // A string has `length` and index access without being boxed.
11972            if let Value::String(value) = object {
11973                if text == "length" {
11974                    return Ok(Value::Int(value.utf16_len() as i32));
11975                }
11976                if let Some(index) = array_index(text) {
11977                    return Ok(match value.wtf8().unit_at(index as usize) {
11978                        Some(unit) => self.string_wtf8(unit),
11979                        None => Value::Undefined,
11980                    });
11981                }
11982            }
11983            // A property of a primitive is looked up on its prototype: this is what
11984            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11985            let prototype = match object {
11986                Value::String(_) => self.realm.string_proto.clone(),
11987                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11988                Value::Bool(_) => self.realm.boolean_proto.clone(),
11989                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11990                // `sym.description` reads through the prototype, not off the symbol.
11991                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11992                // …and a bigint's on `BigInt.prototype`, which is how
11993                // `(255n).toString(16)` reaches its method.
11994                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11995                _ => None,
11996            };
11997            if let Some(prototype) = prototype
11998                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11999            {
12000                return Ok(value);
12001            }
12002            return Ok(Value::Undefined);
12003        };
12004        Ok(self
12005            .get_property_key(object, key)?
12006            .unwrap_or(Value::Undefined))
12007    }
12008
12009    /// The `#name` a private symbol stands for, for error messages.
12010    ///
12011    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12012    /// was made from.
12013    fn private_name(symbol: &Value) -> Option<String> {
12014        match symbol {
12015            Value::Symbol(symbol) if symbol.is_private() => Some(
12016                symbol
12017                    .description()
12018                    .map(|text| text.to_string())
12019                    .unwrap_or_default(),
12020            ),
12021            _ => None,
12022        }
12023    }
12024
12025    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12026    ///
12027    /// Every private-field opcode takes the symbol the class stored in its own scope; a
12028    /// non-symbol here would be a compiler bug, and the reference guards it with
12029    /// `JS_ThrowTypeErrorNotASymbol`.
12030    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12031        match symbol {
12032            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12033            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12034        }
12035    }
12036
12037    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12038    ///
12039    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12040    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12041    /// would hit if the parser did not reject it first.
12042    fn define_private_field(
12043        &mut self,
12044        object: &Value,
12045        symbol: &Value,
12046        value: Value,
12047    ) -> JsResult<()> {
12048        let key = self.private_key(symbol)?;
12049        let Some(target) = object.as_object() else {
12050            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12051        };
12052        if !target.is_extensible() {
12053            return Err(Signal::Throw(
12054                self.make_error("TypeError", "object is not extensible"),
12055            ));
12056        }
12057        if target.own_property_key(&key).is_some() {
12058            let name = Self::private_name(symbol).unwrap_or_default();
12059            return Err(Signal::Throw(self.make_error(
12060                "TypeError",
12061                &format!("private class field '{name}' already exists"),
12062            )));
12063        }
12064        target.define_data_key(&key, value);
12065        Ok(())
12066    }
12067
12068    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12069    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12070        let key = self.private_key(symbol)?;
12071        let Some(target) = object.as_object() else {
12072            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12073        };
12074        match target.own_property_key(&key) {
12075            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12076            None => {
12077                let name = Self::private_name(symbol).unwrap_or_default();
12078                Err(Signal::Throw(self.make_error(
12079                    "TypeError",
12080                    &format!("private class field '{name}' does not exist"),
12081                )))
12082            }
12083        }
12084    }
12085
12086    /// `JS_SetPrivateField`: the store half of the same rule.
12087    fn write_private_field(
12088        &mut self,
12089        object: &Value,
12090        symbol: &Value,
12091        value: Value,
12092    ) -> JsResult<()> {
12093        let key = self.private_key(symbol)?;
12094        let Some(target) = object.as_object() else {
12095            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12096        };
12097        if target.write_value_key(&key, value) {
12098            return Ok(());
12099        }
12100        let name = Self::private_name(symbol).unwrap_or_default();
12101        Err(Signal::Throw(self.make_error(
12102            "TypeError",
12103            &format!("private class field '{name}' does not exist"),
12104        )))
12105    }
12106
12107    /// The `in` half: does `object` have this private field?
12108    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12109    ///
12110    /// The symbol is created once per class — the first `add_brand` on a given home object
12111    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12112    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12113    /// emit for the *instance* brand passes null because all it wants is the symbol.
12114    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12115        let Some(home_object) = home.as_object() else {
12116            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12117        };
12118        let symbol = match home_object.private_brand() {
12119            Some(symbol) => symbol,
12120            None => {
12121                let symbol = Gc::new(
12122                    self.heap,
12123                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
12124                );
12125                home_object.set_private_brand(symbol.clone());
12126                symbol
12127            }
12128        };
12129        let Some(target) = object.as_object() else {
12130            // Not an object: nothing to brand. The reference does the same, and `undefined`
12131            // here would otherwise turn a field initialiser into a TypeError.
12132            return Ok(());
12133        };
12134        if !target.is_extensible() {
12135            return Err(Signal::Throw(
12136                self.make_error("TypeError", "object is not extensible"),
12137            ));
12138        }
12139        if target.carries_brand(&symbol) {
12140            return Err(Signal::Throw(
12141                self.make_error("TypeError", "private method is already present"),
12142            ));
12143        }
12144        target.add_brand(symbol);
12145        Ok(())
12146    }
12147
12148    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12149    ///
12150    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12151    /// decides whether to throw.
12152    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12153        let Some(function) = function.as_object() else {
12154            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12155        };
12156        let Some(home) = function.home_object() else {
12157            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12158        };
12159        let Some(brand) = home.private_brand() else {
12160            return Err(Signal::Throw(
12161                self.make_error("TypeError", "expecting <brand> private field"),
12162            ));
12163        };
12164        Ok(object.carries_brand(&brand))
12165    }
12166
12167    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12168        let Value::Object(object) = object else {
12169            return Err(Signal::Throw(self.make_error(
12170                "TypeError",
12171                &format!("cannot set property '{key}' of {}", object.to_js_string()),
12172            )));
12173        };
12174        // The write half of the property inline cache, in effect: an own, writable,
12175        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12176        // decide — no prototype walk (an own property shadows the chain before a setter
12177        // there could matter), no extensibility check (the object already has the key),
12178        // and no `[[DefineOwnProperty]]`.
12179        //
12180        // `this.value = …` inside a method is the whole write side of
12181        // `property:method-call`, and it was reaching `set_property_with_key` with its
12182        // proxy test, its typed-array test, its array-index test and finally a linear
12183        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12184        //
12185        // Every disqualifier is checked here: a proxy traps the set, an array index and
12186        // `length` live outside the property table, and a typed array's element is stored
12187        // through its view's element type.
12188        if object.proxy_state().is_none()
12189            && !object.is_array()
12190            && object.typed_array_element_type().is_none()
12191            && object.write_value_key(key, value.clone())
12192        {
12193            return Ok(());
12194        }
12195        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12196        let on_failure = if self.frame().code.code.strict {
12197            DeleteFailure::Throw
12198        } else {
12199            DeleteFailure::Ignore
12200        };
12201        self.set_property_with_key(object, key, value, on_failure)
12202    }
12203
12204    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12205    ///
12206    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12207    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12208    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12209    /// `Number.parseInt(sym)` — so those callers use this instead.
12210    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12211        if matches!(value, Value::Symbol(_)) {
12212            return Err(Signal::Throw(
12213                self.make_error("TypeError", "cannot convert symbol to string"),
12214            ));
12215        }
12216        // An object runs `ToPrimitive` first, which may itself produce a symbol —
12217        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12218        let value = self.to_primitive(value.clone(), Hint::String)?;
12219        if matches!(value, Value::Symbol(_)) {
12220            return Err(Signal::Throw(
12221                self.make_error("TypeError", "cannot convert symbol to string"),
12222            ));
12223        }
12224        Ok(value.to_js_string())
12225    }
12226
12227    /// `ToPropertyKey` for a builtin that takes a key argument.
12228    ///
12229    /// Fallible: a key whose `toString` throws has to propagate that error, both for
12230    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12231    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12232    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12233    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12234        self.propkey(value)
12235    }
12236
12237    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12238    ///
12239    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12240    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12241    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12242    /// `RangeError` — and why this cannot be a plain `ToNumber`.
12243    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
12244        let number = match value {
12245            Value::Int(number) => *number as f64,
12246            Value::Float(number) => *number,
12247            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
12248            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
12249            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
12250            // reference answers 0.
12251            Value::Null | Value::Bool(_) => value.to_number(),
12252            _ => {
12253                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
12254                match primitive {
12255                    Value::Int(number) => number as f64,
12256                    Value::Float(number) => number,
12257                    other => {
12258                        // `ToString` then `ToNumber`, so a string length goes through the
12259                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
12260                        // `Value::to_number` on the string already implements exactly that.
12261                        let text = self.to_js_string(&other)?;
12262                        crate::value::string_to_number(&text)
12263                    }
12264                }
12265            }
12266        };
12267        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
12268        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
12269        // is a `RangeError`, not `0`.
12270        if !number.is_finite()
12271            || number.fract() != 0.0
12272            || !(0.0..=u32::MAX as f64).contains(&number)
12273        {
12274            return Err(self.range_error("invalid array length"));
12275        }
12276        Ok(number as u32)
12277    }
12278
12279    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
12280    /// `Object.getOwnPropertySymbols` put in their result array.
12281    pub fn key_value(&self, key: &PropertyKey) -> Value {
12282        match key {
12283            PropertyKey::String(text) => self.string_wtf8(text.clone()),
12284            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12285        }
12286    }
12287
12288    /// Fill in a String exotic object: `_value`, `length` and the index properties.
12289    ///
12290    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
12291    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
12292    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
12293    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
12294    /// the two paths had drifted; this is the one both now use.
12295    ///
12296    /// The indices are *code units*, so an astral character occupies two of them — the
12297    /// same rule `s.length` and `s[i]` follow.
12298    /// Give an already-created object the internal slot that makes it a wrapper of
12299    /// `value`, so the primitive's prototype methods work on it.
12300    ///
12301    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
12302    /// which are wrappers of their own type holding the empty value.
12303    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
12304        self.internal_set(object, "_value", value);
12305    }
12306
12307    pub(crate) fn init_string_wrapper(
12308        &mut self,
12309        object: &Gc<JsObject>,
12310        text: &Gc<crate::value::JsString>,
12311    ) {
12312        object.define(
12313            "length",
12314            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
12315        );
12316        for index in 0..text.utf16_len() {
12317            if let Some(unit) = text.wtf8().unit_at(index) {
12318                object.define(
12319                    &index.to_string(),
12320                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
12321                    Property::with_attributes(self.string_wtf8(unit), false, true),
12322                );
12323            }
12324        }
12325        object.define_key(
12326            &self.internal_slot("_value"),
12327            Property::with_attributes(Value::String(text.clone()), false, false),
12328        );
12329    }
12330
12331    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
12332    ///
12333    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
12334    /// throws. The wrapper carries its primitive in `_value` — the same slot
12335    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
12336    /// on a boxed value no constructor ever built.
12337    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12338        let (prototype, primitive) = match value {
12339            Value::Object(object) => return Ok(object.clone()),
12340            Value::String(text) => {
12341                let object = self.new_object(self.realm.string_proto.clone());
12342                self.init_string_wrapper(&object, text);
12343                return Ok(object);
12344            }
12345            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
12346            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
12347            // A symbol and a bigint box into wrappers whose methods live on
12348            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
12349            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
12350            // branch below instead produced an object with *no* prototype, so those
12351            // methods were unreachable on a box.
12352            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
12353            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
12354            Value::Undefined | Value::Null => {
12355                return Err(Signal::Throw(self.make_error(
12356                    "TypeError",
12357                    &format!("cannot convert {} to object", value.to_js_string()),
12358                )));
12359            }
12360            _ => (None, value.clone()),
12361        };
12362        let object = self.new_object(prototype);
12363        self.internal_set(&object, "_value", primitive);
12364        Ok(object)
12365    }
12366
12367    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
12368    ///
12369    /// Split out for a reader that has to create the object *before* it knows what it wraps:
12370    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
12371    /// written before its primitive, so the placeholder has to exist first and be filled in
12372    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
12373    /// than a second in the deserialiser.
12374    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
12375        let prototype = match value {
12376            Value::String(_) => self.realm.string_proto.clone(),
12377            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12378            Value::Bool(_) => self.realm.boolean_proto.clone(),
12379            Value::Symbol(_) => self.realm.symbol_proto.clone(),
12380            Value::BigInt(_) => self.realm.bigint_proto.clone(),
12381            _ => {
12382                return Err(Signal::Throw(self.make_error(
12383                    "TypeError",
12384                    &format!("cannot box {}", value.to_js_string()),
12385                )));
12386            }
12387        };
12388        object.set_proto(prototype);
12389        if let Value::String(text) = value {
12390            self.init_string_wrapper(object, text);
12391            return Ok(());
12392        }
12393        self.internal_set(object, "_value", value.clone());
12394        Ok(())
12395    }
12396
12397    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
12398    ///
12399    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
12400    /// through the `Symbol` function object, so the registry is reachable as a method rather
12401    /// than only from `builtins::symbol`.
12402    pub fn symbol_for(&mut self, key: &str) -> Value {
12403        if let Some(existing) = self.realm.symbol_registry.get(key) {
12404            return existing.clone();
12405        }
12406        let symbol = crate::builtins::symbol::symbol_value(
12407            self,
12408            crate::value::JsSymbol::registered(key.to_string()),
12409        );
12410        self.realm
12411            .symbol_registry
12412            .insert(key.to_string(), symbol.clone());
12413        symbol
12414    }
12415
12416    /// `a == b`, the coercing comparison.
12417    ///
12418    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
12419    /// which is what makes `[] == ""` true: `[]` becomes `""` via
12420    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
12421    /// because the conversion is allowed to call script code, so the two primitive
12422    /// operands are handed back to it.
12423    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
12424        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
12425            return Ok(left.loose_equals(&right));
12426        }
12427        // `null == undefined` holds even though neither is an object.
12428        if matches!(left, Value::Undefined | Value::Null)
12429            && matches!(right, Value::Undefined | Value::Null)
12430        {
12431            return Ok(true);
12432        }
12433        if matches!(left, Value::Undefined | Value::Null)
12434            || matches!(right, Value::Undefined | Value::Null)
12435        {
12436            return Ok(false);
12437        }
12438        // Two objects compare by identity. Only an object *against a primitive* is
12439        // converted, which is why `{} == {}` is false while `[] == ""` is true.
12440        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
12441            return Ok(a.ptr_eq(b));
12442        }
12443        let left = self.to_primitive(left, Hint::Default)?;
12444        let right = self.to_primitive(right, Hint::Default)?;
12445        Ok(left.loose_equals(&right))
12446    }
12447
12448    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
12449        let Value::Object(object) = object else {
12450            return Err(Signal::Throw(
12451                self.make_error("TypeError", "cannot use 'in' on a non-object"),
12452            ));
12453        };
12454        let key = self.propkey(key)?;
12455        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
12456        // trap. One implementation, so an array's derived `length` and its inherited holes
12457        // cannot be right in one caller and wrong in another.
12458        self.has_own_or_inherited(object, &key)
12459    }
12460
12461    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
12462    ///
12463    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
12464    /// whole reason the operator is a hook rather than a prototype walk.
12465    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12466        if let Value::Object(function) = constructor {
12467            let key = self.realm.well_known_key(WellKnown::HasInstance);
12468            let method = self.get_property_key(function, &key)?;
12469            if let Some(method) = method
12470                && !matches!(method, Value::Undefined)
12471            {
12472                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
12473                return Ok(answer.to_boolean());
12474            }
12475        }
12476        self.instance_of(object, constructor)
12477    }
12478
12479    /// `OrdinaryHasInstance`: the prototype walk on its own.
12480    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12481        self.instance_of(object, constructor)
12482    }
12483
12484    /// `IsArray`: an array, or a proxy whose target is one.
12485    ///
12486    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
12487    /// makes `Array.isArray(new Proxy([], {}))` true.
12488    pub fn is_array_value(&self, value: &Value) -> bool {
12489        match value {
12490            Value::Object(object) => {
12491                if let Some(state) = object.proxy_state() {
12492                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
12493                }
12494                object.is_array()
12495            }
12496            _ => false,
12497        }
12498    }
12499
12500    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
12501    ///
12502    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
12503    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
12504    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
12505    /// see [`Interp::enqueue_job_function`].
12506    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
12507        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
12508        // the handler is reported rather than lost — the same reason a `then` reaction needs a
12509        // promise to settle.
12510        let promise = self.new_promise();
12511        self.fulfill_promise(&promise, Value::Undefined);
12512        self.jobs.push_back(Job::Reaction {
12513            handler: Some(function),
12514            argument: Value::Undefined,
12515            rejected: false,
12516            promise,
12517        });
12518        Ok(())
12519    }
12520
12521    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12522        let Value::Object(target) = object else {
12523            return Ok(false);
12524        };
12525        let Value::Object(function) = constructor else {
12526            return Err(Signal::Throw(self.make_error(
12527                "TypeError",
12528                "right-hand side of 'instanceof' is not callable",
12529            )));
12530        };
12531        let prototype = self.get_property(function, "prototype")?;
12532        let Some(Value::Object(prototype)) = prototype else {
12533            return Ok(false);
12534        };
12535        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
12536        // which is also what makes `proxyOfInstance instanceof C` work.
12537        let mut current = Some(target.clone());
12538        while let Some(object) = current {
12539            if object.ptr_eq(&prototype) {
12540                return Ok(true);
12541            }
12542            current = self.object_prototype_of(&object)?;
12543        }
12544        Ok(false)
12545    }
12546
12547    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
12548    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
12549        if let Some(proto) = self.proxy_get_prototype_of(object)? {
12550            return Ok(proto);
12551        }
12552        if let Some(exotic) = object.exotic()
12553            && let Some(proto) = exotic.get_prototype(self, object)?
12554        {
12555            return Ok(proto);
12556        }
12557        Ok(object.proto())
12558    }
12559
12560    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
12561    pub fn object_set_prototype_of(
12562        &mut self,
12563        object: &Gc<JsObject>,
12564        proto: Option<Gc<JsObject>>,
12565    ) -> JsResult<bool> {
12566        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
12567            return Ok(answer);
12568        }
12569        if let Some(exotic) = object.exotic()
12570            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
12571        {
12572            return Ok(answer);
12573        }
12574        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
12575        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
12576        // inheriting from itself, which every later prototype walk then had to defend
12577        // against — and `Reflect.setPrototypeOf` reported success for an operation the
12578        // language says is impossible.
12579        if let Some(proto) = &proto {
12580            let mut current = Some(proto.clone());
12581            let mut guard = 0;
12582            while let Some(node) = current {
12583                if node.ptr_eq(object) {
12584                    return Err(Signal::Throw(
12585                        self.make_error("TypeError", "circular prototype chain"),
12586                    ));
12587                }
12588                guard += 1;
12589                if guard > 1000 {
12590                    break;
12591                }
12592                current = node.proto();
12593            }
12594        }
12595        object.set_proto(proto);
12596        Ok(true)
12597    }
12598
12599    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
12600    ///
12601    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
12602    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
12603    /// already one.
12604    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
12605        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
12606        // (§10.4.5.2 step 1.b) — the prototype chain is *not* consulted for a canonical
12607        // numeric index. That is observable twice over: a view that has been resized out
12608        // of bounds has no indices, so `2 in view` must then be `false` even when
12609        // `Object.getPrototypeOf(view)[2]` exists, and a key like `"-1"` or `"1.5"` is
12610        // canonical-numeric-but-invalid, so `in` answers `false` where an ordinary
12611        // lookup would have found `TypedArray.prototype["1.5"]`. A proxy is excluded
12612        // because it has no `[[ViewedArrayBuffer]]` slot of its own.
12613        if object.typed_array_parts().is_some()
12614            && object.proxy_state().is_none()
12615            && let Some(numeric) = canonical_numeric_index(key)
12616        {
12617            return Ok(typed_array_index_is_valid(object, numeric));
12618        }
12619        let mut current = Some(object.clone());
12620        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
12621        let mut guard = 0;
12622        while let Some(node) = current {
12623            guard += 1;
12624            if guard > 1000 {
12625                return Ok(false);
12626            }
12627            let own = self.object_get_own_property(&node, key)?;
12628            if own.is_some() {
12629                return Ok(true);
12630            }
12631            current = self.object_prototype_of(&node)?;
12632        }
12633        Ok(false)
12634    }
12635
12636    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
12637    ///
12638    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
12639    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
12640    /// boolean as well, and it needs the receiver to be the one the caller named.
12641    pub fn set_property_with_key_receiver(
12642        &mut self,
12643        object: &Gc<JsObject>,
12644        key: &PropertyKey,
12645        value: Value,
12646        receiver: Option<&Value>,
12647        on_failure: DeleteFailure,
12648    ) -> JsResult<bool> {
12649        let receiver = receiver
12650            .cloned()
12651            .unwrap_or_else(|| Value::Object(object.clone()));
12652        if object.proxy_state().is_some() {
12653            return match self.proxy_set(object, key, value, &receiver)? {
12654                Some(accepted) => Ok(accepted),
12655                None => Ok(true),
12656            };
12657        }
12658        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
12659        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
12660        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
12661        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
12662        //
12663        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
12664        //
12665        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
12666        // * an *invalid* index with a different receiver answers `true` and does nothing,
12667        //   not even converting `V` (`valueOfCalls` stays 0);
12668        // * a valid index with a different receiver falls through to
12669        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
12670        //   value lands on the **receiver**, unconverted, and can be refused by a
12671        //   non-extensible receiver, an accessor, or a read-only index there.
12672        //
12673        // The last one used to write into the view itself, which left `target[0]` changed
12674        // and `receiver[0]` untouched — backwards.
12675        if object.typed_array_element_type().is_some()
12676            && let Some(numeric) = canonical_numeric_index(key)
12677        {
12678            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12679            if same {
12680                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
12681                return Ok(true);
12682            }
12683            if !typed_array_index_is_valid(object, numeric) {
12684                return Ok(true);
12685            }
12686            let Some(receiver) = receiver.as_object().cloned() else {
12687                return Ok(false);
12688            };
12689            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
12690                if existing.is_accessor() || !existing.writable {
12691                    return Ok(false);
12692                }
12693                let property = Property {
12694                    value: Some(value),
12695                    ..existing
12696                };
12697                return self.object_define_own_property(&receiver, key, property);
12698            }
12699            return self.object_define_own_property(&receiver, key, Property::data(value));
12700        }
12701        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
12702        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
12703        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
12704        // `Reflect.set` to *report* the refusal instead of raising.
12705        //
12706        // A receiver that is not the object turns the whole operation into
12707        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
12708        // `[[Set]]` rather than a lookup — that is what makes
12709        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
12710        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
12711        // writes to `object`, so it cannot express that and is only used when the two are
12712        // the same.
12713        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12714        if !same {
12715            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
12716        }
12717        // Same receiver: the plain path below writes into `object`, which is right, but it
12718        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
12719        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
12720        if let Some(existing) = self.object_get_own_property(object, key)? {
12721            if existing.is_accessor() {
12722                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
12723                    Some(setter) => {
12724                        self.call_value(setter, receiver, vec![value])?;
12725                        Ok(true)
12726                    }
12727                    None => Ok(false),
12728                };
12729            }
12730            if !existing.writable {
12731                return Ok(false);
12732            }
12733        }
12734        // Otherwise it is an ordinary create-or-write into `object` itself.
12735        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
12736        Ok(true)
12737    }
12738
12739    /// `[[IsExtensible]]`, with the proxy trap when there is one.
12740    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12741        if let Some(answer) = self.proxy_is_extensible(object)? {
12742            return Ok(answer);
12743        }
12744        if let Some(exotic) = object.exotic()
12745            && let Some(answer) = exotic.is_extensible(self, object)?
12746        {
12747            return Ok(answer);
12748        }
12749        Ok(object.is_extensible())
12750    }
12751
12752    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
12753    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12754        if let Some(answer) = self.proxy_prevent_extensions(object)? {
12755            return Ok(answer);
12756        }
12757        if let Some(exotic) = object.exotic()
12758            && let Some(answer) = exotic.prevent_extensions(self, object)?
12759        {
12760            return Ok(answer);
12761        }
12762        object.set_extensible(false);
12763        Ok(true)
12764    }
12765
12766    fn copy_properties(
12767        &mut self,
12768        target: &Value,
12769        source: &Value,
12770        exclusion: &Value,
12771    ) -> JsResult<()> {
12772        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
12773        // does contribute: its index properties are own, enumerable and writable, which
12774        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
12775        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
12776        // is a no-op.
12777        let Some(target) = target.as_object() else {
12778            return Ok(());
12779        };
12780        let source_object = match source {
12781            Value::Object(object) => object.clone(),
12782            Value::String(text) => {
12783                // Untaken keys are the string's indices, which are code units.
12784                for index in 0..text.utf16_len() {
12785                    if let Some(unit) = text.wtf8().unit_at(index) {
12786                        target.define_data(&index.to_string(), self.string_wtf8(unit));
12787                    }
12788                }
12789                return Ok(());
12790            }
12791            _ => return Ok(()),
12792        };
12793        // An object *rest* element passes the keys already taken by the literal part as
12794        // an array of strings; a spread passes `null`, which excludes nothing. Only the
12795        // string keys of the exclusion array are meaningful, so an array is read by its
12796        // elements rather than by its own property names.
12797        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
12798        if let Value::Object(list) = exclusion
12799            && let Some(length) = list.array_length()
12800        {
12801            for index in 0..length {
12802                if let Some(value) = list.array_get(index) {
12803                    excluded.push(self.propkey_of(&value)?);
12804                }
12805            }
12806        }
12807        let source = &source_object;
12808        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
12809        // Reading the property table directly made every spread of a proxy empty.
12810        let keys = self.object_own_property_keys(source)?;
12811        for as_key in keys {
12812            if as_key.is_symbol() {
12813                // A spread copies string-keyed properties only.
12814                continue;
12815            }
12816            if excluded.contains(&crate::value::Wtf8::new(
12817                as_key.as_str().unwrap_or_default(),
12818            )) {
12819                continue;
12820            }
12821            let enumerable = self
12822                .object_get_own_property(source, &as_key)?
12823                .is_some_and(|property| property.enumerable);
12824            if !enumerable {
12825                continue;
12826            }
12827            let value = self
12828                .get_property_key(source, &as_key)?
12829                .unwrap_or(Value::Undefined);
12830            target.define_data_key(&as_key, value);
12831        }
12832        Ok(())
12833    }
12834
12835    // -- iteration ---------------------------------------------------------
12836
12837    /// One object's own keys in enumeration order: array indices ascending, then the
12838    /// rest in insertion order.
12839    ///
12840    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
12841    /// whether the key is enumerable, which the caller resolves per key because an
12842    /// array's elements are not in the same store as its named properties.
12843    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
12844        // An index can arrive twice, once from the array's element store and once from
12845        // its property map, so the numeric keys go through a map that keeps the
12846        // enumerable answer if either source gave one.
12847        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
12848        for (key, enumerable) in &own {
12849            if let Some(index) = key.as_str().and_then(array_index) {
12850                let entry = numeric.entry(index).or_insert(false);
12851                *entry = *entry || *enumerable;
12852            }
12853        }
12854        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12855            .into_iter()
12856            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12857            .collect();
12858        ordered.extend(
12859            own.into_iter()
12860                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12861        );
12862        ordered
12863    }
12864
12865    /// Build the key list a `for-in` loop walks.
12866    ///
12867    /// The order is the specification's: own properties before inherited ones, and
12868    /// within one object the integer-like keys in ascending numeric order ahead of the
12869    /// string keys in insertion order. A shadowed key only appears once, and a key that
12870    /// is a non-enumerable own property anywhere nearer is skipped entirely.
12871    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12872        let record = self.new_object(None);
12873        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12874        // A proxy supplies its own key list, and — the reason this is not just another
12875        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12876        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12877        // descriptor there.
12878        if let Value::Object(object) = value
12879            && object.proxy_state().is_some()
12880        {
12881            let own = self
12882                .proxy_own_keys(object)?
12883                .unwrap_or_else(|| object.own_property_keys());
12884            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12885            let mut numeric: Vec<u32> = Vec::new();
12886            let mut rest: Vec<PropertyKey> = Vec::new();
12887            for key in own {
12888                match key.as_str().and_then(array_index) {
12889                    Some(index) => numeric.push(index),
12890                    None => rest.push(key),
12891                }
12892            }
12893            numeric.sort_unstable();
12894            ordered.extend(
12895                numeric
12896                    .into_iter()
12897                    .map(|index| PropertyKey::from(index.to_string())),
12898            );
12899            ordered.extend(rest);
12900            for (index, key) in ordered.into_iter().enumerate() {
12901                record.define_data(&index.to_string(), self.key_value(&key));
12902            }
12903            record.define_data("__index", Value::Int(0));
12904            // The mark that makes `for_in_advance` re-ask the proxy per key.
12905            record.define_data("__proxy", Value::Object(object.clone()));
12906            return Ok(record);
12907        }
12908        if let Value::Object(object) = value {
12909            let mut chain = vec![object.clone()];
12910            chain.extend(object.chain());
12911            // Every own string key the walk has seen, enumerable or not. A
12912            // non-enumerable own property still hides a same-named enumerable one
12913            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12914            // keeps `x` out of the loop even when the prototype has one.
12915            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12916            for object in chain {
12917                let mut own: Vec<(crate::value::Wtf8, bool)> = object
12918                    .own_property_keys()
12919                    .iter()
12920                    .filter_map(|key| key.as_wtf8().cloned())
12921                    .map(|key| {
12922                        let enumerable = object
12923                            .own_property(&key.to_string_lossy())
12924                            .map(|property| property.enumerable)
12925                            .unwrap_or(false);
12926                        (key, enumerable)
12927                    })
12928                    .collect();
12929                if let Some(length) = object.array_length() {
12930                    own.retain(|(key, _)| key.as_str() != Some("length"));
12931                    for index in 0..length {
12932                        if object.array_get(index).is_some() {
12933                            own.push((crate::value::Wtf8::new(index.to_string()), true));
12934                        }
12935                    }
12936                }
12937                // Integer-like keys come first in ascending order, then the rest in
12938                // insertion order — and the ordering is *per object*, not for the chain
12939                // as a whole: one pass over every collected key lifted a prototype's
12940                // `"4"` above the target's own `x`/`y`, which is not the order
12941                // `for…in` reports.
12942                for (key, enumerable) in Self::order_own_keys(own) {
12943                    if visited.contains(&key) {
12944                        continue;
12945                    }
12946                    visited.push(key.clone());
12947                    if enumerable {
12948                        keys.push(key);
12949                    }
12950                }
12951            }
12952        }
12953        for (index, key) in keys.into_iter().enumerate() {
12954            record.define_data(&index.to_string(), self.string_wtf8(key));
12955        }
12956        record.define_data("__index", Value::Int(0));
12957        Ok(record)
12958    }
12959
12960    /// The next key of a `for…in` record, `None` when the loop is done.
12961    ///
12962    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12963    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12964    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12965    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12966    /// key the handler had already withdrawn.
12967    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12968        let Value::Object(record) = record else {
12969            return Ok(None);
12970        };
12971        let proxy = record
12972            .own_property("__proxy")
12973            .and_then(|property| property.value);
12974        loop {
12975            let index = record
12976                .own_property("__index")
12977                .and_then(|property| property.value)
12978                .map(|value| value.to_int32())
12979                .unwrap_or(0);
12980            let Some(candidate) = record
12981                .own_property(&index.to_string())
12982                .and_then(|property| property.value)
12983            else {
12984                return Ok(None);
12985            };
12986            record.define_data("__index", Value::Int(index + 1));
12987            let text = candidate.to_js_string();
12988            let Some(Value::Object(proxy)) = &proxy else {
12989                return Ok(Some(text));
12990            };
12991            // The candidate is already a key string here, so the lookup does not need a
12992            // second `ToPropertyKey` conversion.
12993            let key = PropertyKey::from(text.as_str());
12994            let live = match self.proxy_get_own_property(proxy, &key)? {
12995                Some(descriptor) => descriptor,
12996                // Not a proxy after all, or it lost its state: fall back to the target.
12997                None => proxy.own_property_key(&key),
12998            };
12999            if live.is_some_and(|property| property.enumerable) {
13000                return Ok(Some(text));
13001            }
13002            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13003            // next one.
13004        }
13005    }
13006
13007    /// The iterator for `for-of`: the object and its `next` method.
13008    ///
13009    /// An object that already carries a `next` method is used as it is — that is what
13010    /// `arr.values()` returns — and only arrays and strings get the built-in
13011    /// sequence iterator.
13012    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13013    ///
13014    /// Callers that must choose between the iterable and the array-like protocol — the
13015    /// typed-array constructor is the main one — need to ask *before* committing to one.
13016    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13017        let key = self.realm.well_known_key(WellKnown::Iterator);
13018        let method = self.read_field_key(value, &key)?;
13019        if matches!(method, Value::Undefined | Value::Null) {
13020            return Ok(false);
13021        }
13022        if !matches!(&method, Value::Object(object) if object.is_callable()) {
13023            return Err(Signal::Throw(
13024                self.make_error("TypeError", "Symbol.iterator is not callable"),
13025            ));
13026        }
13027        Ok(true)
13028    }
13029
13030    /// Collect everything an iterable yields.
13031    ///
13032    /// The cap is a guard against a generator that never ends: an unbounded collect would
13033    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13034    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13035    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13036    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13037        const MAX_ITEMS: usize = 1 << 24;
13038        let iterator = self.get_iterator(value)?;
13039        let mut out = Vec::new();
13040        loop {
13041            let (element, done) = self.iterator_step(&iterator)?;
13042            if done {
13043                return Ok(out);
13044            }
13045            out.push(element);
13046            if out.len() > MAX_ITEMS {
13047                // Close before refusing: the walk is being abandoned, so the iterator's
13048                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
13049                // unrun and a locked resource unreleased.
13050                self.close_iterator_after_throw(&iterator)?;
13051                return Err(self.range_error("iterable is too long to collect"));
13052            }
13053        }
13054    }
13055
13056    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
13057    ///
13058    /// A native constructor calls this once it has validated its arguments, which is the
13059    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
13060    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
13061    /// never reached. The prototype comes from `new.target` when it is an object, and from
13062    /// `default_proto` otherwise.
13063    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13064        let proto = self.ctor_prototype(default_proto)?;
13065        Ok(self.new_object(Some(proto)))
13066    }
13067
13068    /// An **array** whose prototype comes from `new.target`.
13069    ///
13070    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
13071    /// instance from `new.target.prototype`, and building a plain array instead made every
13072    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
13073    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
13074        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
13075        Ok(JsObject::array(self.heap, Some(proto), 0))
13076    }
13077
13078    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
13079    ///
13080    /// The `Option` form is for the constructors that build their instance in a helper which
13081    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
13082    /// from `await`'s internal promise, and only the first has a `new.target`.
13083    fn ctor_prototype_opt(
13084        &mut self,
13085        default_proto: Option<Gc<JsObject>>,
13086    ) -> JsResult<Option<Gc<JsObject>>> {
13087        let Some(target) = self.pending_new_target.clone() else {
13088            return Ok(default_proto);
13089        };
13090        let Some(target) = target.as_object().cloned() else {
13091            return Ok(default_proto);
13092        };
13093        match self.get_property(&target, "prototype")? {
13094            Some(Value::Object(proto)) => Ok(Some(proto)),
13095            _ => Ok(default_proto),
13096        }
13097    }
13098
13099    /// `new.target.prototype`, or `default_proto` when this is a plain call.
13100    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13101        let Some(target) = self.pending_new_target.clone() else {
13102            return Ok(default_proto);
13103        };
13104        let Some(target) = target.as_object().cloned() else {
13105            return Ok(default_proto);
13106        };
13107        match self.get_property(&target, "prototype")? {
13108            Some(Value::Object(proto)) => Ok(proto),
13109            _ => Ok(default_proto),
13110        }
13111    }
13112
13113    /// `CreateDataPropertyOrThrow(O, key, value)`.
13114    ///
13115    /// A *definition*, not an assignment. The difference is visible the moment the target
13116    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
13117    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
13118    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
13119    /// refused (`configurable: false`).
13120    ///
13121    /// The fast path exists because this is called once per element by `map`, `filter`,
13122    /// `slice` and friends: a plain array with no custom element descriptors and a writable
13123    /// `length` can store straight into its element vector.
13124    pub fn create_data_property_or_throw(
13125        &mut self,
13126        object: &Gc<JsObject>,
13127        index: usize,
13128        value: Value,
13129    ) -> JsResult<()> {
13130        if object.is_array()
13131            && object.elements_writable()
13132            && !object.has_element_descriptors()
13133            && object.is_extensible()
13134            && object.array_set(self.heap, index, value.clone())
13135        {
13136            return Ok(());
13137        }
13138        let key = PropertyKey::from(index.to_string());
13139        let property = Property {
13140            value: Some(value),
13141            writable: true,
13142            enumerable: true,
13143            configurable: true,
13144            ..Property::default()
13145        };
13146        // `CreateDataProperty` always asks for the default attributes, so it can only ever
13147        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13148        // the rest. Checking here rather than inside `object_define_own_property` is
13149        // deliberate: that function receives a fully-populated `Property` and cannot tell
13150        // an omitted attribute from an explicit `false`, so the generic check it would need
13151        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13152        // writable property (that cost eight `Object/defineProperty` tests).
13153        if let Some(existing) = self.object_get_own_property(object, &key)?
13154            && !existing.configurable
13155        {
13156            return Err(self.type_error("cannot create the property"));
13157        }
13158        if self.object_define_own_property(object, &key, property)? {
13159            return Ok(());
13160        }
13161        Err(self.type_error("cannot create the property"))
13162    }
13163
13164    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
13165    ///
13166    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
13167    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
13168    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
13169    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
13170    /// run user code and both can throw.
13171    pub fn species_constructor(
13172        &mut self,
13173        object: &Gc<JsObject>,
13174        default: Value,
13175    ) -> JsResult<Value> {
13176        let Some(constructor) = self.get_property(object, "constructor")? else {
13177            return Ok(default);
13178        };
13179        let constructor = match constructor {
13180            Value::Undefined => return Ok(default),
13181            Value::Object(constructor) => constructor,
13182            _ => return Err(self.type_error("constructor is not an object")),
13183        };
13184        let key = self.realm.well_known_key(WellKnown::Species);
13185        let species = self.get_property_key(&constructor, &key)?;
13186        match species {
13187            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
13188            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
13189            Some(_) => Err(self.type_error("species is not a constructor")),
13190        }
13191    }
13192
13193    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
13194    ///
13195    /// The result is an array of `length` holes whose prototype comes from
13196    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
13197    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
13198    /// is why the `IsArray` check is the first step and not an optimisation.
13199    pub fn array_species_create(
13200        &mut self,
13201        original: &Value,
13202        length: usize,
13203    ) -> JsResult<Gc<JsObject>> {
13204        let Some(object) = original.as_object().cloned() else {
13205            return Ok(self.new_array_of_length(length));
13206        };
13207        if !object.is_array() {
13208            return Ok(self.new_array_of_length(length));
13209        }
13210        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
13211        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
13212        let Some(constructor) = self.get_property(&object, "constructor")? else {
13213            return Ok(self.new_array_of_length(length));
13214        };
13215        let species = match constructor {
13216            Value::Undefined => return Ok(self.new_array_of_length(length)),
13217            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
13218                return Ok(self.new_array_of_length(length));
13219            }
13220            Value::Object(constructor) => {
13221                let key = self.realm.well_known_key(WellKnown::Species);
13222                match self.get_property_key(&constructor, &key)? {
13223                    None | Some(Value::Undefined) | Some(Value::Null) => {
13224                        return Ok(self.new_array_of_length(length));
13225                    }
13226                    Some(species) => species,
13227                }
13228            }
13229            // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
13230            // is a `TypeError`, not "the default". Treating it as the default made
13231            // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
13232            // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
13233            // `concat/create-ctor-non-object` are the same rule three times.
13234            _ => return Err(self.type_error("constructor is not an object")),
13235        };
13236        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
13237        // that is merely callable is the `create-species-non-ctor` case.
13238        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
13239            return Err(self.type_error("species is not a constructor"));
13240        }
13241        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
13242        let Some(created) = created.as_object().cloned() else {
13243            return Err(self.type_error("species constructor did not answer an object"));
13244        };
13245        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
13246        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
13247        // object, and `create-species-with-non-writable-property` asserts exactly that.
13248        // The length is set for the array case; the generic case is the caller's
13249        // `Set(A, "length", …)`.
13250        if created.is_array() {
13251            created.array_set_length(self.heap, length);
13252        }
13253        Ok(created)
13254    }
13255
13256    /// Whether `object` is this realm's `%Array%`.
13257    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
13258        self.realm
13259            .array_constructor
13260            .as_ref()
13261            .is_some_and(|array| array.ptr_eq(object))
13262    }
13263
13264    /// A fresh `length`-hole array with the intrinsic prototype.
13265    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
13266        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
13267        array.array_set_length(self.heap, length);
13268        array
13269    }
13270
13271    /// Whether this call is a construction, i.e. `new.target` is defined.
13272    ///
13273    /// A native constructor receives `this = undefined` (it builds its own instance), so it
13274    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
13275    /// The native function currently executing, if any.
13276    pub fn current_native(&self) -> Option<Gc<JsObject>> {
13277        self.current_native.clone()
13278    }
13279
13280    /// Whether this call is a construction, i.e. `new.target` is defined.
13281    pub fn is_constructing(&self) -> bool {
13282        self.pending_new_target.is_some()
13283    }
13284
13285    /// The `TypeError` a constructor too primitive to have a wrapper raises.
13286    ///
13287    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
13288    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
13289    /// happens inside the native function, which is why the trace carries an
13290    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
13291    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
13292    /// constructor`, and an unnamed one reports the leading space of `" is not a
13293    /// constructor"` because the reference formats the empty name as it is.
13294    ///
13295    /// It is also the answer for a `new.target` that cannot be named at all — not a
13296    /// function, or a throwing `name` getter — where the reference falls back to the bare
13297    /// `not a constructor`.
13298    pub fn not_a_constructor_error(&mut self) -> Signal {
13299        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
13300        self.not_a_constructor_error_for(target)
13301    }
13302
13303    /// The same `TypeError` for an explicit target, for the callers that check
13304    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
13305    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
13306        let target = match target {
13307            Value::Object(target) if target.is_callable() => target,
13308            _ => return self.type_error("not a constructor"),
13309        };
13310        let name = match self.get_property(&target, "name") {
13311            Ok(Some(value)) => value.to_js_string(),
13312            _ => return self.type_error("not a constructor"),
13313        };
13314        self.type_error(format!("{name} is not a constructor"))
13315    }
13316
13317    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
13318    ///
13319    /// True whenever `new.target` is not the callee itself, or when it has no usable
13320    /// `prototype` — the cases where reading the property is observable at all.
13321    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
13322        match &self.pending_new_target {
13323            Some(Value::Object(target)) => !target.ptr_eq(callee),
13324            Some(_) => true,
13325            None => false,
13326        }
13327    }
13328
13329    /// The symbol key for one of the engine's own hidden slots.
13330    ///
13331    /// Cached on the realm, so every object of a kind shares one key and a slot can be
13332    /// read back by name.
13333    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
13334        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
13335            return PropertyKey::Symbol(symbol.clone());
13336        }
13337        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
13338        self.realm
13339            .internal_slots
13340            .borrow_mut()
13341            .insert(name, Value::Symbol(symbol.clone()));
13342        PropertyKey::Symbol(symbol)
13343    }
13344
13345    /// Read a hidden slot, or `None` when the object has none of that name.
13346    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
13347        let slots = self.realm.internal_slots.borrow();
13348        let Value::Symbol(symbol) = slots.get(name)? else {
13349            return None;
13350        };
13351        object
13352            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
13353            .and_then(|property| property.value)
13354    }
13355
13356    /// Define a hidden slot.
13357    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
13358        let key = self.internal_slot(name);
13359        object.define_key(&key, Property::with_attributes(value, false, false));
13360    }
13361
13362    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
13363    ///
13364    /// The method is looked up on the value (through its prototype), called with no
13365    /// arguments, and its result becomes the iterator. A generator gets here through
13366    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
13367    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
13368    ///
13369    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
13370    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
13371    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
13372    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
13373    /// does, and a user-defined iterable works without a special case.
13374    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
13375    /// `Symbol.iterator`.
13376    ///
13377    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
13378    /// iterable is legal there, and each value it produces is simply already settled by
13379    /// the time the `await` around it runs.
13380    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13381        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
13382        let method = self.read_field_key(value, &async_key)?;
13383        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
13384        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
13385        // is *present but not callable* is a TypeError — it does not mean "try the other
13386        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
13387        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
13388        // guard is there to catch.
13389        let absent = matches!(method, Value::Undefined | Value::Null);
13390        if !absent {
13391            let Value::Object(object) = &method else {
13392                return Err(Signal::Throw(
13393                    self.make_error("TypeError", "value is not iterable"),
13394                ));
13395            };
13396            if !object.is_callable() {
13397                return Err(Signal::Throw(
13398                    self.make_error("TypeError", "value is not iterable"),
13399                ));
13400            }
13401        }
13402        if absent {
13403            return self.get_iterator(value);
13404        }
13405        let iterator = self.call_value(method, value.clone(), Vec::new())?;
13406        if !matches!(iterator, Value::Object(_)) {
13407            return Err(Signal::Throw(
13408                self.make_error("TypeError", "iterator is not an object"),
13409            ));
13410        }
13411        let next = self.read_field(&iterator, "next")?;
13412        Ok(Iterator {
13413            object: iterator,
13414            next,
13415        })
13416    }
13417
13418    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13419        let key = self.realm.well_known_key(WellKnown::Iterator);
13420        let method = self.read_field_key(value, &key)?;
13421        let Value::Object(function) = &method else {
13422            return Err(Signal::Throw(self.make_error(
13423                "TypeError",
13424                &format!("{} is not iterable", value.to_js_string()),
13425            )));
13426        };
13427        if !function.is_callable() {
13428            return Err(Signal::Throw(self.make_error(
13429                "TypeError",
13430                &format!("{} is not iterable", value.to_js_string()),
13431            )));
13432        }
13433        let iterator = self.call_value(method, value.clone(), Vec::new())?;
13434        // The spec requires an object here; a primitive iterator has no `next` to call
13435        // and would fail one step later with a confusing message.
13436        if !matches!(iterator, Value::Object(_)) {
13437            return Err(Signal::Throw(
13438                self.make_error("TypeError", "iterator is not an object"),
13439            ));
13440        }
13441        let next = self.read_field(&iterator, "next")?;
13442        Ok(Iterator {
13443            object: iterator,
13444            next,
13445        })
13446    }
13447
13448    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
13449    /// cannot replace it.
13450    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
13451        let method = self.read_field(&iterator.object, "return")?;
13452        if matches!(method, Value::Undefined | Value::Null) {
13453            return Ok(());
13454        }
13455        if !matches!(&method, Value::Object(object) if object.is_callable()) {
13456            return Err(self.type_error("iterator return is not a function"));
13457        }
13458        self.call_value(method, iterator.object.clone(), Vec::new())?;
13459        Ok(())
13460    }
13461
13462    /// One step of an internal iterator: the value and whether it is exhausted.
13463    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
13464        // A real iterator (`next` is a function) answers with a result object.
13465        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
13466            let result =
13467                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
13468            let Some(result) = result.as_object().cloned() else {
13469                return Err(self.type_error("iterator result is not an object"));
13470            };
13471            let done = self
13472                .get_property(&result, "done")?
13473                .is_some_and(|value| value.to_boolean());
13474            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
13475            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
13476            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
13477            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
13478            // made an unrelated `value` getter observable after the loop was over.
13479            if done {
13480                return Ok((Value::Undefined, true));
13481            }
13482            let value = self
13483                .get_property(&result, "value")?
13484                .unwrap_or(Value::Undefined);
13485            return Ok((value, false));
13486        }
13487        // An iterator whose `next` is not callable is treated as exhausted, which is
13488        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
13489        // that are not iterable at all.
13490        Ok((Value::Undefined, true))
13491    }
13492
13493    /// `[...iterable]`: append everything the iterator yields, and answer the next
13494    /// index.
13495    ///
13496    /// This goes through the same iterator machinery `for-of` uses rather than copying
13497    /// an array's elements, because a spread source is any iterable: a string spreads
13498    /// into its characters and an array iterator spreads into its results. Handling
13499    /// only arrays made `[..."ab"]` come out empty with no error at all.
13500    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
13501        let Some(target) = array.as_object().cloned() else {
13502            return Ok(0);
13503        };
13504        let start = target.array_length().unwrap_or(0);
13505        let mut added = 0;
13506        let iterator = self.get_iterator(iterable)?;
13507        loop {
13508            let (value, done) = self.iterator_step(&iterator)?;
13509            if done {
13510                break;
13511            }
13512            target.array_set(self.heap, start + added, value);
13513            added += 1;
13514        }
13515        Ok((start + added) as i32)
13516    }
13517
13518    /// How an uncaught exception is reported.
13519    ///
13520    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
13521    /// with `ToString` — `js_std_dump_error` is three lines that end in
13522    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
13523    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
13524    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
13525    ///
13526    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
13527    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
13528    /// `toString`"; it does call it, but only for objects of a class it does not know how
13529    /// to walk, and never for errors, arrays or plain objects.
13530    ///
13531    /// A printer that fails must not take the reporter down with it, so that case falls
13532    /// back to the `ToString` rendering.
13533    pub fn describe_exception(&mut self, value: &Value) -> String {
13534        match crate::print::sprint(self, value) {
13535            Ok(text) => text,
13536            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
13537        }
13538    }
13539
13540    /// The file name of whatever is running, innermost frame first.
13541    ///
13542    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
13543    /// innermost frame's file name, without distinguishing a module body from a plain
13544    /// script. `import()` uses it as the base for a relative specifier, which is why
13545    /// `import('./x.js')` inside a script resolves next to the script and not next to the
13546    /// process's working directory.
13547    pub fn script_or_module_name(&self) -> Option<String> {
13548        self.script_or_module_name_at(0)
13549    }
13550
13551    /// [`Interp::script_or_module_name`] `level` frames further out.
13552    ///
13553    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
13554    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
13555    /// frame without a file name is skipped rather than counted, because a native call
13556    /// pushes no frame of its own and so cannot be a level.
13557    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
13558        self.frames
13559            .iter()
13560            .rev()
13561            .filter_map(|frame| frame.code.code.filename.clone())
13562            .nth(level)
13563    }
13564
13565    /// The current call stack, formatted the way `qjs` prints `error.stack`.
13566    ///
13567    /// One `    at name (file:line:col)` line per active frame, innermost first. The
13568    /// position is the one recorded for the instruction each frame is stopped on, which
13569    /// is why the compiler builds a pc-to-position table per function: without it a
13570    /// trace could only name the function, not the line inside it.
13571    ///
13572    /// A frame whose code has no positions prints just `(file)`, matching the
13573    /// reference's output for stripped bytecode.
13574    pub fn stack_trace(&self) -> String {
13575        self.stack_trace_skipping(0)
13576    }
13577
13578    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
13579    fn stack_trace_skipping(&self, skip: usize) -> String {
13580        // One ordered list, innermost first, so `skip` counts the same thing whether the
13581        // frames it leaves out are native or bytecode. Indices rather than references: a
13582        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
13583        let depth = self.frames.len();
13584        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
13585        // A native entered while `at` bytecode frames were live was called *from* the
13586        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
13587        // entered at the current depth are therefore innermost of all.
13588        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
13589            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
13590                if *at == wanted {
13591                    order.push((true, index));
13592                }
13593            }
13594        };
13595        push_natives(&mut order, depth);
13596        for index in (0..depth).rev() {
13597            order.push((false, index));
13598            push_natives(&mut order, index);
13599        }
13600        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
13601        // barrier. Natives entered at exactly the barrier depth are the eval entry point
13602        // itself (`evalScript (native)`), and the reference leaves those out too.
13603        if let Some(barrier) = self.trace_barriers.last().copied() {
13604            order.retain(|(is_native, index)| match is_native {
13605                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
13606                false => *index >= barrier,
13607            });
13608        }
13609
13610        let mut out = String::new();
13611        for (is_native, index) in order.into_iter().skip(skip) {
13612            match is_native {
13613                true => {
13614                    out.push_str("    at ");
13615                    let (native, _) = &self.native_frames[index];
13616                    let name = native
13617                        .own_property("name")
13618                        .and_then(|property| property.value)
13619                        .map(|value| value.to_js_string())
13620                        .unwrap_or_default();
13621                    out.push_str(&name);
13622                    out.push_str(" (native)\n");
13623                }
13624                false => {
13625                    let frame = &self.frames[index];
13626                    let code = &frame.code.code;
13627                    let file = code.filename.as_deref().unwrap_or("<input>");
13628                    // The name comes from the function *object*, not from the compiled code:
13629                    // an anonymous function expression is named by the property it is stored
13630                    // in (`{valueOf: function(){}}`), which only the object knows.
13631                    let bound_name = match &frame.callee {
13632                        Value::Object(object) => {
13633                            object
13634                                .own_property("name")
13635                                .and_then(|property| match property.value {
13636                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
13637                                        Some(text.to_string_lossy().into_owned())
13638                                    }
13639                                    _ => None,
13640                                })
13641                        }
13642                        _ => None,
13643                    };
13644                    // No callee object means the body was entered by the host, so the
13645                    // name has to come from the compiled code. Two cases differ:
13646                    //
13647                    // * an *unnamed* function of any kind — the reference reads the
13648                    //   `name` property, finds it empty, and prints `<anonymous>`;
13649                    // * a *module* body, which has no `name` property at all: the
13650                    //   reference builds that function object with `js_closure2` and
13651                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
13652                    //   so a trace reaching it also prints `<anonymous>` — while a
13653                    //   *script* body prints `<eval>`, its `name`.
13654                    let unnamed = code.name.is_empty() || code.module.is_some();
13655                    out.push_str("    at ");
13656                    match bound_name.as_deref() {
13657                        Some(name) => out.push_str(name),
13658                        None if unnamed => out.push_str("<anonymous>"),
13659                        None => out.push_str(&code.name),
13660                    }
13661                    match code.position_at(frame.at as u32) {
13662                        Some((line, column)) => {
13663                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
13664                        }
13665                        None => out.push_str(&format!(" ({file})\n")),
13666                    }
13667                }
13668            }
13669        }
13670        out
13671    }
13672
13673    /// Give an anonymous function the name of the property it is stored in.
13674    ///
13675    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
13676    /// enumerable and not configurable, and a function that already has a real name
13677    /// keeps it.
13678    ///
13679    /// "Already named" means a *non-empty* name: every function object is created with
13680    /// a `name` of `""` so the property exists on all of them, and treating that empty
13681    /// string as a name left every anonymous function nameless — which is how a stack
13682    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
13683    /// `SetFunctionName`, for a name that came from source text.
13684    fn set_function_name(&mut self, function: &Value, name: &str) {
13685        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
13686    }
13687
13688    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
13689    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
13690    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
13691        let Value::Object(object) = function else {
13692            return;
13693        };
13694        // `SetFunctionName` applies to *functions* and classes only, and only when they are
13695        // anonymous. Without the callability guard, `{value: someObject}` renamed
13696        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
13697        // on the right-hand side of a property. That is how a `zipKeyed` result object
13698        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
13699        // has no `NamedEvaluation` at all.
13700        if !object.is_callable() {
13701            return;
13702        }
13703        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
13704            && !existing.wtf8().is_empty()
13705        {
13706            return;
13707        }
13708        let text = self.string_wtf8(name.clone());
13709        object.define("name", Property::name_or_length(text));
13710    }
13711
13712    // -- global declarations -----------------------------------------------
13713
13714    /// Declare a global binding, creating its reference cell.
13715    /// Declare a `var` or function global, whose home is the global object.
13716    ///
13717    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
13718    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
13719    /// such as `print`, or a redeclaration — is left alone.
13720    pub fn declare_var_global(&mut self, name: &str) {
13721        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
13722        // global object is exactly the leak `typeof my_var === "undefined"` after
13723        // `eval("var my_var=2")` rules out.
13724        if let Some(scope) = self.eval_scope.as_mut() {
13725            scope.entry(name.to_string()).or_insert(Value::Undefined);
13726            return;
13727        }
13728        // A sloppy direct eval declares into its *caller's* variable environment. Doing
13729        // this on the global object instead made `eval("var c = 1")` inside a parameter
13730        // list overwrite a global `c`, and made two calls to the same function share one
13731        // binding.
13732        if let Some(cell) = self.declare_eval_local(name) {
13733            cell.set(Value::Undefined);
13734            return;
13735        }
13736        let global = self.realm.global.clone();
13737        if global.own_property(name).is_some() {
13738            return;
13739        }
13740        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
13741        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
13742        // whole point of that trick and what lets `Object.defineProperty` reshape it
13743        // afterwards. `eval_scope` is `Some` while an eval is running.
13744        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
13745        global.define(
13746            name,
13747            Property {
13748                value: Some(Value::Undefined),
13749                writable: true,
13750                enumerable: true,
13751                configurable: from_eval,
13752                ..Property::default()
13753            },
13754        );
13755    }
13756
13757    /// Declare a *lexical* global binding, which starts in its dead zone.
13758    ///
13759    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
13760    /// global object and is created when its initialiser runs.
13761    pub fn declare_global(&mut self, name: &str, is_const: bool) {
13762        if is_const {
13763            self.realm.lexical_consts.insert(name.to_string());
13764        }
13765        if !self.realm.globals.contains_key(name) {
13766            // `Uninitialized` rather than `Undefined`: the binding exists but is not
13767            // readable until its initialiser runs, and that is what `let x` before
13768            // `x = 1` has to observe.
13769            let cell = self.new_cell(Value::Uninitialized);
13770            self.realm.globals.insert(name.to_string(), cell);
13771            self.realm.declared.push(name.to_string());
13772        }
13773    }
13774}
13775
13776/// The bytecode and environment of a function object, if it is a bytecode function.
13777///
13778/// Extracted before a call so no borrow of the object is held across it.
13779fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
13780    function.with(|data| match &data.kind {
13781        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
13782        _ => None,
13783    })
13784}
13785
13786/// A native call target, extracted before the call so no borrow is held.
13787enum NativeCall {
13788    Native(NativeFn),
13789    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
13790    /// not hold that object's `RefCell` borrow.
13791    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
13792    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
13793    Bound {
13794        target: Value,
13795        this: Value,
13796        leading: Vec<Value>,
13797    },
13798    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
13799    Revoker(crate::object::ProxyRef),
13800    /// A promise's `resolve`.
13801    PromiseResolve(Gc<JsObject>),
13802    /// A promise's `reject`.
13803    PromiseReject(Gc<JsObject>),
13804    /// The executor `NewPromiseCapability(C)` hands a user constructor.
13805    CapabilityExecutor {
13806        state: Gc<JsObject>,
13807    },
13808    /// One leg of a `then` that settles through a user capability.
13809    ThenShim {
13810        handler: Option<Value>,
13811        resolve: Value,
13812        reject: Value,
13813        fulfilled: bool,
13814    },
13815    /// One continuation of an `await`.
13816    AwaitResume {
13817        coroutine: Gc<JsObject>,
13818        promise: Gc<JsObject>,
13819        kind: ResumeKind,
13820    },
13821    /// One element of a `Promise` combinator settling.
13822    CombinatorSettle {
13823        state: Gc<JsObject>,
13824        index: usize,
13825        fulfilled: bool,
13826    },
13827    /// One of `Promise.prototype.finally`'s two shims.
13828    FinallyShim {
13829        callback: Option<Value>,
13830        fulfilled: bool,
13831        constructor: Value,
13832    },
13833    /// Settle a promise with a fixed outcome.
13834    SettlePromise {
13835        promise: Gc<JsObject>,
13836        value: Value,
13837        rejected: bool,
13838    },
13839    /// Continue an async generator after its `await` settled.
13840    GeneratorResume {
13841        generator: Gc<JsObject>,
13842        promise: Gc<JsObject>,
13843        kind: ResumeKind,
13844    },
13845    /// Read a module namespace's binding out of its cell.
13846    ModuleBinding(Gc<Cell>),
13847    /// Finish a completed async generator's `return(v)` once `v` has settled.
13848    CompletedReturn {
13849        generator: Gc<JsObject>,
13850        promise: Gc<JsObject>,
13851        rejected: bool,
13852    },
13853    /// Answer a pending async-generator method with `{value, done}`.
13854    YieldResult {
13855        generator: Gc<JsObject>,
13856        promise: Gc<JsObject>,
13857        done: bool,
13858    },
13859    /// One step of `AsyncDisposableStack.disposeAsync`.
13860    DisposeStep {
13861        remaining: Gc<JsObject>,
13862        promise: Gc<JsObject>,
13863        error: Value,
13864        rejected: bool,
13865    },
13866}
13867
13868/// What a store does when the object refuses the write.
13869#[derive(Clone, Copy, PartialEq, Eq)]
13870pub enum DeleteFailure {
13871    /// Raise a `TypeError`, which is what strict mode and every built-in does.
13872    Throw,
13873    /// Ignore the write, which is what a sloppy-mode assignment does.
13874    Ignore,
13875}
13876
13877/// Whether `object` is a `Date` instance, by the class tag it carries.
13878///
13879/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13880/// builtins module depending on the interpreter's conversion order.
13881fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13882    interp
13883        .internal_get(object, "_class")
13884        .is_some_and(|value| value.to_js_string() == "Date")
13885}
13886
13887/// Which type `ToPrimitive` prefers when it converts an object.
13888#[derive(Clone, Copy, PartialEq, Eq)]
13889pub enum Hint {
13890    /// The default hint, which behaves like [`Hint::Number`].
13891    Default,
13892    /// `Number(obj)` and the arithmetic operators.
13893    Number,
13894    /// `String(obj)` and `ToPropertyKey`.
13895    String,
13896}
13897
13898/// Which table a binding slot indexes, for the messages that name it.
13899#[derive(Clone, Copy)]
13900enum VarSlot {
13901    Loc,
13902    Closure,
13903}
13904
13905/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13906fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13907    Ok(this)
13908}
13909
13910/// An internal iterator: the sequence plus a cursor.
13911pub(crate) struct Iterator {
13912    pub(crate) object: Value,
13913    pub(crate) next: Value,
13914}
13915
13916/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13917/// and plain `a` for a method.
13918///
13919/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13920/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13921/// reads `at get a (file:1:2)`.
13922/// The same prefixing, for a name that may hold an unpaired surrogate.
13923fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13924    let prefix = match flags & 3 {
13925        1 => "get ",
13926        2 => "set ",
13927        _ => return key.clone(),
13928    };
13929    let mut units: Vec<u16> = prefix.encode_utf16().collect();
13930    units.extend_from_slice(&key.to_units());
13931    crate::value::Wtf8::from_units(&units)
13932}
13933
13934fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13935    match flags & 3 {
13936        1 => format!("get {key}"),
13937        2 => format!("set {key}"),
13938        _ => key.to_string(),
13939    }
13940}
13941
13942/// Define a method or accessor property, per the `define_method` flag byte.
13943///
13944/// The low two bits pick value/getter/setter and bit 2 marks the property
13945/// enumerable.
13946///
13947/// A getter and a setter arrive as two separate `define_method` instructions, and the
13948/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13949/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13950/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13951/// `JS_DefineProperty`, which leaves the other half alone.
13952fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13953    let enumerable = flags & 4 != 0;
13954    let kind = flags & 3;
13955    let existing = object.own_property_key(key);
13956    let property = match kind {
13957        1 => Property {
13958            getter: Some(function),
13959            // The setter half, if this literal already defined one.
13960            setter: existing
13961                .filter(Property::is_accessor)
13962                .and_then(|p| p.setter),
13963            enumerable,
13964            configurable: true,
13965            ..Property::default()
13966        },
13967        2 => Property {
13968            getter: existing
13969                .filter(Property::is_accessor)
13970                .and_then(|p| p.getter),
13971            setter: Some(function),
13972            enumerable,
13973            configurable: true,
13974            ..Property::default()
13975        },
13976        _ => Property {
13977            value: Some(function),
13978            writable: true,
13979            enumerable,
13980            configurable: true,
13981            ..Property::default()
13982        },
13983    };
13984    object.define_key(key, property);
13985}
13986
13987// ---------------------------------------------------------------------------
13988// Operand decoding
13989// ---------------------------------------------------------------------------
13990
13991/// How `print` renders a value: the reference's `JS_PrintValue`.
13992///
13993/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13994/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13995/// The format is reproduced closely because the test suite compares output text:
13996///
13997/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13998/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13999/// * a cycle prints `[circular N]` with `N` the stack index of the object;
14000/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
14001///   end print as `<N empty item(s)>`;
14002/// * a string is quoted inside a container but raw at the top level, which is why
14003///   `print("x")` and `print(["x"])` differ.
14004pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
14005    // A string argument is printed raw: `js_print` converts it with `ToString`
14006    // instead of dumping it, and the quoting only appears inside a container.
14007    if let Value::String(text) = value {
14008        return text.to_string_lossy().into_owned();
14009    }
14010    let mut printer = Printer {
14011        interp,
14012        out: String::new(),
14013        stack: Vec::new(),
14014    };
14015    printer.value(value, 0);
14016    printer.out
14017}
14018
14019/// The internal class name an object carries, when it has one.
14020fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
14021    interp
14022        .internal_get(object, "_class")
14023        .map(|value| value.to_js_string())
14024}
14025
14026/// A string property, looked up the way `GetProperty` does: own first, then the
14027/// prototype chain. Needed because the print formatter holds the interpreter
14028/// immutably and so cannot run getters.
14029fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
14030    let mut current = Some(object.clone());
14031    // Bounded, because a prototype cycle would otherwise loop forever.
14032    for _ in 0..100 {
14033        let node = current?;
14034        if let Some(property) = node.own_property(name)
14035            && let Some(value) = property.value
14036        {
14037            return Some(value.to_js_string());
14038        }
14039        current = node.with(|data| data.proto.clone());
14040    }
14041    None
14042}
14043
14044/// The `JS_PrintValue` state: output, and the objects currently being printed.
14045struct Printer<'a, 'rt> {
14046    /// Kept for the class-name lookups that typed arrays and `Date` will need.
14047    #[allow(dead_code)]
14048    interp: &'a Interp<'rt>,
14049    out: String,
14050    stack: Vec<Gc<JsObject>>,
14051}
14052
14053impl Printer<'_, '_> {
14054    /// Depth past which a container is summarised by its class name.
14055    const MAX_DEPTH: usize = 2;
14056
14057    fn value(&mut self, value: &Value, level: usize) {
14058        match value {
14059            Value::Undefined
14060            | Value::Uninitialized
14061            | Value::Hole
14062            | Value::CatchOffset(_)
14063            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
14064            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
14065            // The printer writes a bigint the way the language spells one, so a dump is
14066            // unambiguous about which kind of number it is showing.
14067            Value::BigInt(big) => {
14068                self.out.push_str(&big.to_decimal_string());
14069                self.out.push('n');
14070            }
14071            Value::Null => self.out.push_str("null"),
14072            Value::Bool(true) => self.out.push_str("true"),
14073            Value::Bool(false) => self.out.push_str("false"),
14074            Value::Int(number) => self.out.push_str(&number.to_string()),
14075            Value::Float(number) => {
14076                self.out
14077                    .push_str(&crate::value::number_to_string_for_print(*number));
14078            }
14079            Value::String(text) => self.print_string(&text.to_string_lossy()),
14080            Value::Object(object) => self.object(object, level),
14081        }
14082    }
14083
14084    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
14085        // A cycle is reported rather than followed; the index is where the object
14086        // already sits in the print stack, which is what the reference shows.
14087        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
14088            self.out.push_str(&format!("[circular {index}]"));
14089            return;
14090        }
14091        if object.is_callable() {
14092            let name = object
14093                .own_property("name")
14094                .and_then(|property| property.value)
14095                .map(|value| value.to_js_string())
14096                .unwrap_or_default();
14097            if name.is_empty() {
14098                self.out.push_str("[Function (anonymous)]");
14099            } else {
14100                self.out.push_str(&format!("[Function {name}]"));
14101            }
14102            return;
14103        }
14104        if level >= Self::MAX_DEPTH {
14105            let class = if object.is_array() { "Array" } else { "Object" };
14106            self.out.push_str(&format!("[{class}]"));
14107            return;
14108        }
14109        // `Date` and `Error` print as themselves rather than as bags of properties:
14110        // the ISO string, and `Name: message` followed by the trace.
14111        if let Some(class) = class_of(self.interp, object) {
14112            if class == "Date" {
14113                self.date(object);
14114                return;
14115            }
14116            if class == "Error" {
14117                self.error(object);
14118                return;
14119            }
14120        }
14121        self.stack.push(object.clone());
14122        if object.is_array() {
14123            self.array(object, level);
14124        } else {
14125            self.plain_object(object, level);
14126        }
14127        self.stack.pop();
14128    }
14129
14130    /// A Date prints as its ISO string; an invalid one falls through to the plain
14131    /// object form, the way the reference falls back when `toISOString` throws.
14132    fn date(&mut self, object: &Gc<JsObject>) {
14133        let value = self
14134            .interp
14135            .internal_get(object, "_date_value")
14136            .map(|value| value.to_number());
14137        match value.and_then(crate::builtins::date::iso_string) {
14138            Some(text) => self.out.push_str(&text),
14139            None => self.plain_object(object, 0),
14140        }
14141    }
14142
14143    /// `Name: message`, then the trace with its trailing newline removed.
14144    fn error(&mut self, object: &Gc<JsObject>) {
14145        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
14146        self.out.push_str(&name);
14147        if let Some(message) = inherited(object, "message")
14148            && !message.is_empty()
14149        {
14150            self.out.push_str(": ");
14151            self.out.push_str(&message);
14152        }
14153        if let Some(stack) = inherited(object, "stack") {
14154            self.out.push('\n');
14155            self.out.push_str(stack.trim_end_matches('\n'));
14156        }
14157    }
14158
14159    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
14160        let elements = object.array_elements().unwrap_or_default();
14161        self.out.push_str("[ ");
14162        // An interior hole means the array is "sparse": the reference prints those
14163        // as `index: value` pairs and says nothing about the holes themselves, while
14164        // a hole run at the end becomes a single `<N empty items>` note.
14165        let last_present = elements
14166            .iter()
14167            .rposition(|value| !matches!(value, Value::Hole));
14168        let has_interior_hole = match last_present {
14169            Some(last) => elements[..last]
14170                .iter()
14171                .any(|value| matches!(value, Value::Hole)),
14172            None => false,
14173        };
14174        let mut first = true;
14175        if has_interior_hole {
14176            let mut index = 0;
14177            while index < elements.len() {
14178                let value = &elements[index];
14179                if matches!(value, Value::Hole) {
14180                    index += 1;
14181                    continue;
14182                }
14183                if !first {
14184                    self.out.push_str(", ");
14185                }
14186                first = false;
14187                self.out.push_str(&format!("{index}: "));
14188                self.value(value, level + 1);
14189                index += 1;
14190            }
14191        } else {
14192            for (index, value) in elements.iter().enumerate() {
14193                if matches!(value, Value::Hole) {
14194                    continue;
14195                }
14196                if !first {
14197                    self.out.push_str(", ");
14198                }
14199                first = false;
14200                let _ = index;
14201                self.value(value, level + 1);
14202            }
14203            if let Some(last) = last_present {
14204                let trailing = elements.len() - last - 1;
14205                if trailing > 0 {
14206                    if !first {
14207                        self.out.push_str(", ");
14208                    }
14209                    self.out.push_str(&format!(
14210                        "<{trailing} empty item{}>",
14211                        if trailing > 1 { "s" } else { "" }
14212                    ));
14213                }
14214            } else if !elements.is_empty() {
14215                let count = elements.len();
14216                self.out.push_str(&format!(
14217                    "<{count} empty item{}>",
14218                    if count > 1 { "s" } else { "" }
14219                ));
14220            }
14221        }
14222        self.out.push_str(" ]");
14223    }
14224
14225    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
14226        self.out.push_str("{ ");
14227        let mut first = true;
14228        for key in object.own_keys() {
14229            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
14230                continue;
14231            };
14232            if !property.enumerable {
14233                continue;
14234            }
14235            if !first {
14236                self.out.push_str(", ");
14237            }
14238            first = false;
14239            self.out
14240                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
14241                    &key.to_string_lossy(),
14242                )));
14243            self.out.push_str(": ");
14244            // An accessor has no value to dump; the reference names the half that
14245            // exists instead of calling it.
14246            if property.is_accessor() {
14247                let text = match (property.getter.is_some(), property.setter.is_some()) {
14248                    (true, true) => "[Getter/Setter]",
14249                    (false, true) => "[Setter]",
14250                    _ => "[Getter]",
14251                };
14252                self.out.push_str(text);
14253            } else {
14254                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
14255            }
14256        }
14257        self.out.push_str(" }");
14258    }
14259
14260    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
14261    fn print_string(&mut self, text: &str) {
14262        self.out.push('"');
14263        for character in text.chars() {
14264            match character {
14265                '"' => self.out.push_str("\\\""),
14266                '\\' => self.out.push_str("\\\\"),
14267                '\n' => self.out.push_str("\\n"),
14268                '\r' => self.out.push_str("\\r"),
14269                '\t' => self.out.push_str("\\t"),
14270                c if (c as u32) < 0x20 => {
14271                    self.out.push_str(&format!("\\u{:04x}", c as u32));
14272                }
14273                c => self.out.push(c),
14274            }
14275        }
14276        self.out.push('"');
14277    }
14278}
14279
14280/// How `print` renders a value.
14281///
14282/// `ToString`, except that negative zero keeps its sign — the reference's host
14283/// printer does that while `String(-0)` is `"0"`.
14284pub fn display(value: &Value) -> String {
14285    match value {
14286        Value::Float(number) => crate::value::number_to_string_for_print(*number),
14287        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
14288            "undefined".to_string()
14289        }
14290        other => other.to_js_string(),
14291    }
14292}
14293
14294// ---------------------------------------------------------------------------
14295// Numeric operators
14296// ---------------------------------------------------------------------------
14297
14298/// `a + b` keeping the `Int` representation when it fits.
14299fn add_numbers(left: Value, right: Value) -> Value {
14300    match (&left, &right) {
14301        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
14302            Some(sum) => Value::Int(sum),
14303            None => Value::Float(*a as f64 + *b as f64),
14304        },
14305        _ => Value::Float(left.to_number() + right.to_number()),
14306    }
14307}
14308
14309/// The arithmetic operators other than `+`, which needs string concatenation.
14310fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14311    use Opcode::*;
14312    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
14313    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
14314    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
14315    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
14316        return Ok(match op {
14317            And => Value::Int(x & y),
14318            Or => Value::Int(x | y),
14319            Xor => Value::Int(x ^ y),
14320            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
14321            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
14322            Shr => match (*x as u32) >> ((*y as u32) & 31) {
14323                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
14324                shifted => Value::Float(shifted as f64),
14325            },
14326            Sub => match x.checked_sub(*y) {
14327                Some(value) => Value::Int(value),
14328                None => Value::Float(*x as f64 - *y as f64),
14329            },
14330            _ => return arithmetic_slow(op, left, right),
14331        });
14332    }
14333    arithmetic_slow(op, left, right)
14334}
14335
14336/// [`arithmetic`] for everything the integer fast path above does not take.
14337fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14338    use Opcode::*;
14339    let (a, b) = (left.to_number(), right.to_number());
14340    Ok(match op {
14341        Sub => match (&left, &right) {
14342            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
14343                Some(value) => Value::Int(value),
14344                None => Value::Float(a - b),
14345            },
14346            _ => Value::Float(a - b),
14347        },
14348        Mul => Value::Float(a * b),
14349        Div => Value::Float(a / b),
14350        Mod => Value::Float(js_mod(a, b)),
14351        Pow => Value::Float(a.powf(b)),
14352        And => Value::Int(left.to_int32() & right.to_int32()),
14353        Or => Value::Int(left.to_int32() | right.to_int32()),
14354        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
14355        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
14356        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
14357        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
14358        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
14359        // fits the small-integer representation stays an `Int`; the rest become a
14360        // float, which is how the reference keeps `n >>> 0` non-negative.
14361        Shr => {
14362            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
14363            match i32::try_from(shifted) {
14364                Ok(value) => Value::Int(value),
14365                Err(_) => Value::Float(shifted as f64),
14366            }
14367        }
14368        _ => Value::Float(a),
14369    })
14370}
14371
14372/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
14373///
14374/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
14375/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
14376/// slow path where the rules live.
14377fn is_number(value: &Value) -> bool {
14378    matches!(value, Value::Int(_) | Value::Float(_))
14379}
14380
14381/// The `Value::Bool` a comparison operator answers for `ordering`.
14382///
14383/// `None` is the unordered case — a `NaN` on either side — and every operator answers
14384/// false for it, including `<=` and `>=`.
14385fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
14386    use Opcode::*;
14387    let answer = match (op, ordering) {
14388        (_, None) => false,
14389        (Lt, Some(ordering)) => ordering.is_lt(),
14390        (Lte, Some(ordering)) => ordering.is_le(),
14391        (Gt, Some(ordering)) => ordering.is_gt(),
14392        (Gte, Some(ordering)) => ordering.is_ge(),
14393        _ => false,
14394    };
14395    Value::Bool(answer)
14396}
14397
14398/// `%`, which follows the sign of the dividend rather than Rust's.
14399fn js_mod(left: f64, right: f64) -> f64 {
14400    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
14401        return f64::NAN;
14402    }
14403    if right.is_infinite() {
14404        return left;
14405    }
14406    let remainder = left % right;
14407    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
14408    // the spec makes the sign match the dividend.
14409    if remainder == 0.0 {
14410        0.0f64.copysign(left)
14411    } else {
14412        remainder
14413    }
14414}
14415
14416fn negate(value: Value) -> Value {
14417    match value {
14418        Value::Int(0) => Value::Float(-0.0),
14419        Value::Int(i) => Value::Int(-i),
14420        other => Value::Float(-other.to_number()),
14421    }
14422}
14423
14424fn increment(value: Value) -> Value {
14425    match value {
14426        Value::Int(i) => match i.checked_add(1) {
14427            Some(next) => Value::Int(next),
14428            None => Value::Float(i as f64 + 1.0),
14429        },
14430        other => Value::Float(other.to_number() + 1.0),
14431    }
14432}
14433
14434fn decrement(value: Value) -> Value {
14435    match value {
14436        Value::Int(i) => match i.checked_sub(1) {
14437            Some(next) => Value::Int(next),
14438            None => Value::Float(i as f64 - 1.0),
14439        },
14440        other => Value::Float(other.to_number() - 1.0),
14441    }
14442}
14443
14444/// Compare a `BigInt` with an `f64` on their mathematical values.
14445///
14446/// Neither side is rounded to the other's precision: the number is split into its integer
14447/// part (compared as an exact bigint) and its fraction, which is what decides the answer
14448/// when the integer parts are equal. An infinite value is larger than every bigint.
14449fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
14450    use std::cmp::Ordering;
14451    if number.is_nan() {
14452        return None;
14453    }
14454    if number.is_infinite() {
14455        return Some(if number > 0.0 {
14456            Ordering::Less
14457        } else {
14458            Ordering::Greater
14459        });
14460    }
14461    let truncated = number.trunc();
14462    // A number wider than `i128` still has an exact integer part, but no bigint form we can
14463    // build cheaply; the sign of the difference is all that is needed, so compare against
14464    // the bigint's own magnitude instead.
14465    if truncated.abs() >= 1.7e38 {
14466        let big_as_f64 = big.to_f64();
14467        return big_as_f64.partial_cmp(&number);
14468    }
14469    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
14470    match big.cmp(&integer) {
14471        Ordering::Equal => {
14472            // Same integer part: the fraction decides, and a negative number's fraction is
14473            // below the integer (`-1.5` truncates to `-1`).
14474            if number > truncated {
14475                Some(Ordering::Less)
14476            } else if number < truncated {
14477                Some(Ordering::Greater)
14478            } else {
14479                Some(Ordering::Equal)
14480            }
14481        }
14482        other => Some(other),
14483    }
14484}
14485
14486/// `CanonicalNumericIndexString(argument)` (§7.1.21).
14487///
14488/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
14489/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
14490/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
14491/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
14492/// rather than treating it as `0`.
14493fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
14494    let PropertyKey::String(text) = key else {
14495        // A symbol is never an index.
14496        return None;
14497    };
14498    let text = text.to_string_lossy();
14499    if text == "-0" {
14500        return Some(-0.0);
14501    }
14502    let number: f64 = text.parse().ok()?;
14503    // The round-trip test *is* the definition: only the canonical spelling qualifies.
14504    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
14505    // `"0.10"` does not.
14506    let rendered = Value::Float(number).to_js_string();
14507    (rendered == text).then_some(number)
14508}
14509
14510/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
14511///
14512/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
14513/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
14514/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
14515/// numeric and invalid, which is why they stop the prototype chain instead of falling
14516/// through it.
14517///
14518/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
14519/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
14520/// `in`, `delete` and `defineProperty` separately to make sure it does not.
14521fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
14522    numeric.is_finite()
14523        && numeric.fract() == 0.0
14524        && !(numeric == 0.0 && numeric.is_sign_negative())
14525        && numeric >= 0.0
14526        && object
14527            .typed_array_length()
14528            .is_some_and(|length| (numeric as usize) < length)
14529}