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 **intrinsic** `%Object.prototype.toString%`.
93    ///
94    /// Not a lookup on `Object.prototype`: `Array.prototype.toString` names the intrinsic
95    /// directly, so `delete Object.prototype.toString` does not change its fallback
96    /// (`Array/prototype/toString/non-callable-join-string-tag` deletes it and then calls
97    /// `Array.prototype.toString` on a dozen receivers).
98    pub object_proto_to_string: Option<Gc<JsObject>>,
99    /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
100    pub array_constructor: Option<Gc<JsObject>>,
101    /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
102    pub promise_constructor: Option<Gc<JsObject>>,
103    /// Reference cells for globals declared by the script.
104    ///
105    /// A declared global is read with `get_var` (by name) but written with
106    /// `put_var_ref` (through the cell), so the cell is what makes a function
107    /// declaration and its uses agree on one binding.
108    pub globals: BTreeMap<String, Gc<Cell>>,
109    /// Names of the globals that came from a *declaration*, which are
110    /// non-configurable properties of the global object.
111    pub declared: Vec<String>,
112    /// Names among the lexical globals that are `const`.
113    ///
114    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
115    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
116    /// path does not carry, so a store through it would look like a plain `let`. The
117    /// realm records it once, at declaration, and answers for every reader.
118    pub lexical_consts: BTreeSet<String>,
119    /// The error constructors by class name, so a runtime error can throw a real
120    /// `TypeError` instance rather than a look-alike object.
121    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
122    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
123    pub string_proto: Option<Gc<JsObject>>,
124    /// `Number.prototype`.
125    pub number_proto: Option<Gc<JsObject>>,
126    /// `Boolean.prototype`.
127    pub boolean_proto: Option<Gc<JsObject>>,
128    /// `BigInt.prototype`.
129    pub bigint_proto: Option<Gc<JsObject>>,
130    /// `Error.prototype`, the prototype of every error instance.
131    pub error_proto: Gc<JsObject>,
132    /// `Date.prototype`, so the constructor can build an instance in the
133    /// function-call form (`Date()` returns a string) without going through `new`.
134    pub date_proto: Gc<JsObject>,
135    /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
136    ///
137    /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
138    /// whole `ThrowTypeError/` directory finds it through
139    /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
140    /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
141    /// Creating a fresh one per property would make
142    /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
143    /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
144    pub throw_type_error: Option<Gc<JsObject>>,
145    /// `%GeneratorPrototype%`, the prototype of every generator object.
146    pub generator_proto: Gc<JsObject>,
147    /// `Promise.prototype`, the prototype of every promise.
148    pub promise_proto: Option<Gc<JsObject>>,
149    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
150    pub async_generator_proto: Option<Gc<JsObject>>,
151    /// `%AsyncIteratorPrototype%`, the prototype of `%AsyncGeneratorPrototype%`.
152    ///
153    /// It carries exactly two methods — `@@asyncIterator` and `@@asyncDispose` — and is the
154    /// object test262 reaches through
155    /// `Object.getPrototypeOf(Object.getPrototypeOf(generator.prototype))`.
156    pub async_iterator_proto: Option<Gc<JsObject>>,
157    /// `Symbol.prototype`.
158    pub symbol_proto: Option<Gc<JsObject>>,
159    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
160    /// `_date_value`.
161    ///
162    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
163    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
164    /// language does not have and `new Error()` listed `_class` beside `message` and
165    /// `stack` — and a caller that copies every own property (which
166    /// `Object.create(null, props)` effectively does) tried to write an internal name and
167    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
168    /// and `JSON.stringify`, while remaining an ordinary traced property.
169    ///
170    /// `RefCell` because interning is memoisation rather than observable state: filling the
171    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
172    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
173    /// built while reporting a failure must not require an exclusive borrow.
174    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
175
176    /// The `Symbol.for` registry: `key -> symbol`.
177    ///
178    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
179    /// symbol every time within one script while a fresh realm starts empty.
180    pub symbol_registry: BTreeMap<String, Value>,
181    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
182    pub regexp_proto: Option<Gc<JsObject>>,
183    /// The `RegExp` constructor.
184    pub regexp_ctor: Option<Gc<JsObject>>,
185    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
186    ///
187    /// The prototype rather than the constructor on purpose: a script that replaces
188    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
189    /// error wrapping, which the `using` test suite checks explicitly.
190    pub suppressed_error_proto: Option<Gc<JsObject>>,
191    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
192    pub disposable_stack_proto: Option<Gc<JsObject>>,
193    /// `Map.prototype`.
194    pub map_proto: Option<Gc<JsObject>>,
195    /// `Set.prototype`.
196    pub set_proto: Option<Gc<JsObject>>,
197    /// Every live `FinalizationRegistry`, held weakly.
198    ///
199    /// The cleanup callback has to run from a *safe point* — a place where script is not
200    /// already executing and no engine borrow is held — and the collector cannot enumerate
201    /// heap objects by type. Registering each registry here gives the drain a list to walk.
202    ///
203    /// The handles are weak on purpose: a registry the script dropped must be collectable,
204    /// and it must not be resurrected merely because the drain knew about it. Entries whose
205    /// target has expired are swept out as the drain walks, so the vector does not grow
206    /// without bound in a program that creates many short-lived registries.
207    pub finalization_registries: Vec<WeakGc<JsObject>>,
208    /// `ArrayBuffer.prototype`.
209    pub array_buffer_proto: Option<Gc<JsObject>>,
210    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
211    pub typed_array_proto: Option<Gc<JsObject>>,
212    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
213    ///
214    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
215    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
216    /// `"Object"` and `r instanceof Int32Array` is false.
217    pub typed_array_protos: Vec<Gc<JsObject>>,
218    /// `DataView.prototype`.
219    pub data_view_proto: Option<Gc<JsObject>>,
220    /// The `AsyncDisposableStack` prototype.
221    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
222    /// `CreateAsyncFromSyncIterator`, as a script function.
223    ///
224    /// `GetIterator(obj, async)` has to wrap the synchronous iterator it falls back to, and
225    /// the wrapper's state machine is written in JavaScript (see
226    /// [`crate::builtins::async_from_sync`]). Holding the factory here is what lets the Rust
227    /// side call it without a global name a script could shadow.
228    pub async_from_sync: Option<Value>,
229    /// `Iterator.prototype`.
230    pub iterator_proto: Option<Gc<JsObject>>,
231    /// The `Iterator` constructor itself.
232    ///
233    /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
234    /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
235    /// place it can live is the realm.
236    pub iterator_ctor: Option<Gc<JsObject>>,
237    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
238    ///
239    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
240    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
241    /// `[object Iterator Helper]`).
242    pub iterator_helper_proto: Option<Gc<JsObject>>,
243    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
244    /// that was not already an `Iterator`.
245    ///
246    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
247    /// untouched and does *not* override `@@toStringTag`, so
248    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
249    pub iterator_wrap_proto: Option<Gc<JsObject>>,
250    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
251    pub generator_function_proto: Option<Gc<JsObject>>,
252    /// `%AsyncFunction.prototype%`.
253    pub async_function_proto: Option<Gc<JsObject>>,
254    /// `%AsyncGeneratorFunction.prototype%`.
255    pub async_generator_function_proto: Option<Gc<JsObject>>,
256    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
257    ///
258    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
259    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
260    /// prototype per iterator made every array iterator's prototype distinct.
261    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
262    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
263    ///
264    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
265    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
266    /// both faster and impossible to break from a script.
267    well_known_symbols: WellKnownSymbols,
268    /// The classes the host registered, and the prototype each one hands its instances.
269    pub host_classes: HostClasses,
270}
271
272/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
273///
274/// One per realm, because a class id is only meaningful within the runtime that handed it
275/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
276/// a host class cannot collide.
277pub struct HostClasses {
278    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
279    /// `JS_GetOpaque(val, 0)` has to match nothing.
280    next_id: u32,
281    /// What each registered class does.
282    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
283    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
284    ///
285    /// A strong reference, so the prototype a host installed outlives every script
286    /// reference to it — which is what `JS_SetClassProto` promises.
287    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
288}
289
290impl HostClasses {
291    fn new() -> HostClasses {
292        HostClasses {
293            next_id: 1,
294            defs: std::collections::BTreeMap::new(),
295            protos: std::collections::BTreeMap::new(),
296        }
297    }
298
299    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
300    pub fn register(&mut self, def: ClassDef) -> ClassId {
301        let id = ClassId::from_raw(self.next_id);
302        self.next_id += 1;
303        self.defs.insert(id, std::rc::Rc::new(def));
304        id
305    }
306
307    /// Register `def` under an id the caller already has (`JS_NewClass`).
308    ///
309    /// The C API splits "get an id" from "register a class" because a module may be
310    /// initialised lazily; registering twice under one id replaces the definition, and an
311    /// object created under the old one keeps the old behaviour, since it carries its own
312    /// reference.
313    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
314        if !id.is_valid() {
315            return false;
316        }
317        // Keep the counter past any id handed out explicitly, so a later `register` cannot
318        // reuse one.
319        self.next_id = self.next_id.max(id.get() + 1);
320        self.defs.insert(id, std::rc::Rc::new(def));
321        true
322    }
323
324    /// What `id` was registered with.
325    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
326        self.defs.get(&id).cloned()
327    }
328
329    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
330    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
331        self.protos.insert(id, proto);
332    }
333
334    /// The prototype installed for `id`, if the host installed one.
335    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
336        self.protos.get(&id).cloned()
337    }
338
339    /// How many classes the host registered.
340    pub fn len(&self) -> usize {
341        self.defs.len()
342    }
343
344    /// Whether no class has been registered.
345    pub fn is_empty(&self) -> bool {
346        self.defs.is_empty()
347    }
348}
349
350impl Default for HostClasses {
351    fn default() -> HostClasses {
352        HostClasses::new()
353    }
354}
355
356/// One binding of the frame that called `eval`, so the eval'd code can read and
357/// write it by name.
358struct EvalBinding {
359    /// The name it was declared with.
360    name: String,
361    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
362    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
363    /// a function that declares `a` must find that `a`.
364    frame: usize,
365    /// Which table of that frame it lives in.
366    slot: EvalSlot,
367    /// The slot index within that table.
368    index: usize,
369}
370
371/// Which table of a frame an [`EvalBinding`] indexes.
372#[derive(Clone, Copy)]
373enum EvalSlot {
374    Arg,
375    Local,
376}
377
378/// One activation record.
379struct Frame {
380    /// The bytecode being run.
381    code: Gc<CompiledCode>,
382    /// The cells this closure captured.
383    env: Gc<ClosureEnv>,
384    /// The `this` binding.
385    this: Value,
386    /// Argument slots, sized to the declared parameter count.
387    args: Vec<Value>,
388    /// How many values the caller actually passed, which is what `arguments.length`
389    /// reports and what `...rest` slices from.
390    passed_count: usize,
391    /// The passed values, **only when they do not fit in [`Self::args`]**.
392    ///
393    /// `args` is sized to the declared parameters, so a call that passes no more than
394    /// that already holds every passed value in its first `passed_count` slots — copying
395    /// them here as well was two writes and a buffer per call, on the hottest path in
396    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
397    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
398    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
399    /// its own copy.
400    ///
401    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
402    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
403    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
404    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
405    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
406    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
407    #[allow(clippy::box_collection)]
408    passed_overflow: Option<Box<Vec<Value>>>,
409    /// Local slots.
410    locals: Vec<Value>,
411    /// Reference cells for this frame's own captured bindings.
412    cells: Vec<Gc<Cell>>,
413    /// The operand stack.
414    stack: Vec<Value>,
415    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
416    local_vars: Option<Gc<LocalVars>>,
417
418    /// Index of the next instruction, not a byte offset.
419    ///
420    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
421    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
422    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
423    /// `Frame`, and `frames.push` copies the whole struct on every call.
424    pc: usize,
425    /// Byte offset of the instruction being executed, which is what a stack trace
426    /// reports. `pc` has already moved past it by the time an instruction runs.
427    ///
428    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
429    at: usize,
430    /// The callee, so a native builtin can tell which constructor it is.
431    callee: Value,
432    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
433    new_target: Value,
434    /// What this frame costs against [`Interp::stack_limit`], in bytes.
435    ///
436    /// Cached rather than recomputed because it is charged on every call and a call is the
437    /// hottest thing in the interpreter.
438    cost: usize,
439    /// [`Interp::stack_used`] before this frame was pushed.
440    ///
441    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
442    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
443    /// leave the counter wrong. There are eight places that drop frames; one subtraction
444    /// forgotten in any of them would leak budget until the depth limit moved.
445    stack_base: usize,
446    /// Whether this frame's body ended in a `tail_call`.
447    ///
448    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
449    /// with its own frame just like `call` does and only skips storing the result
450    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
451    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
452    /// pushed as usual, and this marker makes its return value the *caller's* return
453    /// value without running the instructions after the call.
454    tail: bool,
455}
456
457impl Frame {
458    /// Read a local slot, taking the frame as `self`.
459    ///
460    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
461    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
462    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
463    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
464    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
465    #[inline]
466    fn read_loc(&self, slot: usize) -> Value {
467        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
468        if cell == -1 {
469            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
470        }
471        match self.cells.get(cell as usize) {
472            Some(cell) => cell.get(),
473            None => Value::Undefined,
474        }
475    }
476
477    /// [`Self::read_loc`] for an argument slot.
478    #[inline]
479    fn read_arg(&self, slot: usize) -> Value {
480        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
481        if cell == -1 {
482            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
483        }
484        match self.cells.get(cell as usize) {
485            Some(cell) => cell.get(),
486            None => Value::Undefined,
487        }
488    }
489
490    /// The values the caller actually passed, which is what `arguments` exposes.
491    ///
492    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
493    fn passed(&self) -> &[Value] {
494        match &self.passed_overflow {
495            Some(values) => values,
496            None => &self.args[..self.passed_count],
497        }
498    }
499
500    /// The decoded instructions of the function this frame runs.
501    ///
502    /// A method rather than `frame.code.insns` at the call site so that the borrow is
503    /// obviously of the frame — the dispatch loop holds one across a `get`.
504    fn insns(&self) -> &[crate::insn::Insn] {
505        &self.code.insns
506    }
507}
508
509impl js_gc::Trace for Frame {
510    fn trace(&self, tracer: &mut js_gc::Tracer) {
511        self.code.trace(tracer);
512        self.env.trace(tracer);
513        self.this.trace(tracer);
514        for value in &self.args {
515            value.trace(tracer);
516        }
517        for value in self.passed() {
518            value.trace(tracer);
519        }
520        for value in &self.locals {
521            value.trace(tracer);
522        }
523        for cell in &self.cells {
524            cell.trace(tracer);
525        }
526        if let Some(local_vars) = &self.local_vars {
527            tracer.visit(local_vars);
528        }
529        for value in &self.stack {
530            value.trace(tracer);
531        }
532        self.callee.trace(tracer);
533        self.new_target.trace(tracer);
534    }
535}
536
537/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
538/// emitted `if_false` treats as "keep going".
539/// How many finished frames' value buffers are kept for reuse.
540const RECYCLE_SLOTS: usize = 8;
541
542/// The largest buffer worth keeping. See [`Interp::free_values`].
543const RECYCLE_MAX_CAPACITY: usize = 4096;
544
545const RESUME_NEXT: i32 = 0;
546/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
547/// generator fall into its `return_async`.
548const RESUME_RETURN: i32 = 1;
549/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
550/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
551/// must forward the exception into the inner iterator rather than finish.
552const RESUME_THROW: i32 = 2;
553
554/// One microtask.
555///
556/// The queue holds *data* rather than closures because its contents are GC values: a
557/// closure would be invisible to the collector, and a pending reaction is exactly the
558/// kind of thing that must keep its handlers and its promise alive.
559pub enum Job {
560    /// A `then` reaction about to run.
561    Reaction {
562        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
563        handler: Option<Value>,
564        /// The value or reason to call it with.
565        argument: Value,
566        /// Whether the source promise rejected, which decides the pass-through kind.
567        rejected: bool,
568        /// The promise the answer settles.
569        promise: Gc<JsObject>,
570    },
571    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
572    Thenable {
573        /// The `then` that was found on the value.
574        then: Value,
575        /// The thenable itself, which becomes `then`'s `this`.
576        value: Value,
577        /// The promise being resolved.
578        promise: Gc<JsObject>,
579    },
580    /// A pending `import(specifier)`.
581    Import {
582        /// The specifier, already converted to a string.
583        specifier: String,
584        /// The module that asked, which the specifier resolves against.
585        referrer: String,
586        /// The promise `import()` handed back.
587        promise: Gc<JsObject>,
588    },
589    /// An async generator resuming after the value it awaited settled.
590    GeneratorResume {
591        /// The async generator to continue.
592        generator: Gc<JsObject>,
593        /// The promise the pending method returned.
594        promise: Gc<JsObject>,
595        /// Whether this delivers the value or raises the reason.
596        kind: ResumeKind,
597        /// The settled value, or the rejection reason.
598        value: Value,
599    },
600    /// An async function resuming after the value it awaited settled.
601    Resume {
602        /// The body, parked in a coroutine.
603        coroutine: Gc<JsObject>,
604        /// The promise the async function handed its caller.
605        promise: Gc<JsObject>,
606        /// Whether this resumption delivers a value or raises one.
607        kind: ResumeKind,
608        /// The settled value, or the rejection reason.
609        value: Value,
610    },
611}
612
613/// One macro-task: work the event loop owes the script but has not run yet.
614///
615/// The microtask queue ([`Job`]) is different: those run before the host regains control.
616/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
617/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
618/// logic: the engine decides *what* is due, the host decides *how to wait*.
619///
620/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
621/// reference counting even though nothing else references it — the same rule the `HostFn`
622/// documentation states from the other side (a host closure must not hold a `Gc`, so the
623/// `Gc` lives here instead).
624pub enum Task {
625    /// A `setTimeout` that is due at `due_at`.
626    ///
627    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
628    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
629    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
630    /// would give this engine a timer the reference cannot produce, with nothing to
631    /// compare it against.
632    Timer {
633        /// The id `setTimeout` returned, for `clearTimeout`.
634        id: i32,
635        /// What to call when it fires.
636        callback: Value,
637        /// When it becomes runnable, as a monotonic instant.
638        due_at: std::time::Instant,
639    },
640}
641
642/// A descriptor the host has to poll, and which directions have a handler.
643///
644/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
645/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
646/// blocks on it, and the host reports back through [`Interp::fire_fd`].
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648pub struct FdInterest {
649    /// The descriptor to watch.
650    pub fd: i32,
651    /// Whether `os.setReadHandler` registered a callback.
652    pub read: bool,
653    /// Whether `os.setWriteHandler` registered a callback.
654    pub write: bool,
655}
656
657/// The callbacks registered for one descriptor, per direction.
658#[derive(Default)]
659pub(crate) struct FdHandlers {
660    /// `os.setReadHandler`'s callback.
661    pub read: Option<Value>,
662    /// `os.setWriteHandler`'s callback.
663    pub write: Option<Value>,
664}
665
666/// The file name `eval` reports, which the reference does not inherit from the caller.
667///
668/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
669/// reference and the names show up in stack traces.
670/// The description of the private symbol a class brand is made from.
671///
672/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
673/// place no script can reach, since no expression can name a private symbol.
674const BRAND_DESCRIPTION: &str = "brand";
675
676/// One validated property lookup.
677///
678/// Covers both own-property hits and prototype hits. The second kind was deliberately left
679/// uncached at first ("a prototype hit depends on more than the object and the name"), and
680/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
681/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
682/// names on every iteration (measured: 100 ns per call over an empty loop).
683pub struct FieldCache {
684    /// The name, so two different properties of one object do not collide.
685    key: PropertyKey,
686    /// Where the value was found, relative to the chain below.
687    index: usize,
688    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
689    level: u8,
690    /// The receiver and every prototype down to (and including) the level that answered,
691    /// each with the length of its property table at the time.
692    ///
693    /// That length is the whole guard, and it is sufficient for the ways the answer can
694    /// change without a lookup: adding or deleting any property moves it, and a
695    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
696    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
697    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
698    /// the one that was cached.
699    ///
700    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
701    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
702    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
703}
704
705/// How many links of a prototype chain a [`FieldCache`] remembers.
706///
707/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
708/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
709/// at three.
710const MAX_CACHED_CHAIN: usize = 3;
711
712/// A remembered global-variable lookup.
713///
714/// A `var` global is an ordinary property of the global object, so reading one walks the
715/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
716/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
717/// fixed by the bytecode, and the slot in the object's table only changes if the global
718/// object is mutated, which the index-and-name check below catches.
719pub struct GlobalCache {
720    /// The global object the lookup was resolved on, weakly.
721    object: js_gc::WeakGc<JsObject>,
722    /// Index of the data property in the global object's table.
723    index: usize,
724}
725
726/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
727const GLOBAL_CACHE_SLOTS: usize = 1024;
728
729/// How many property lookups are remembered.
730///
731/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
732/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
733/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
734/// lookup itself. Making it bigger stops helping: the working set of a real program's
735/// property sites is bounded by its code size.
736const FIELD_CACHE_SLOTS: usize = 4096;
737
738/// How much the heap may grow past the last `out of memory` before saying it again.
739///
740/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
741/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
742/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
743/// because it looks like it works. The reference gets this for free: it fails inside
744/// `js_malloc`, and its printing path happens not to allocate.
745///
746/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
747/// allocating is stopped within a rounding error of the limit) and far above what a
748/// handler needs.
749const OOM_HYSTERESIS: usize = 64 * 1024;
750
751/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
752pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
753
754/// How many instructions run between polls of [`Interp::interrupt`].
755///
756/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
757/// order of magnitude on both implementations — which is what lets a C driver compare its
758/// output byte for byte (see `scripts/m15-capi.sh --embed`).
759pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
760
761/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
762///
763/// Chosen so that the byte budget is what actually decides for every ordinary
764/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
765/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
766/// millions of frames.
767pub const MAX_FRAMES: usize = 200_000;
768
769const EVAL_FILE: &str = "<input>";
770
771/// The file name `std.evalScript` reports.
772const EVAL_SCRIPT_FILE: &str = "<evalScript>";
773
774/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
775///
776/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
777/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
778fn clamp_delay(delay_ms: f64) -> std::time::Duration {
779    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
780    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
781    // non-positive delay mean "due now".
782    if delay_ms.is_nan() || delay_ms <= 0.0 {
783        return std::time::Duration::ZERO;
784    }
785    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
786}
787
788impl js_gc::Trace for Task {
789    fn trace(&self, tracer: &mut js_gc::Tracer) {
790        let Task::Timer { callback, .. } = self;
791        callback.trace(tracer);
792    }
793}
794
795/// What one turn of the event loop did, so the caller cannot spin by accident.
796///
797/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
798/// core until the timer is due. Naming the three cases makes the wait explicit.
799#[derive(Debug, Clone, Copy, PartialEq, Eq)]
800pub enum Turn {
801    /// Something ran. Call again immediately — there may be more ready work.
802    Ran,
803    /// Nothing is runnable, but descriptors are registered: the host must poll
804    /// [`Interp::pending_fds`] for at most this long, then report readiness with
805    /// [`Interp::fire_fd`].
806    ///
807    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
808    /// the failure this project treats as worst — a handler that silently never fires —
809    /// so the two cannot be confused by accident.
810    Poll(std::time::Duration),
811    /// Nothing is runnable yet, but something is pending. Block at most this long, then
812    /// call again.
813    Wait(std::time::Duration),
814    /// Nothing is pending at all: the loop is done.
815    Done,
816}
817
818impl js_gc::Trace for Job {
819    fn trace(&self, tracer: &mut js_gc::Tracer) {
820        match self {
821            Job::Reaction {
822                handler,
823                argument,
824                promise,
825                ..
826            } => {
827                if let Some(handler) = handler {
828                    handler.trace(tracer);
829                }
830                argument.trace(tracer);
831                tracer.visit(promise);
832            }
833            Job::Thenable {
834                then,
835                value,
836                promise,
837            } => {
838                then.trace(tracer);
839                value.trace(tracer);
840                tracer.visit(promise);
841            }
842            Job::Resume {
843                coroutine,
844                promise,
845                value,
846                ..
847            } => {
848                tracer.visit(coroutine);
849                tracer.visit(promise);
850                value.trace(tracer);
851            }
852            Job::Import { promise, .. } => tracer.visit(promise),
853            Job::GeneratorResume {
854                generator,
855                promise,
856                value,
857                ..
858            } => {
859                tracer.visit(generator);
860                tracer.visit(promise);
861                value.trace(tracer);
862            }
863        }
864    }
865}
866
867/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869pub enum ResumeKind {
870    /// The generator was just created and is being run to its first suspension.
871    Start,
872    /// `next(v)`.
873    Next,
874    /// `return(v)`.
875    Return,
876    /// `throw(e)`.
877    Throw,
878}
879
880/// A generator object's saved execution.
881///
882/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
883/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
884/// separately allocated buffers.
885pub struct GeneratorState {
886    /// The detached frame, or `None` once the generator has finished or while it runs.
887    frame: Option<Frame>,
888    /// How far it got.
889    phase: GeneratorPhase,
890    /// Whether the last suspension was an `await` rather than a `yield`.
891    ///
892    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
893    /// value and a magic number, because the emitted code branches on which method
894    /// resumed it, while an `await` simply continues with its value. Getting this wrong
895    /// leaves an extra value on the operand stack that the next instruction then
896    /// consumes — a wrong answer rather than a crash.
897    parked_on_await: bool,
898    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
899    ///
900    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
901    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
902    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
903    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
904    /// delegating. Tracking it as part of the phase, the way the reference splits
905    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
906    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
907    /// exception and never reached `xs.throw`.
908    parked_on_yield_star: bool,
909    /// Pending `next`/`return`/`throw` calls, oldest first.
910    ///
911    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
912    /// called back to back must answer in that order, with the second call's value
913    /// arriving at the *second* `yield`. Running each call straight into the body — which
914    /// is what this engine did before — delivered the last queued value to whichever
915    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
916    /// `a === b ===` the final argument.
917    ///
918    /// The front entry is the one being served; it stays there (with `async_busy` set)
919    /// until its promise settles, because an `await` inside the body is a suspension of
920    /// the *driver*, not the end of the request.
921    requests: std::collections::VecDeque<AsyncRequest>,
922    /// Whether the front request is in flight.
923    async_busy: bool,
924    /// Whether this came from an `async function*`.
925    ///
926    /// A sync generator and an async one share `ObjectKind::Generator`, so without this
927    /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
928    /// `AsyncGeneratorValidate` has to tell them apart
929    /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
930    pub is_async: bool,
931}
932
933/// How one async-generator request ended.
934enum AsyncOutcome {
935    /// The method answered this `{value, done}`.
936    Value(Value),
937    /// The body threw.
938    Error(Value),
939}
940
941/// One queued `next`/`return`/`throw` on an async generator: the reference's
942/// `JSAsyncGeneratorRequest`.
943pub struct AsyncRequest {
944    /// Which method was called.
945    kind: ResumeKind,
946    /// Its argument.
947    value: Value,
948    /// The promise the method answered.
949    promise: Gc<JsObject>,
950}
951
952/// Which of §27.5.3.3's states a generator is in.
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954enum GeneratorPhase {
955    /// Created, `initial_yield` reached, body not entered.
956    SuspendedStart,
957    /// Parked at a `yield`.
958    SuspendedYield,
959    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
960    Executing,
961    /// Finished; the frame is gone.
962    Completed,
963}
964
965impl js_gc::Trace for GeneratorState {
966    fn trace(&self, tracer: &mut js_gc::Tracer) {
967        if let Some(frame) = &self.frame {
968            frame.trace(tracer);
969        }
970        for request in &self.requests {
971            request.value.trace(tracer);
972            tracer.visit(&request.promise);
973        }
974    }
975}
976
977/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
978/// them in.
979///
980/// Each is a field rather than a map entry because the runtime reads them on hot paths
981/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
982/// failure — reaching a default here means the builtin did not install, and every
983/// accessor panics rather than silently answering `undefined`.
984///
985/// [`builtins::symbol`]: crate::builtins::symbol
986#[derive(Default)]
987pub struct WellKnownSymbols {
988    /// The symbol values, positionally. Empty until `Symbol` installs.
989    symbols: Vec<Value>,
990}
991
992/// Which well-known symbol a caller wants.
993///
994/// A typed accessor beats passing a name around: a typo is a compile error rather than
995/// an `undefined` key that quietly matches nothing.
996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
997pub enum WellKnown {
998    /// `Symbol.toPrimitive`.
999    ToPrimitive,
1000    /// `Symbol.iterator`.
1001    Iterator,
1002    /// `Symbol.match`.
1003    Match,
1004    /// `Symbol.matchAll`.
1005    MatchAll,
1006    /// `Symbol.replace`.
1007    Replace,
1008    /// `Symbol.search`.
1009    Search,
1010    /// `Symbol.split`.
1011    Split,
1012    /// `Symbol.toStringTag`.
1013    ToStringTag,
1014    /// `Symbol.isConcatSpreadable`.
1015    IsConcatSpreadable,
1016    /// `Symbol.hasInstance`.
1017    HasInstance,
1018    /// `Symbol.species`.
1019    Species,
1020    /// `Symbol.unscopables`.
1021    Unscopables,
1022    /// `Symbol.asyncIterator`.
1023    AsyncIterator,
1024    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1025    Disposable,
1026    /// `Symbol.asyncDispose` — the awaited form.
1027    AsyncDisposable,
1028}
1029
1030impl WellKnown {
1031    /// The index `Symbol`'s installer creates this symbol at.
1032    fn index(self) -> usize {
1033        match self {
1034            WellKnown::ToPrimitive => 0,
1035            WellKnown::Iterator => 1,
1036            WellKnown::Match => 2,
1037            WellKnown::MatchAll => 3,
1038            WellKnown::Replace => 4,
1039            WellKnown::Search => 5,
1040            WellKnown::Split => 6,
1041            WellKnown::ToStringTag => 7,
1042            WellKnown::IsConcatSpreadable => 8,
1043            WellKnown::HasInstance => 9,
1044            WellKnown::Species => 10,
1045            WellKnown::Unscopables => 11,
1046            WellKnown::AsyncIterator => 12,
1047            WellKnown::Disposable => 13,
1048            WellKnown::AsyncDisposable => 14,
1049        }
1050    }
1051}
1052
1053impl Realm {
1054    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1055    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1056        self.well_known_symbols.symbols = symbols;
1057    }
1058
1059    /// A well-known symbol.
1060    pub fn well_known(&self, which: WellKnown) -> Value {
1061        self.well_known_symbols
1062            .symbols
1063            .get(which.index())
1064            .cloned()
1065            .unwrap_or(Value::Undefined)
1066    }
1067
1068    /// The well-known symbol as a property key.
1069    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1070        match self.well_known(which) {
1071            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1072            // Unreachable once `Symbol` has installed; an empty string key matches
1073            // nothing, which degrades to "the object has no such method".
1074            _ => PropertyKey::from(String::new()),
1075        }
1076    }
1077}
1078
1079/// The interpreter: a realm plus a frame stack.
1080pub struct Interp<'a> {
1081    /// The heap everything is allocated on.
1082    pub heap: &'a Heap,
1083    /// The realm.
1084    pub realm: Realm,
1085    /// Active frames, outermost first.
1086    frames: Vec<Frame>,
1087    /// Value buffers from frames that have finished, reused by the next call.
1088    ///
1089    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1090    /// the locals and the operand stack — and free all four on return. `call:recursion`
1091    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1092    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1093    ///
1094    /// Bounded in both directions: a few buffers per kind, and none larger than
1095    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1096    /// and keeping its buffer would pin that memory for the rest of the run.
1097    free_values: Vec<Vec<Value>>,
1098    /// A strict-mode `eval`'s own variable scope, while its script runs.
1099    ///
1100    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1101    /// become a global. Name lookups still fall through to the realm, which is why
1102    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1103    eval_scope: Option<BTreeMap<String, Value>>,
1104    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1105    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1106    eval_depth: usize,
1107    /// The calling frame's own bindings, which the running `eval` can read and write.
1108    ///
1109    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1110    /// come from the frame, and a write is applied back to the frame (or to the cell
1111    /// the frame captured) when the eval finishes. That is what makes
1112    /// `f("a = 3")` visible to the caller as `a === 3`.
1113    eval_bindings: Vec<EvalBinding>,
1114    /// The calling frame's `arguments`, while an `eval` runs.
1115    ///
1116    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1117    /// own yet still has to see the caller's `arguments`.
1118    eval_arguments: Option<Value>,
1119    /// The `with` objects live at the moment the running `eval` started, innermost first.
1120    ///
1121    /// `None` outside an eval, which is what keeps a finished block's object from
1122    /// shadowing ordinary bytecode reads.
1123    eval_with: Option<Vec<Gc<JsObject>>>,
1124    /// The bindings the running direct `eval` makes visible, as name → cell.
1125    ///
1126    /// Set for the duration of an eval and then restored, but every closure created
1127    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1128    /// `eval("f = () => i")` work after the eval has returned.
1129    active_eval_scope: Option<Gc<EvalScope>>,
1130    /// The frame that called the direct `eval` currently running, if any.
1131    ///
1132    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1133    /// on the global object, which is what keeps
1134    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1135    /// gives each call its own `x`.
1136    eval_caller: Option<Option<usize>>,
1137    /// The caller's `new.target`, while an `eval` runs.
1138    ///
1139    /// The eval'd code is a script with no constructor of its own, so it inherits the
1140    /// one the enclosing function was called with.
1141    eval_new_target: Option<Value>,
1142    /// `new.target` for the frame about to be pushed.
1143    ///
1144    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1145    /// value reaches the frame without threading a parameter through every call site.
1146    ///
1147    /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1148    /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1149    /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1150    /// value was parked for the outer call and never consumed.
1151    pending_new_target: Option<Value>,
1152    /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1153    ///
1154    /// `undefined` outside a `new` call.
1155    active_new_target: Value,
1156    /// Names of the native functions currently executing, outermost first.
1157    ///
1158    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1159    /// trace still names it with `(native)` instead of a position, so the names are
1160    /// tracked separately and stitched into [`Interp::stack_trace`].
1161    ///
1162    /// The third field is how many bytecode frames were live when the native was entered,
1163    /// which is what places it *among* them rather than before all of them. Native
1164    /// functions used to be emitted up front on the grounds that they never re-enter
1165    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1166    /// The natives currently running, innermost last: the function object and the
1167    /// depth it was entered at.
1168    ///
1169    /// The *name* is deliberately not stored. It used to be, read with
1170    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1171    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1172    /// benchmark. A stack trace is built rarely; it can read the name then.
1173    native_frames: Vec<(Gc<JsObject>, usize)>,
1174    /// The native function currently executing, for the ones that have to know *which*
1175    /// function they are — a typed-array constructor reads its element type off itself.
1176    ///
1177    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1178    /// reports whatever the enclosing bytecode frame was called with.
1179    current_native: Option<Gc<JsObject>>,
1180    /// Text written by `print` and friends, in order.
1181    ///
1182    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1183    /// once at the end, which is also when upstream's line buffering becomes
1184    /// visible for the cases compared here.
1185    pub output: String,
1186    /// Where `print` also writes, as it goes. `output` keeps the full log for
1187    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1188    ///
1189    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1190    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1191    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1192    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1193    /// would show a script's output all at once when it finished.
1194    pub output_sink: Option<Box<dyn std::io::Write>>,
1195    /// Where recent property reads found their value.
1196    ///
1197    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1198    /// table remembering *which object* and *which entry of its property table* answered a
1199    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1200    /// can move; the property can become an accessor), which is what makes a stale entry a
1201    /// miss rather than a wrong answer.
1202    ///
1203    /// The object is held weakly: a cache that held it strongly would keep up to
1204    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1205    /// program cannot see and cannot work around.
1206    pub field_cache: Vec<Option<FieldCache>>,
1207    /// Global lookups, by binding slot. See [`GlobalCache`].
1208    global_cache: Vec<Option<GlobalCache>>,
1209    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1210    /// under its limit. See [`Interp::check_memory`].
1211    pub oom_reported_at: usize,
1212    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1213    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1214    ///
1215    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1216    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1217    /// host that wants to stop a runaway script must not have to wait for it to return.
1218    ///
1219    /// Two things this cannot do, both of them differences a host can observe:
1220    ///
1221    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1222    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1223    ///   needs a signal that the `catch` machinery does not see, which is a change to
1224    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1225    ///   a host that stops the script itself.
1226    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1227    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1228    ///   both, so the difference is when the counter hits zero, not whether it will.
1229    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1230    /// Instructions until the next [`Interp::interrupt`] poll.
1231    pub interrupt_counter: u32,
1232    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1233    ///
1234    /// A separate field from [`Interp::uncatchable`] because the two live for different
1235    /// spans. This one is the host's standing request; it survives the start of an
1236    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1237    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1238    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1239    /// cleared it before the script it was set for had a chance to throw.
1240    pub uncatchable_next: bool,
1241    /// Whether the exception now unwinding may be caught by a `catch`.
1242    ///
1243    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1244    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1245    /// a host stopping a runaway loop is not fought by the loop.
1246    ///
1247    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1248    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1249    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1250    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1251    pub uncatchable: bool,
1252    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1253    ///
1254    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1255    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1256    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1257    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1258    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1259    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1260    ///
1261    /// The numbers come out close for the same reason a C frame and a heap frame of this
1262    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1263    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1264    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1265    /// `crates/quickjs-cli/tests/limits.rs`.
1266    pub stack_limit: usize,
1267    /// The most frames that may be live at once, whatever the byte budget says.
1268    ///
1269    /// A second bound for a reason the reference does not have: our frames cost less than
1270    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1271    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1272    /// `--stack-size 1G` from being a memory bomb.
1273    pub max_frames: usize,
1274    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1275    ///
1276    /// Script execution does not return until this has drained, which is what makes
1277    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1278    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1279    /// not a `for`.
1280    pub(crate) jobs: std::collections::VecDeque<Job>,
1281    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1282    ///
1283    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1284    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1285    pub(crate) tasks: Vec<Task>,
1286    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1287    /// barrier'd evaluation started.
1288    ///
1289    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1290    /// lets a REPL report an error from the line it just evaluated without also reporting
1291    /// its own readline loop.
1292    trace_barriers: Vec<usize>,
1293    /// `os.signal` handlers, keyed by signal number.
1294    ///
1295    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1296    /// a handler cannot be freed while it is still registered.
1297    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1298    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1299    ///
1300    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1301    /// that is only reachable from a host closure could be freed while still registered.
1302    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1303    /// The next timer id.
1304    ///
1305    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1306    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1307    next_timer_id: i32,
1308    /// Errors thrown by timer callbacks, already rendered.
1309    ///
1310    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1311    /// that throws has no promise behind it. Both are reported by the host at the end of
1312    /// the loop, but only one is fixed up by a later `.catch`.
1313    timer_errors: Vec<String>,
1314    /// The module registry, keyed by canonical name.
1315    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1316    /// How the host turns a specifier into bytes.
1317    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1318    /// The module the host was asked to run, for `import.meta.main`.
1319    pub main_module_name: Option<String>,
1320    /// The name to register the *entry* module under, when the host supplies one.
1321    ///
1322    /// The entry's bytes come from a path on disk; this is the name the module graph should
1323    /// know it by. They differ for a host that evaluates a file it did not write — a test
1324    /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1325    /// a module importing *itself* resolves the specifier against the real path, finds no
1326    /// record under that name, and loads a second copy with its own bindings.
1327    pub entry_module_name: Option<String>,
1328    /// Module bodies currently running, innermost last.
1329    ///
1330    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1331    /// this is the only place that knows which module that is.
1332    pub module_stack: Vec<String>,
1333    /// Rejections that no handler has claimed, with the promise they belong to.
1334    ///
1335    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1336    /// reason alone cannot say whether somebody eventually listened.
1337    unhandled: Vec<(Gc<JsObject>, Value)>,
1338}
1339
1340impl<'a> Interp<'a> {
1341    /// Build an interpreter over `heap`, with a fresh realm.
1342    pub fn new(heap: &'a Heap) -> Interp<'a> {
1343        let object_proto = JsObject::ordinary(heap, None);
1344        let function_proto = JsObject::function(
1345            heap,
1346            Some(object_proto.clone()),
1347            Callable::Native {
1348                func: |_, _, _| Ok(Value::Undefined),
1349                own_instance: false,
1350            },
1351        );
1352        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1353        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1354        let mut interp = Interp {
1355            heap,
1356            realm: Realm {
1357                global,
1358                object_proto,
1359                function_proto,
1360                array_proto,
1361                array_constructor: None,
1362                promise_constructor: None,
1363                object_proto_to_string: None,
1364                globals: BTreeMap::new(),
1365                declared: Vec::new(),
1366                lexical_consts: BTreeSet::new(),
1367                errors: BTreeMap::new(),
1368                string_proto: None,
1369                number_proto: None,
1370                boolean_proto: None,
1371                bigint_proto: None,
1372                error_proto: JsObject::ordinary(heap, None),
1373                date_proto: JsObject::ordinary(heap, None),
1374                throw_type_error: None,
1375                generator_proto: JsObject::ordinary(heap, None),
1376                promise_proto: None,
1377                async_generator_proto: None,
1378                async_iterator_proto: None,
1379                symbol_proto: None,
1380                symbol_registry: BTreeMap::new(),
1381                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1382                regexp_proto: None,
1383                regexp_ctor: None,
1384                suppressed_error_proto: None,
1385                disposable_stack_proto: None,
1386                map_proto: None,
1387                set_proto: None,
1388                finalization_registries: Vec::new(),
1389                array_buffer_proto: None,
1390                typed_array_proto: None,
1391                typed_array_protos: Vec::new(),
1392                data_view_proto: None,
1393                async_disposable_stack_proto: None,
1394                async_from_sync: None,
1395                iterator_proto: None,
1396                iterator_ctor: None,
1397                iterator_helper_proto: None,
1398                iterator_wrap_proto: None,
1399                generator_function_proto: None,
1400                async_function_proto: None,
1401                async_generator_function_proto: None,
1402                iterator_protos: std::collections::BTreeMap::new(),
1403                well_known_symbols: WellKnownSymbols::default(),
1404                host_classes: HostClasses::new(),
1405            },
1406            frames: Vec::new(),
1407            free_values: Vec::new(),
1408            global_cache: {
1409                let mut cache = Vec::new();
1410                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1411                cache
1412            },
1413            eval_scope: None,
1414            eval_depth: 0,
1415            eval_bindings: Vec::new(),
1416            eval_arguments: None,
1417            eval_with: None,
1418            active_eval_scope: None,
1419            eval_caller: None,
1420            pending_new_target: None,
1421            active_new_target: Value::Undefined,
1422            eval_new_target: None,
1423            native_frames: Vec::new(),
1424            current_native: None,
1425            output: String::new(),
1426            output_sink: None,
1427            field_cache: {
1428                let mut cache = Vec::new();
1429                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1430                cache
1431            },
1432            oom_reported_at: 0,
1433            interrupt: None,
1434            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1435            uncatchable_next: false,
1436            uncatchable: false,
1437            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1438            // absent.
1439            stack_limit: DEFAULT_STACK_SIZE,
1440            max_frames: MAX_FRAMES,
1441            jobs: std::collections::VecDeque::new(),
1442            tasks: Vec::new(),
1443            trace_barriers: Vec::new(),
1444            signal_handlers: std::collections::BTreeMap::new(),
1445            fd_handlers: std::collections::BTreeMap::new(),
1446            next_timer_id: 1,
1447            timer_errors: Vec::new(),
1448            modules: std::collections::BTreeMap::new(),
1449            module_loader: None,
1450            main_module_name: None,
1451            entry_module_name: None,
1452            module_stack: Vec::new(),
1453            unhandled: Vec::new(),
1454        };
1455        crate::builtins::install(&mut interp);
1456        interp
1457    }
1458
1459    // -- allocation helpers -------------------------------------------------
1460
1461    /// A new string value.
1462    /// A `BigInt` value from a computed big integer.
1463    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1464        Value::BigInt(Gc::new(self.heap, value))
1465    }
1466
1467    /// A string value from bytes that are already WTF-8, which is how a string with an
1468    /// unpaired surrogate reaches a `Value`.
1469    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1470        Value::string_wtf8(self.heap, text)
1471    }
1472
1473    /// A new string value, from text that is valid UTF-8.
1474    pub fn string(&self, text: impl Into<String>) -> Value {
1475        Value::string(self.heap, text)
1476    }
1477
1478    /// A new ordinary object with the given prototype.
1479    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1480        JsObject::ordinary(self.heap, proto)
1481    }
1482
1483    // -- host classes -------------------------------------------------------
1484
1485    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1486    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1487        self.realm.host_classes.register(def)
1488    }
1489
1490    /// Register `def` under an id the host already holds (`JS_NewClass`).
1491    ///
1492    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1493    /// `JS_NewClass`.
1494    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1495        self.realm.host_classes.define(id, def)
1496    }
1497
1498    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1499    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1500        self.realm.host_classes.set_proto(id, proto);
1501    }
1502
1503    /// The prototype installed for `id`, if any.
1504    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1505        self.realm.host_classes.proto(id)
1506    }
1507
1508    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1509    ///
1510    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1511    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1512    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1513    /// host installed none.
1514    ///
1515    /// Answers `None` for an id that was never registered: the C API would return an
1516    /// exception, and silently making an ordinary object instead would move the failure to
1517    /// the first `JS_GetOpaque` that no longer matches.
1518    pub fn new_host_object(
1519        &mut self,
1520        proto: Option<Gc<JsObject>>,
1521        class_id: ClassId,
1522    ) -> Option<Gc<JsObject>> {
1523        let class = self.realm.host_classes.def(class_id)?;
1524        let proto = proto
1525            .or_else(|| self.realm.host_classes.proto(class_id))
1526            .or_else(|| Some(self.realm.object_proto.clone()));
1527        Some(JsObject::host_object(self.heap, proto, class_id, class))
1528    }
1529
1530    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1531    ///
1532    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1533    /// object, it is an object of another class, or the class never got a payload. A host
1534    /// that has to tell them apart uses [`JsObject::host_class_id`].
1535    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1536        let object = value.as_object()?;
1537        if object.host_class_id()? != class_id {
1538            return None;
1539        }
1540        object.host_opaque()
1541    }
1542
1543    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1544    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1545        match value.as_object() {
1546            Some(object) => object.set_host_opaque(opaque),
1547            None => false,
1548        }
1549    }
1550
1551    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1552    ///
1553    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1554    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1555    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1556    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1557    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1558    /// said `[object Object]` instead of `[object Array Iterator]`.
1559    ///
1560    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1561    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1562    /// its own.
1563    pub fn new_iterator_prototype(
1564        &mut self,
1565        tag: &str,
1566        next: crate::object::NativeFn,
1567    ) -> Gc<JsObject> {
1568        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1569            return existing.clone();
1570        }
1571        let parent = self.realm.iterator_proto.clone();
1572        let proto = self.new_object(parent);
1573        let next = self.new_native("next", 0, next);
1574        proto.define(
1575            "next",
1576            Property::with_attributes(Value::Object(next), true, false),
1577        );
1578        let key = self.realm.well_known_key(WellKnown::Iterator);
1579        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1580        proto.define_key(
1581            &key,
1582            Property::with_attributes(Value::Object(identity), true, false),
1583        );
1584        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1585        let tag_value = self.string(tag);
1586        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1587        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1588        // checks it.
1589        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1590        self.realm
1591            .iterator_protos
1592            .insert(tag.to_string(), proto.clone());
1593        proto
1594    }
1595
1596    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1597    ///
1598    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1599    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1600    /// produced. That is why the two branches are not merged.
1601    pub fn object_own_property_keys(
1602        &mut self,
1603        object: &Gc<JsObject>,
1604    ) -> JsResult<Vec<PropertyKey>> {
1605        if let Some(keys) = self.proxy_own_keys(object)? {
1606            return Ok(keys);
1607        }
1608        // Integer-like keys ascending, then the string keys in insertion order, then the
1609        // symbols — the order every schema that walks an object expects.
1610        let entries = object.property_entries();
1611        let mut numeric: Vec<u32> = Vec::new();
1612        // An integer-indexed exotic object reports its indices as own keys even though they
1613        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1614        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1615        // order). The length is asked per call, so a resizable buffer's view reports the
1616        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1617        if object.typed_array_parts().is_some() {
1618            for index in 0..object.typed_array_length().unwrap_or(0) {
1619                // `u32::try_from` cannot fail for a real length, but the length is a
1620                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1621                // as an array index and one element beyond is not.
1622                match u32::try_from(index) {
1623                    Ok(index) => numeric.push(index),
1624                    Err(_) => break,
1625                }
1626            }
1627        }
1628        let mut strings: Vec<PropertyKey> = Vec::new();
1629        let mut symbols: Vec<PropertyKey> = Vec::new();
1630        for (key, _) in entries {
1631            match &key {
1632                // A class-private name is never reported by any enumeration: that is the
1633                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1634                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1635                // symbol skip, `Object.assign`) therefore cannot see it.
1636                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1637                PropertyKey::Symbol(_) => symbols.push(key),
1638                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1639                    Some(index) => {
1640                        if !numeric.contains(&index) {
1641                            numeric.push(index);
1642                        }
1643                    }
1644                    None => strings.push(key),
1645                },
1646            }
1647        }
1648        // An array's `length` is an own property from the moment the array exists, so it
1649        // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1650        // as `["length", "a"]`, not `["a", "length"]`
1651        // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1652        // than stored in the property table, which is why it has to be placed here.
1653        if object.is_array() && object.proxy_state().is_none() {
1654            // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1655            // the property table, at whatever position the *define* happened, but the key
1656            // lists it as the array's oldest string property because that is what it is.
1657            if let Some(position) = strings
1658                .iter()
1659                .position(|key| key.as_str() == Some("length"))
1660            {
1661                strings.remove(position);
1662            }
1663            strings.insert(0, PropertyKey::from("length"));
1664        }
1665        numeric.sort_unstable();
1666        let mut keys: Vec<PropertyKey> = numeric
1667            .into_iter()
1668            .map(|index| PropertyKey::from(index.to_string()))
1669            .collect();
1670        keys.extend(strings);
1671        keys.extend(symbols);
1672        Ok(keys)
1673    }
1674
1675    /// The state behind a promise object, or `None` when `object` is not one.
1676    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1677        object.with(|data| match &data.kind {
1678            ObjectKind::Promise(state) => Some(state.clone()),
1679            _ => None,
1680        })
1681    }
1682
1683    /// A new pending promise.
1684    pub fn new_promise(&mut self) -> Gc<JsObject> {
1685        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1686        // the one place every promise is built, and a subclass that builds its instances
1687        // somewhere else would be invisible to `instanceof`.
1688        let default = self.realm.promise_proto.clone();
1689        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1690        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1691        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1692        // `prototype` getter therefore still gets a working promise; the alternative is a
1693        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1694        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1695        Self::make_promise_object(self.heap, proto)
1696    }
1697
1698    /// A promise object with an explicit prototype, and nothing else.
1699    ///
1700    /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1701    /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1702    /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1703    /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1704    pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1705        let promise = JsObject::ordinary(heap, proto);
1706        promise.with_mut(|data| {
1707            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1708                crate::object::PromiseState::default(),
1709            )));
1710        });
1711        promise
1712    }
1713
1714    /// Fulfil `promise`, unless it has already settled.
1715    ///
1716    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1717    /// after `reject`, changes nothing.
1718    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1719        let Some(state) = self.promise_state(promise) else {
1720            return;
1721        };
1722        let reactions = {
1723            let mut state = state.borrow_mut();
1724            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1725                return;
1726            }
1727            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1728            std::mem::take(&mut state.reactions)
1729        };
1730        self.queue_reactions(reactions, value, false);
1731    }
1732
1733    /// Reject `promise`, unless it has already settled.
1734    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1735        let Some(state) = self.promise_state(promise) else {
1736            return;
1737        };
1738        let reactions = {
1739            let mut state = state.borrow_mut();
1740            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1741                return;
1742            }
1743            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1744            std::mem::take(&mut state.reactions)
1745        };
1746        // Remember it only when nothing is listening *now*; a `then` registered later
1747        // prunes the entry in `perform_then`.
1748        if reactions.is_empty() {
1749            self.unhandled.push((promise.clone(), reason.clone()));
1750        }
1751        self.queue_reactions(reactions, reason, true);
1752    }
1753
1754    /// Queue one job per reaction.
1755    ///
1756    /// This is what makes `then` asynchronous even on an already-settled promise:
1757    /// `p.then(f); g()` calls `g` first.
1758    fn queue_reactions(
1759        &mut self,
1760        reactions: Vec<crate::object::PromiseReaction>,
1761        argument: Value,
1762        rejected: bool,
1763    ) {
1764        for reaction in reactions {
1765            let handler = if rejected {
1766                reaction.on_rejected.clone()
1767            } else {
1768                reaction.on_fulfilled.clone()
1769            };
1770            self.jobs.push_back(Job::Reaction {
1771                handler,
1772                argument: argument.clone(),
1773                rejected,
1774                promise: reaction.promise,
1775            });
1776        }
1777    }
1778
1779    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1780    /// resolve/reject pair.
1781    ///
1782    /// The pair are callable objects rather than Rust closures, because the script gets
1783    /// them and may stash them for later.
1784    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1785        let promise = self.new_promise();
1786        // Both handlers are built-ins with an empty name and length 1, in
1787        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1788        // off `Object.getOwnPropertyNames`.
1789        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1790        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1791        (promise, Value::Object(resolve), Value::Object(reject))
1792    }
1793
1794    /// §27.2.1.5 `NewPromiseCapability(C)`.
1795    ///
1796    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1797    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1798    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1799    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1800    /// silently ignored argument.
1801    ///
1802    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1803    /// the engine's own executor is exactly what `new_promise_capability` builds.
1804    pub fn new_promise_capability_for(
1805        &mut self,
1806        constructor: &Value,
1807    ) -> JsResult<(Value, Value, Value)> {
1808        let Some(object) = constructor.as_object().cloned() else {
1809            return Err(self.type_error("promise constructor is not a constructor"));
1810        };
1811        if !object.is_constructor() {
1812            return Err(self.type_error("promise constructor is not a constructor"));
1813        }
1814        if self
1815            .realm
1816            .promise_constructor
1817            .as_ref()
1818            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1819        {
1820            let (promise, resolve, reject) = self.new_promise_capability();
1821            return Ok((Value::Object(promise), resolve, reject));
1822        }
1823        let state = self.new_object(Some(self.realm.object_proto.clone()));
1824        // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1825        // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1826        // which only a *custom* constructor can observe, and none of the combinator tests
1827        // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1828        let executor = self.builtin_function(
1829            "",
1830            2,
1831            Callable::CapabilityExecutor {
1832                state: state.clone(),
1833            },
1834        );
1835        let promise = self.construct(
1836            Value::Object(object.clone()),
1837            Value::Object(object),
1838            vec![Value::Object(executor)],
1839        )?;
1840        // The pair is read *after* the constructor returns, so a constructor that never
1841        // called its executor, or called it with non-callables, is the spec's step 11
1842        // `TypeError` — not something the engine can paper over.
1843        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1844            return Err(self.type_error("promise executor never ran"));
1845        };
1846        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1847            return Err(self.type_error("promise executor never ran"));
1848        };
1849        for handler in [&resolve, &reject] {
1850            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1851                return Err(self.type_error("promise capability handler is not callable"));
1852            }
1853        }
1854        Ok((promise, resolve, reject))
1855    }
1856
1857    /// §27.2.3.1 `PromiseResolve(C, x)`.
1858    ///
1859    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1860    /// an `x` that is already a promise of exactly this constructor is handed back
1861    /// unchanged, and anything else gets a fresh capability from `C`.
1862    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1863        if let Value::Object(object) = &value
1864            && self.promise_state(object).is_some()
1865        {
1866            // `x.constructor === C` means "already the right kind", so no capability is
1867            // built — which is observable through a `resolve` that counts its calls.
1868            let x_constructor = self.get_property(object, "constructor")?;
1869            let same = match (
1870                x_constructor.as_ref().and_then(Value::as_object),
1871                constructor.as_object(),
1872            ) {
1873                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1874                _ => false,
1875            };
1876            if same {
1877                return Ok(value);
1878            }
1879        }
1880        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1881        // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1882        // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1883        // the intrinsic one swallows its own self-resolution error.
1884        self.call_value(resolve, Value::Undefined, vec![value])?;
1885        Ok(promise)
1886    }
1887
1888    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1889    /// promise, as `{ value: completion }`.
1890    ///
1891    /// The three cases are the reference's, and they differ on purpose:
1892    ///
1893    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1894    ///   exception before any promise exists;
1895    /// * a **runtime** error rejects the returned promise;
1896    /// * success resolves it with `{ value }`, where the value is the script's completion
1897    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1898    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1899    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1900    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1901    ///
1902    /// # What this does not do
1903    ///
1904    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1905    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1906    /// the parser and the suspension machinery to accept a suspended top-level script, and
1907    /// is not implemented — such source is a syntax error here. Everything else about the
1908    /// flag is reproduced.
1909    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1910        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1911        // too, and the reference truncates that one at the same place as a runtime failure.
1912        if barrier {
1913            let depth = self.frames.len();
1914            self.trace_barriers.push(depth);
1915        }
1916        // Compiled before the promise exists, so a parse failure propagates as a throw
1917        // instead of being folded into a rejection.
1918        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1919            Ok(compiled) => compiled,
1920            Err(error) => {
1921                if barrier {
1922                    self.trace_barriers.pop();
1923                }
1924                return Err(error);
1925            }
1926        };
1927        // An async body answers its own promise, and that promise is what the reference
1928        // hands back — the same object, not a wrapper around it. Its resolution value is
1929        // the `{value}` object the compiled epilogue built.
1930        if compiled.kind.is_async() {
1931            let strict = compiled.strict;
1932            let promise = self.run_eval_script(compiled, strict)?;
1933            if barrier {
1934                self.trace_barriers.pop();
1935            }
1936            return Ok(promise);
1937        }
1938        let (promise, resolve, reject) = self.new_promise_capability();
1939        let strict = compiled.strict;
1940        match self.run_eval_script(compiled, strict) {
1941            Ok(value) => {
1942                // `{ value }` is a plain object, so resolving with it adopts nothing even
1943                // when the completion value is itself a promise.
1944                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1945                self.set_property(&wrapped, "value", value)?;
1946                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1947            }
1948            Err(Signal::Throw(error)) => {
1949                self.call_value(reject, Value::Undefined, vec![error])?;
1950            }
1951            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1952        }
1953        if barrier {
1954            self.trace_barriers.pop();
1955        }
1956        Ok(Value::Object(promise))
1957    }
1958
1959    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1960    ///
1961    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1962    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1963    /// timer table, where the collector already scans it.
1964    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1965        let (promise, resolve, _reject) = self.new_promise_capability();
1966        let resolve = self.new_host_function(
1967            "resolve",
1968            1,
1969            Box::new(
1970                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1971                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1972                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1973                },
1974            ),
1975        );
1976        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1977        // timer table is part of what the collector walks.
1978        self.schedule_timer(Value::Object(resolve), delay_ms);
1979        Ok(Value::Object(promise))
1980    }
1981
1982    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1983    /// new promise resolved with it.
1984    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1985        if let Value::Object(object) = &value
1986            && self.promise_state(object).is_some()
1987        {
1988            return Ok(value);
1989        }
1990        let promise = self.new_promise();
1991        self.resolve_promise_with(&promise, value)?;
1992        Ok(Value::Object(promise))
1993    }
1994
1995    /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1996    ///
1997    /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1998    /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1999    /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2000    /// therefore observable — which is exactly what
2001    /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2002    /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2003    /// shortcut.
2004    pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2005        if let Value::Object(object) = &value
2006            && self.promise_state(object).is_some()
2007        {
2008            let constructor = self.get_property(object, "constructor")?;
2009            let same = match (&constructor, &self.realm.promise_constructor) {
2010                (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2011                _ => false,
2012            };
2013            if same {
2014                return Ok(value);
2015            }
2016        }
2017        let promise = self.new_promise();
2018        self.resolve_promise_with(&promise, value)?;
2019        Ok(Value::Object(promise))
2020    }
2021
2022    /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2023    ///
2024    /// The pair of resolving functions a promise hands to its executor shares this record, so
2025    /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2026    /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2027    pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2028        let Some(state) = self.promise_state(promise) else {
2029            return true;
2030        };
2031        let mut state = state.borrow_mut();
2032        if state.resolved {
2033            return false;
2034        }
2035        state.resolved = true;
2036        true
2037    }
2038
2039    /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2040    fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2041        let Some(state) = self.promise_state(promise) else {
2042            return;
2043        };
2044        state.borrow_mut().resolved = false;
2045    }
2046
2047    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2048    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2049        // Resolving a promise with itself is a `TypeError`. The check exists because the
2050        // alternative is a chain of self-reactions that never settles.
2051        if let Value::Object(object) = &value
2052            && object.ptr_eq(promise)
2053        {
2054            // The spec rejects *and* throws, so both the promise and the caller see it.
2055            let thrown = self.type_error("cannot resolve a promise with itself");
2056            let Signal::Throw(error) = thrown.clone() else {
2057                unreachable!("type_error always throws")
2058            };
2059            self.reject_promise(promise, error);
2060            return Err(thrown);
2061        }
2062        // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2063        // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2064        // whoever resolved it — a poisoned `then` getter is the case every
2065        // `*-poisoned-then` test is written against.
2066        let then = match &value {
2067            Value::Object(object) => match self.get_property(object, "then") {
2068                Ok(then) => then,
2069                Err(signal) => {
2070                    if let Signal::Throw(reason) = signal {
2071                        self.reject_promise(promise, reason);
2072                        return Ok(());
2073                    }
2074                    return Err(signal);
2075                }
2076            },
2077            _ => None,
2078        };
2079        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2080        if !callable_then {
2081            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2082            self.fulfill_promise(promise, value);
2083            return Ok(());
2084        }
2085        // Adopting a thenable is asynchronous — `then` is called from a job, never from
2086        // inside `resolve`, so a script cannot make a promise settle synchronously.
2087        self.jobs.push_back(Job::Thenable {
2088            then: then.expect("checked callable"),
2089            value,
2090            promise: promise.clone(),
2091        });
2092        Ok(())
2093    }
2094
2095    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2096    ///
2097    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2098    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2099    ///
2100    /// The property read is **not** short-circuitable even for a real promise: the spec says
2101    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2102    /// expects it to run. Skipping the read for promises not only lost the throw, it made
2103    /// the combinator's loop infinite — the test's iterator never sets `done`.
2104    pub fn invoke_then(
2105        &mut self,
2106        thenable: Value,
2107        on_fulfilled: Value,
2108        on_rejected: Value,
2109    ) -> JsResult<()> {
2110        let then = match &thenable {
2111            Value::Object(object) => self.get_property(object, "then")?,
2112            primitive => {
2113                let boxed = self.object_from(primitive)?;
2114                self.get_property(&boxed, "then")?
2115            }
2116        };
2117        let Some(then) = then else {
2118            return Err(self.type_error("thenable has no then method"));
2119        };
2120        if !matches!(&then, Value::Object(object) if object.is_callable()) {
2121            return Err(self.type_error("then is not a function"));
2122        }
2123        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2124        Ok(())
2125    }
2126
2127    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2128    ///
2129    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2130    /// promise.
2131    pub fn perform_then(
2132        &mut self,
2133        promise: &Gc<JsObject>,
2134        on_fulfilled: Option<Value>,
2135        on_rejected: Option<Value>,
2136    ) -> JsResult<Value> {
2137        let Some(state) = self.promise_state(promise) else {
2138            return Err(self.type_error("not a promise"));
2139        };
2140        // Whether a rejection handler is being attached decides whether a recorded
2141        // rejection stops being unhandled, so it is read before the values are moved.
2142        let has_rejection_handler = on_rejected.is_some();
2143        let derived = self.new_promise();
2144        let reaction = crate::object::PromiseReaction {
2145            on_fulfilled,
2146            on_rejected,
2147            promise: derived.clone(),
2148        };
2149        let settled = {
2150            let mut state = state.borrow_mut();
2151            // A rejection somebody reacts to is no longer unhandled.
2152            state.handled = true;
2153            match &state.status {
2154                crate::object::PromiseStatus::Pending => {
2155                    state.reactions.push(reaction.clone());
2156                    None
2157                }
2158                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2159                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2160            }
2161        };
2162        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2163        // later, means somebody is listening after all.
2164        if has_rejection_handler {
2165            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2166        }
2167        if let Some((argument, rejected)) = settled {
2168            let handler = if rejected {
2169                reaction.on_rejected
2170            } else {
2171                reaction.on_fulfilled
2172            };
2173            self.jobs.push_back(Job::Reaction {
2174                handler,
2175                argument,
2176                rejected,
2177                promise: reaction.promise,
2178            });
2179        }
2180        Ok(Value::Object(derived))
2181    }
2182
2183    /// The rejections nobody listened to, formatted the way the reference reports them.
2184    ///
2185    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2186    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2187    /// unhandled at the point the queue drains, because a `then` may still be attached
2188    /// before the host acts on it.
2189    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2190        let entries = std::mem::take(&mut self.unhandled);
2191        // Somebody may have attached a handler after the rejection was recorded, so the
2192        // promise is the authority rather than the list.
2193        let still_unhandled: Vec<Value> = entries
2194            .into_iter()
2195            .filter_map(|(promise, reason)| {
2196                let handled = self
2197                    .promise_state(&promise)
2198                    .map(|state| state.borrow().handled)
2199                    .unwrap_or(true);
2200                (!handled).then_some(reason)
2201            })
2202            .collect();
2203        still_unhandled
2204            .into_iter()
2205            .map(|reason| {
2206                let text = self.describe_exception(&reason);
2207                let stack = match &reason {
2208                    Value::Object(object) => self
2209                        .get_property(object, "stack")
2210                        .ok()
2211                        .flatten()
2212                        .map(|value| value.to_js_string())
2213                        // `stack` carries a trailing newline of its own, which would leave
2214                        // a blank line between two reported rejections.
2215                        .map(|text| text.trim_end().to_string())
2216                        .unwrap_or_default(),
2217                    _ => String::new(),
2218                };
2219                if stack.is_empty() {
2220                    format!("Possibly unhandled promise rejection: {text}")
2221                } else {
2222                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2223                }
2224            })
2225            .collect()
2226    }
2227
2228    /// Run the microtask queue to exhaustion.
2229    ///
2230    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2231    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2232    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2233    ///
2234    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2235    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2236    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2237    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2238        crate::builtins::json::parse_text(self, text, true)
2239    }
2240
2241    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2242    ///
2243    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2244    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2245    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2246    ///
2247    /// The callback is called with **no arguments**. The reference stores only the function
2248    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2249    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2250    /// extra arguments arrive as `undefined`.
2251    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2252        let id = self.next_timer_id;
2253        // Wrap rather than grow: the id reaches the script as an `Int32`.
2254        self.next_timer_id = if self.next_timer_id == i32::MAX {
2255            1
2256        } else {
2257            self.next_timer_id + 1
2258        };
2259        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2260        self.tasks.push(Task::Timer {
2261            id,
2262            callback,
2263            due_at,
2264        });
2265        id
2266    }
2267
2268    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2269    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2270    pub fn cancel_timer(&mut self, id: i32) -> bool {
2271        let before = self.tasks.len();
2272        self.tasks.retain(|task| match task {
2273            Task::Timer { id: task_id, .. } => *task_id != id,
2274        });
2275        self.tasks.len() != before
2276    }
2277
2278    /// How long until the earliest pending timer, or `None` when none is pending.
2279    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2280        let now = std::time::Instant::now();
2281        self.tasks
2282            .iter()
2283            .map(|task| match task {
2284                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2285            })
2286            .min()
2287    }
2288
2289    /// Run one turn of the event loop.
2290    ///
2291    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2292    /// run at most one due timer, then drain again. The blocking belongs to the caller
2293    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2294    /// is how it asks.
2295    ///
2296    /// One timer per turn rather than all of them: a timer callback may schedule another
2297    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2298    /// starve the microtask queue.
2299    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2300        self.drain_jobs()?;
2301        let now = std::time::Instant::now();
2302        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2303        // followed by `setTimeout(g, 1)` must run `g` first.
2304        let due = self
2305            .tasks
2306            .iter()
2307            .enumerate()
2308            .filter(|(_, task)| match task {
2309                Task::Timer { due_at, .. } => *due_at <= now,
2310            })
2311            .min_by_key(|(_, task)| match task {
2312                Task::Timer { due_at, .. } => *due_at,
2313            })
2314            .map(|(index, _)| index);
2315        let Some(index) = due else {
2316            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2317            // descriptor is registered but no timer is closer, so a script that never
2318            // touches the descriptor still gets control back. Without a cap a handler on a
2319            // descriptor that is never ready would block for as long as the host allows.
2320            let timeout = self
2321                .next_timeout()
2322                .unwrap_or(std::time::Duration::from_secs(10))
2323                .min(std::time::Duration::from_secs(10));
2324            if !self.fd_handlers.is_empty() {
2325                // Blocking on a timer while descriptors are registered would starve them,
2326                // and blocking on the descriptors while a timer is due would delay it; the
2327                // host polls with the earlier of the two deadlines, which this timeout is.
2328                return Ok(Turn::Poll(timeout));
2329            }
2330            return Ok(match self.next_timeout() {
2331                Some(wait) => Turn::Wait(wait),
2332                None => Turn::Done,
2333            });
2334        };
2335        let Task::Timer { callback, .. } = self.tasks.remove(index);
2336        let this = Value::Undefined;
2337        // A throwing timer callback must not stop the loop: the reference reports it and
2338        // keeps going, because the alternative is that one bad timer silently stops every
2339        // later one.
2340        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2341        match self.call_value(callback, this, Vec::new()) {
2342            Ok(_) => {}
2343            Err(Signal::Throw(value)) => {
2344                let text = self.describe_exception(&value);
2345                self.timer_errors.push(text);
2346            }
2347            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2348        }
2349        self.drain_jobs()?;
2350        Ok(Turn::Ran)
2351    }
2352
2353    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2354    ///
2355    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2356    /// left is removed — the reference does the same, so a script can rely on
2357    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2358    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2359        let entry = self.fd_handlers.entry(fd).or_default();
2360        if readable {
2361            entry.read = callback;
2362        } else {
2363            entry.write = callback;
2364        }
2365        if entry.read.is_none() && entry.write.is_none() {
2366            self.fd_handlers.remove(&fd);
2367        }
2368    }
2369
2370    /// Register or clear an `os.signal` handler.
2371    ///
2372    /// `None` removes it; the host separately restores the default disposition or sets
2373    /// ignore, because which of those happened is the script's choice (`null` versus
2374    /// `undefined`) and not something this table can express.
2375    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2376        match handler {
2377            Some(handler) => {
2378                self.signal_handlers.insert(signal, handler);
2379            }
2380            None => {
2381                self.signal_handlers.remove(&signal);
2382            }
2383        }
2384    }
2385
2386    /// Run the handler for `signal`, reporting whether one ran.
2387    ///
2388    /// A throwing handler is reported and the loop continues, like a timer's.
2389    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2390        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2391            return Ok(false);
2392        };
2393        match self.call_value(handler, Value::Undefined, Vec::new()) {
2394            Ok(_) => {}
2395            Err(Signal::Throw(value)) => {
2396                let text = self.describe_exception(&value);
2397                self.timer_errors.push(text);
2398            }
2399            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2400        }
2401        self.drain_jobs()?;
2402        Ok(true)
2403    }
2404
2405    /// The descriptors the host has to poll, and in which direction.
2406    ///
2407    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2408    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2409    /// `os_poll` asks for.
2410    pub fn pending_fds(&self) -> Vec<FdInterest> {
2411        self.fd_handlers
2412            .iter()
2413            .map(|(fd, entry)| FdInterest {
2414                fd: *fd,
2415                read: entry.read.is_some(),
2416                write: entry.write.is_some(),
2417            })
2418            .collect()
2419    }
2420
2421    /// Call the handler registered for `fd`, reporting whether one ran.
2422    ///
2423    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2424    /// poll iteration and then restarts the loop, because the handler may have changed the
2425    /// registration list underneath it; doing the same here keeps a handler that
2426    /// unregisters itself from being called with stale state.
2427    ///
2428    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2429    /// every later one, exactly as with timers.
2430    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2431        let Some(entry) = self.fd_handlers.get(&fd) else {
2432            return Ok(false);
2433        };
2434        let callback = if readable {
2435            entry.read.clone()
2436        } else if writable {
2437            entry.write.clone()
2438        } else {
2439            None
2440        };
2441        let Some(callback) = callback else {
2442            return Ok(false);
2443        };
2444        self.drain_jobs()?;
2445        match self.call_value(callback, Value::Undefined, Vec::new()) {
2446            Ok(_) => {}
2447            Err(Signal::Throw(value)) => {
2448                let text = self.describe_exception(&value);
2449                self.timer_errors.push(text);
2450            }
2451            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2452        }
2453        self.drain_jobs()?;
2454        Ok(true)
2455    }
2456
2457    /// Take the errors timer callbacks threw, leaving the list empty.
2458    pub fn take_timer_errors(&mut self) -> Vec<String> {
2459        std::mem::take(&mut self.timer_errors)
2460    }
2461
2462    /// Whether anything is still pending: a microtask or a timer.
2463    pub fn has_pending_work(&self) -> bool {
2464        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2465    }
2466
2467    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2468    pub fn has_pending_timers_or_jobs(&self) -> bool {
2469        !self.jobs.is_empty() || !self.tasks.is_empty()
2470    }
2471
2472    /// Run every queued microtask, including ones queued while draining.
2473    pub fn drain_jobs(&mut self) -> JsResult<()> {
2474        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2475        // would spin forever, so the drain is bounded the way the call stack is.
2476        let mut budget = 1_000_000usize;
2477        while let Some(job) = self.jobs.pop_front() {
2478            if budget == 0 {
2479                return Err(Signal::Throw(
2480                    self.make_error("InternalError", "promise job queue did not drain"),
2481                ));
2482            }
2483            budget -= 1;
2484            self.run_job(job)?;
2485            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2486            // engine may run script that the script itself did not ask for. Doing it here
2487            // rather than from a drop hook is what keeps the callback out of arbitrary
2488            // engine bookkeeping — see `builtins::weak`'s header.
2489            crate::builtins::weak::drain_finalizers(self)?;
2490        }
2491        // A script that queued no jobs may still have dropped targets, so the checkpoint
2492        // runs once more after the queue empties.
2493        crate::builtins::weak::drain_finalizers(self)?;
2494        Ok(())
2495    }
2496
2497    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2498    ///
2499    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2500    /// `None` and is swept out here. This is also where the realm learns that a registry
2501    /// died, which is why it is a mutation rather than a read.
2502    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2503        let handles = std::mem::take(&mut self.realm.finalization_registries);
2504        let mut live = Vec::with_capacity(handles.len());
2505        for handle in handles {
2506            let Some(object) = handle.upgrade() else {
2507                continue;
2508            };
2509            let Some(state) = object.finalization_state() else {
2510                continue;
2511            };
2512            live.push((object.clone(), *state));
2513            self.realm.finalization_registries.push(object.downgrade());
2514        }
2515        live
2516    }
2517
2518    /// Run one microtask.
2519    fn run_job(&mut self, job: Job) -> JsResult<()> {
2520        match job {
2521            Job::Reaction {
2522                handler: None,
2523                argument,
2524                rejected,
2525                promise,
2526            } => {
2527                // No handler: the settlement passes straight through to the derived
2528                // promise, which is why `p.catch(f)` ignores fulfilments.
2529                if rejected {
2530                    self.reject_promise(&promise, argument);
2531                } else {
2532                    self.fulfill_promise(&promise, argument);
2533                }
2534                Ok(())
2535            }
2536            Job::Reaction {
2537                handler: Some(handler),
2538                argument,
2539                promise,
2540                ..
2541            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2542                Ok(answer) => {
2543                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2544                        self.reject_promise(&promise, error);
2545                    }
2546                    Ok(())
2547                }
2548                Err(Signal::Throw(reason)) => {
2549                    self.reject_promise(&promise, reason);
2550                    Ok(())
2551                }
2552                Err(other) => Err(other),
2553            },
2554            Job::Thenable {
2555                then,
2556                value,
2557                promise,
2558            } => {
2559                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2560                // the value it produces settles `promise`.
2561                // The thenable's `then` gets this promise's own pair, so whatever it
2562                // produces settles `promise`.
2563                // `length: 1`, `name: ""` — a resolve/reject function is a
2564                // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2565                // with `JsObject::function` left `length` at 0, which a test reads straight
2566                // off the function (`finally/resolved-observable-then-calls-argument`
2567                // requires `resolve.length === 1` for the pair handed to a thenable).
2568                let resolve =
2569                    self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2570                let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2571                // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2572                // so the one-shot record starts over. Without the reset the pair above was
2573                // already spent by the `resolve` that queued this job, and a thenable that
2574                // calls `reject` left the promise pending forever
2575                // (`Promise/all/reject-immed`).
2576                self.forget_resolution(&promise);
2577                let reject = Value::Object(reject);
2578                match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2579                    Ok(_) => Ok(()),
2580                    // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2581                    // reject function, whose one-shot record makes this a no-op once `then`
2582                    // has already resolved the promise
2583                    // (`exception-after-resolve-in-thenable-job`).
2584                    Err(Signal::Throw(reason)) => {
2585                        self.call_value(reject, Value::Undefined, vec![reason])?;
2586                        Ok(())
2587                    }
2588                    Err(other) => Err(other),
2589                }
2590            }
2591            Job::Resume {
2592                coroutine,
2593                promise,
2594                kind,
2595                value,
2596            } => self.drive_async(&coroutine, &promise, kind, value),
2597            Job::GeneratorResume {
2598                generator,
2599                promise,
2600                kind,
2601                value,
2602            } => self.step_async_generator(&generator, &promise, kind, value),
2603            Job::Import {
2604                specifier,
2605                referrer,
2606                promise,
2607            } => {
2608                self.run_dynamic_import(&specifier, &referrer, &promise);
2609                Ok(())
2610            }
2611        }
2612    }
2613
2614    /// One element of a `Promise` combinator settled.
2615    ///
2616    /// The shared state object holds the result array, the number still outstanding, and
2617    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2618    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2619    /// to settle, only whatever `Sub` said a capability is.
2620    ///
2621    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2622    /// and `any` must ignore every later settlement, and `all` must not report a second
2623    /// rejection after the first.
2624    fn settle_combinator(
2625        &mut self,
2626        state: &Gc<JsObject>,
2627        index: usize,
2628        fulfilled: bool,
2629        value: Value,
2630    ) -> JsResult<()> {
2631        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2632        // Each element settles at most once: a thenable may call `onFulfilled` twice
2633        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2634        // call a no-op. Without it the second call decremented `remaining` again and settled
2635        // `all` with a short values array (`call-resolve-element-items`).
2636        let done = field("done");
2637        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2638        let settled = field("settled").is_some_and(|value| value.to_boolean());
2639        if settled {
2640            return Ok(());
2641        }
2642        if let Some(Value::Object(done)) = &done {
2643            if done
2644                .array_get(index)
2645                .is_some_and(|value| value.to_boolean())
2646            {
2647                return Ok(());
2648            }
2649            done.array_set(self.heap, index, Value::Bool(true));
2650        }
2651        let resolve = field("resolve");
2652        let reject = field("reject");
2653        let keys = field("keys");
2654        let results = field("results").and_then(|value| value.as_object().cloned());
2655        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2656        // promise: the handler is a plain function the constructor chose.
2657        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2658            if let Some(handler) = handler {
2659                interp.call_value(handler, Value::Undefined, vec![value])?;
2660            }
2661            Ok(())
2662        };
2663        match kind {
2664            // `race`: the first settlement wins and stops the rest.
2665            3 => {
2666                state.define_data("settled", Value::Bool(true));
2667                let handler = if fulfilled { resolve } else { reject };
2668                settle_with(self, handler, value)?;
2669                return Ok(());
2670            }
2671            // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2672            // the first rejection wins outright.
2673            0 | 4 if !fulfilled => {
2674                state.define_data("settled", Value::Bool(true));
2675                settle_with(self, reject, value)?;
2676                return Ok(());
2677            }
2678            // `any`: the first fulfilment wins.
2679            2 if fulfilled => {
2680                state.define_data("settled", Value::Bool(true));
2681                settle_with(self, resolve, value)?;
2682                return Ok(());
2683            }
2684            _ => {}
2685        }
2686        let Some(results) = &results else {
2687            return Ok(());
2688        };
2689        match kind {
2690            4 => {
2691                results.array_set(self.heap, index, value);
2692            }
2693            0 => {
2694                results.array_set(self.heap, index, value);
2695            }
2696            // `allSettled` (and its keyed twin) never rejects; each slot records what
2697            // happened.
2698            1 | 5 => {
2699                let record = self.new_object(Some(self.realm.object_proto.clone()));
2700                if fulfilled {
2701                    record.define_data("status", self.string("fulfilled"));
2702                    record.define_data("value", value);
2703                } else {
2704                    record.define_data("status", self.string("rejected"));
2705                    record.define_data("reason", value);
2706                }
2707                results.array_set(self.heap, index, Value::Object(record));
2708            }
2709            // `any`: a rejection is parked in the errors array and the sweep continues.
2710            2 => {
2711                results.array_set(self.heap, index, value);
2712            }
2713            _ => {}
2714        }
2715        let remaining = field("remaining")
2716            .map(|value| value.to_int32())
2717            .unwrap_or(0);
2718        let left = remaining - 1;
2719        state.define_data("remaining", Value::Int(left));
2720        if left != 0 {
2721            return Ok(());
2722        }
2723        state.define_data("settled", Value::Bool(true));
2724        match kind {
2725            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2726            // The keyed result: an ordinary object with a **null** prototype, holding the
2727            // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2728            4 | 5 => {
2729                let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2730                settle_with(self, resolve, keyed)?;
2731            }
2732            2 => {
2733                // The rejection is an `AggregateError` whose `errors` is the results array
2734                // itself — the slots are the reasons, in input order.
2735                let errors = results.array_elements().unwrap_or_default();
2736                let error = self.aggregate_error(errors, "all promises were rejected");
2737                settle_with(self, reject, error)?;
2738            }
2739            _ => {}
2740        }
2741        Ok(())
2742    }
2743
2744    /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2745    ///
2746    /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2747    /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2748    /// prototype is load-bearing in both directions: a key called `toString` must not
2749    /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2750    /// (`resolves-empty-object.js`).
2751    pub(crate) fn keyed_result_object(
2752        &mut self,
2753        keys: Option<&Value>,
2754        values: &Gc<JsObject>,
2755    ) -> JsResult<Value> {
2756        let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2757            return Ok(Value::Object(self.new_object(None)));
2758        };
2759        let result = self.new_object(None);
2760        let count = values.array_length().unwrap_or(0);
2761        for index in 0..count {
2762            let Some(key) = keys.array_get(index) else {
2763                continue;
2764            };
2765            let Some(value) = values.array_get(index) else {
2766                continue;
2767            };
2768            let property = Property::with_attributes(value, true, true);
2769            match &key {
2770                Value::Symbol(symbol) => {
2771                    result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2772                }
2773                other => {
2774                    let text = self.to_js_string(other)?;
2775                    result.define_key(&PropertyKey::from(text.as_str()), property);
2776                }
2777            }
2778        }
2779        Ok(Value::Object(result))
2780    }
2781
2782    /// Build an async function's result: a promise whose body runs as a coroutine.
2783    pub fn new_async_function(
2784        &mut self,
2785        function: Value,
2786        this: Value,
2787        args: Vec<Value>,
2788    ) -> JsResult<Value> {
2789        let promise = self.new_promise();
2790        let coroutine = self.new_coroutine(function, this, args)?;
2791        if let Err(Signal::Throw(reason)) =
2792            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2793        {
2794            self.reject_promise(&promise, reason);
2795        }
2796        Ok(Value::Object(promise))
2797    }
2798
2799    /// The coroutine an async body runs in.
2800    ///
2801    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2802    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2803    /// than growing a second state machine. The difference is only in the ending — a
2804    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2805    /// Run `code` as an async function body, answering the promise it settles.
2806    ///
2807    /// Used for a module with top-level `await`: its body is an async function whose
2808    /// caller is the host, so there is no function object to pass through
2809    /// [`Interp::new_async_function`].
2810    pub fn run_async_body(
2811        &mut self,
2812        code: Gc<CompiledCode>,
2813        env: Gc<ClosureEnv>,
2814        this: Value,
2815    ) -> JsResult<Value> {
2816        let promise = self.new_promise();
2817        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2818        if let Err(Signal::Throw(reason)) =
2819            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2820        {
2821            self.reject_promise(&promise, reason);
2822        }
2823        Ok(Value::Object(promise))
2824    }
2825
2826    fn new_coroutine(
2827        &mut self,
2828        function: Value,
2829        this: Value,
2830        args: Vec<Value>,
2831    ) -> JsResult<Gc<JsObject>> {
2832        let Some(object) = function.as_object().cloned() else {
2833            return Err(self.type_error("not a function"));
2834        };
2835        let Some((code, env)) = bytecode_of(&object) else {
2836            return Err(self.type_error("not a function"));
2837        };
2838        self.new_coroutine_from(code, env, this, args)
2839    }
2840
2841    /// Build a coroutine over an already-resolved body.
2842    fn new_coroutine_from(
2843        &mut self,
2844        code: Gc<CompiledCode>,
2845        env: Gc<ClosureEnv>,
2846        this: Value,
2847        args: Vec<Value>,
2848    ) -> JsResult<Gc<JsObject>> {
2849        let function = Value::Undefined;
2850        self.push_frame(code, env, this, args, function)?;
2851        let frame = self.frames.pop().expect("push_frame just pushed it");
2852        let state = GeneratorState {
2853            frame: Some(frame),
2854            phase: GeneratorPhase::SuspendedStart,
2855            parked_on_await: false,
2856            parked_on_yield_star: false,
2857            requests: std::collections::VecDeque::new(),
2858            async_busy: false,
2859            // An `async function` body is driven by `drive_async`, never by the generator
2860            // protocol, and the object is not reachable from script.
2861            is_async: false,
2862        };
2863        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2864        coroutine.with_mut(|data| {
2865            data.kind = ObjectKind::Generator(Box::new(state));
2866        });
2867        Ok(coroutine)
2868    }
2869
2870    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2871    /// `await` and `value` is what it awaited.
2872    fn resume_coroutine(
2873        &mut self,
2874        coroutine: &Gc<JsObject>,
2875        kind: ResumeKind,
2876        value: Value,
2877    ) -> JsResult<(Value, bool)> {
2878        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2879            ObjectKind::Generator(state) => {
2880                let is_async = state.is_async;
2881                Some(std::mem::replace(
2882                    state.as_mut(),
2883                    GeneratorState {
2884                        frame: None,
2885                        phase: GeneratorPhase::Executing,
2886                        parked_on_await: false,
2887                        parked_on_yield_star: false,
2888                        requests: std::collections::VecDeque::new(),
2889                        async_busy: false,
2890                        is_async,
2891                    },
2892                ))
2893            }
2894            _ => None,
2895        }) else {
2896            return Err(self.type_error("not a coroutine"));
2897        };
2898        let result = self.step_generator(&mut state, kind, value);
2899        coroutine.with_mut(|data| {
2900            data.kind = ObjectKind::Generator(Box::new(state));
2901        });
2902        let (value, done, _ready, _reason) = result?;
2903        Ok((value, done))
2904    }
2905
2906    /// Advance an async body and settle its promise with the outcome.
2907    fn drive_async(
2908        &mut self,
2909        coroutine: &Gc<JsObject>,
2910        promise: &Gc<JsObject>,
2911        kind: ResumeKind,
2912        value: Value,
2913    ) -> JsResult<()> {
2914        match self.resume_coroutine(coroutine, kind, value) {
2915            Ok((value, true)) => {
2916                // `Ok` with `done` means the body finished *normally*, even when it was
2917                // resumed by a `throw` — `try { await p } catch {}` completes by
2918                // returning. Only the `Err` arm below is a rejection.
2919                //
2920                // Resolving rather than fulfilling matters: `return promise` in an async
2921                // body adopts the inner promise, so `async function f(){ return
2922                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2923                // promise.
2924                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2925                    self.reject_promise(promise, reason);
2926                }
2927                Ok(())
2928            }
2929            Ok((value, false)) => {
2930                // Parked on `await`: follow what it awaited and resume with the outcome.
2931                let awaited = match self.promise_resolve_value(value) {
2932                    Ok(awaited) => awaited,
2933                    Err(Signal::Throw(error)) => {
2934                        self.reject_promise(promise, error);
2935                        return Ok(());
2936                    }
2937                    Err(other) => return Err(other),
2938                };
2939                self.hook_await(awaited, coroutine, promise)
2940            }
2941            Err(Signal::Throw(reason)) => {
2942                self.reject_promise(promise, reason);
2943                Ok(())
2944            }
2945            Err(other) => Err(other),
2946        }
2947    }
2948
2949    /// Arrange for `coroutine` to resume when `awaited` settles.
2950    fn hook_await(
2951        &mut self,
2952        awaited: Value,
2953        coroutine: &Gc<JsObject>,
2954        promise: &Gc<JsObject>,
2955    ) -> JsResult<()> {
2956        let resumed = JsObject::function(
2957            self.heap,
2958            Some(self.realm.function_proto.clone()),
2959            Callable::AwaitResume {
2960                coroutine: coroutine.clone(),
2961                promise: promise.clone(),
2962                kind: ResumeKind::Next,
2963            },
2964        );
2965        let raised = JsObject::function(
2966            self.heap,
2967            Some(self.realm.function_proto.clone()),
2968            Callable::AwaitResume {
2969                coroutine: coroutine.clone(),
2970                promise: promise.clone(),
2971                kind: ResumeKind::Throw,
2972            },
2973        );
2974        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2975        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2976        let Value::Object(awaited) = &awaited else {
2977            self.jobs.push_back(Job::Resume {
2978                coroutine: coroutine.clone(),
2979                promise: promise.clone(),
2980                kind: ResumeKind::Next,
2981                value: awaited,
2982            });
2983            return Ok(());
2984        };
2985        self.perform_then(
2986            awaited,
2987            Some(Value::Object(resumed)),
2988            Some(Value::Object(raised)),
2989        )?;
2990        Ok(())
2991    }
2992
2993    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2994    /// things an engine keeps outside it — array elements and an array's `length`.
2995    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2996        if let Some(property) = object.own_property_key(key) {
2997            return Some(property);
2998        }
2999        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3000        // be synthesized too — and every one of them is a plain writable, enumerable,
3001        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3002        // `undefined` before this, which made `key-is-numericindex` fail on its own
3003        // side effect check.
3004        //
3005        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3006        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3007        // likewise not elements however numeric they look.
3008        if object.typed_array_element_type().is_some()
3009            && let Some(numeric) = canonical_numeric_index(key)
3010            && numeric.is_finite()
3011            && numeric.fract() == 0.0
3012            && !(numeric == 0.0 && numeric.is_sign_negative())
3013            && numeric >= 0.0
3014            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3015        {
3016            let value = object.typed_array_element(numeric as usize)?;
3017            return Some(Property::data(value));
3018        }
3019        // An array's elements live in their own vector rather than the property table, so
3020        // a descriptor for one has to be synthesized — with the attributes an element has.
3021        if let Some(index) = key.as_str().and_then(array_index)
3022            && let Some(value) = object.array_get(index as usize)
3023            && !matches!(value, Value::Hole)
3024        {
3025            return Some(Property::data(value));
3026        }
3027        // `length` is an own property of an array that is not in its property table
3028        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3029        // and non-enumerable.
3030        if key.as_str() == Some("length")
3031            && let Some(length) = object.array_length()
3032        {
3033            return Some(Property {
3034                value: Some(crate::object::length_value(length)),
3035                writable: object.length_writable(),
3036                enumerable: false,
3037                configurable: false,
3038                getter: None,
3039                setter: None,
3040                descriptor_fields: None,
3041            });
3042        }
3043        None
3044    }
3045
3046    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3047    pub fn object_get_own_property(
3048        &mut self,
3049        object: &Gc<JsObject>,
3050        key: &PropertyKey,
3051    ) -> JsResult<Option<Property>> {
3052        if let Some(answer) = self.proxy_get_own_property(object, key)? {
3053            return Ok(answer);
3054        }
3055        if let Some(exotic) = object.exotic()
3056            && let Some(answer) = exotic.get_own_property(self, object, key)?
3057        {
3058            return Ok(answer);
3059        }
3060        // A module namespace's bindings are accessors internally and data properties to
3061        // script; see `namespace_own_property`.
3062        if object.module_namespace_marker() {
3063            return self.namespace_own_property(object, key);
3064        }
3065        // A mapped `arguments` index is a data property as far as script can see: the
3066        // accessor pair that aliases the parameter is plumbing, and exposing it would
3067        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3068        // report a `get` where the spec has a `[[Value]]`.
3069        if let Some(index) = key.as_str().and_then(crate::object::array_index)
3070            && let Some(cell) = object.mapped_argument_cell(index as usize)
3071        {
3072            // Non-configurable is *not* the default: an ordinary mapped index is
3073            // configurable, and only becomes non-configurable once something
3074            // redefines it. Preserve whatever the property table currently says.
3075            // The attributes come from whatever the property table holds, because they
3076            // can be changed independently of the mapping; only the *value* and the
3077            // data-property *kind* are the accessor's secret.
3078            let flags = Self::ordinary_own_property(object, key);
3079            if let Some(existing) = &flags
3080                && !existing.is_accessor()
3081            {
3082                // Already demapped: the table entry is the answer, not the cell.
3083                return Ok(flags);
3084            }
3085            return Ok(Some(Property {
3086                value: Some(cell.get()),
3087                writable: true,
3088                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3089                configurable: flags.as_ref().is_some_and(|p| p.configurable),
3090                ..Property::default()
3091            }));
3092        }
3093        Ok(Self::ordinary_own_property(object, key))
3094    }
3095
3096    /// Whether `object` is a module namespace exotic object (§10.4.6).
3097    ///
3098    /// Recognised by shape rather than by a flag: a namespace is the only object whose
3099    /// properties are all accessors over a `ModuleBinding` cell. That is the same
3100    /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3101    /// distinction in one place instead of adding a boolean every constructor has to
3102    /// remember to set.
3103    pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3104        object.module_namespace_marker()
3105    }
3106
3107    /// `[[GetOwnProperty]]` for a module namespace exotic object.
3108    ///
3109    /// The bindings are stored as getters — that is the only way a live binding can be read
3110    /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3111    /// descriptor:
3112    ///
3113    /// ```text
3114    /// { [[Value]]: current value, [[Writable]]: true,
3115    ///   [[Enumerable]]: true, [[Configurable]]: false }
3116    /// ```
3117    ///
3118    /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3119    /// `undefined`. Reporting the accessor instead — which is what the property table holds
3120    /// — made every one of test262's namespace descriptor assertions fail, in both the
3121    /// `await-ns-*` and `promise-then-ns-*` families.
3122    ///
3123    /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3124    /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3125    /// property`); the ordinary descriptor machinery derives that from these attributes.
3126    pub fn namespace_own_property(
3127        &mut self,
3128        object: &Gc<JsObject>,
3129        key: &PropertyKey,
3130    ) -> JsResult<Option<Property>> {
3131        let Some(stored) = Self::ordinary_own_property(object, key) else {
3132            return Ok(None);
3133        };
3134        let Some(Property {
3135            getter: Some(getter),
3136            ..
3137        }) = Some(&stored)
3138        else {
3139            return Ok(Some(stored));
3140        };
3141        // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3142        // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3143        // rather than stored.
3144        let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3145        Ok(Some(Property {
3146            value: Some(value),
3147            writable: true,
3148            enumerable: true,
3149            configurable: false,
3150            ..Property::default()
3151        }))
3152    }
3153
3154    /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3155    ///
3156    /// Modelled as "does this descriptor describe the property that is already there?",
3157    /// because a namespace property's attributes are fixed and its value cannot be changed
3158    /// through the namespace. The three ways to succeed:
3159    ///
3160    /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3161    /// * one whose `[[Value]]` is `SameValue` the current binding value;
3162    /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3163    ///   configurable: false}`.
3164    ///
3165    /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3166    /// false), so it goes through the same check against its stored value — which is what
3167    /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3168    /// answer `true` while `{value: "Other"}` answers `false`.
3169    fn namespace_define_own_property(
3170        &mut self,
3171        object: &Gc<JsObject>,
3172        key: &PropertyKey,
3173        property: &Property,
3174    ) -> JsResult<bool> {
3175        let Some(current) = self.namespace_own_property(object, key)? else {
3176            // A name the namespace does not export cannot be added to it.
3177            return Ok(false);
3178        };
3179        if let Some(value) = &property.value {
3180            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3181            if !self.same_value(value, current_value)? {
3182                return Ok(false);
3183            }
3184        }
3185        Ok(true)
3186    }
3187
3188    /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3189    ///
3190    /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3191    /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3192    /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3193    /// descriptor with no fields at all therefore succeeds, which is what
3194    /// `Reflect.defineProperty(ns, k, {})` checks.
3195    ///
3196    /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3197    /// stored property, and a namespace stores its bindings as accessors, so every
3198    /// definition looked like "accessor → data kind changed" or carried `writable: false`
3199    /// from the accessor's own entry. Presence is only available here, before the merge.
3200    pub fn namespace_define_from_descriptor(
3201        &mut self,
3202        object: &Gc<JsObject>,
3203        key: &PropertyKey,
3204        descriptor: &Gc<JsObject>,
3205    ) -> JsResult<bool> {
3206        let Some(current) = self.namespace_own_property(object, key)? else {
3207            return Ok(false);
3208        };
3209        // An accessor descriptor can never describe a namespace binding.
3210        if self.get_property(descriptor, "get")?.is_some()
3211            || self.get_property(descriptor, "set")?.is_some()
3212        {
3213            return Ok(false);
3214        }
3215        if let Some(value) = self.get_property(descriptor, "value")? {
3216            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3217            if !self.same_value(&value, current_value)? {
3218                return Ok(false);
3219            }
3220        }
3221        // The three attribute fields, when named, must restate what the property already
3222        // has. Not a fixed shape: an exported binding reports
3223        // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3224        // is a real own data property with `{false, false, false}`, and both are namespace
3225        // properties. Comparing against `current` is what makes one rule cover both.
3226        for (name, have) in [
3227            ("writable", current.writable),
3228            ("enumerable", current.enumerable),
3229            ("configurable", current.configurable),
3230        ] {
3231            if let Some(named) = self.get_property(descriptor, name)?
3232                && named.to_boolean() != have
3233            {
3234                return Ok(false);
3235            }
3236        }
3237        Ok(true)
3238    }
3239
3240    /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3241    /// compare a requested value against a live binding.
3242    pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3243        Ok(a.same_value(b))
3244    }
3245
3246    ///
3247    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3248    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3249    /// abstract operation here rather than a private helper in `error.rs`.
3250    ///
3251    /// The name is the whole point: the setter must behave as if the prototype were not
3252    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3253    /// the accessor for every error object in the realm. Everything below follows from that:
3254    ///
3255    /// 1. `thisValue` must be an object — otherwise `TypeError`.
3256    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3257    ///    accessor's own home an error rather than a self-shadow.
3258    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3259    ///    either has a string or has made a mistake.
3260    /// 4. An existing *own* property decides the path — an own setter is called, an own
3261    ///    non-writable data property is a `TypeError` — and only a missing own property
3262    ///    falls through to defining one.
3263    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3264    ///    traps and a non-extensible receiver is a `TypeError`.
3265    ///
3266    /// The installed shape is writable + configurable, not enumerable.
3267    pub fn setter_that_ignores_prototype_properties(
3268        &mut self,
3269        this_value: Value,
3270        home: &Gc<JsObject>,
3271        property_key: &str,
3272        args: &[Value],
3273    ) -> JsResult<Value> {
3274        self.setter_that_ignores_prototype_properties_key(
3275            this_value,
3276            home,
3277            &PropertyKey::from(property_key),
3278            args,
3279        )
3280    }
3281
3282    /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3283    ///
3284    /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3285    pub fn setter_that_ignores_prototype_properties_key(
3286        &mut self,
3287        this_value: Value,
3288        home: &Gc<JsObject>,
3289        key: &PropertyKey,
3290        args: &[Value],
3291    ) -> JsResult<Value> {
3292        let Some(receiver) = this_value.as_object().cloned() else {
3293            return Err(self.type_error("setter called on a non-object"));
3294        };
3295        if Gc::ptr_eq(&receiver, home) {
3296            return Err(self.type_error("cannot assign to the accessor's own home object"));
3297        }
3298        // No type check here: §7.3.40 takes an arbitrary `v`, and
3299        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3300        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3301        // before calling this.
3302        let value = args.first().cloned().unwrap_or(Value::Undefined);
3303        // Step 4: an own property on the receiver changes what happens, and there are three
3304        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3305        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3306        // `Set` with `throw = true`, and a test exists for each.
3307        if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3308            if existing.is_accessor() && existing.setter.is_none() {
3309                // A getter-only own accessor cannot be written through.
3310                return Err(self.type_error("no setter for the own property"));
3311            }
3312            // Everything else — an own data property, or an own accessor *with* a setter —
3313            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3314            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3315            // an own user setter receives the value (`setter-own-accessor`), because
3316            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3317            // setter directly is the difference between one code path and two that can
3318            // disagree.
3319            self.set_property_with_key(
3320                &receiver,
3321                key,
3322                value.clone(),
3323                crate::interp::DeleteFailure::Throw,
3324            )?;
3325            return Ok(Value::Undefined);
3326        }
3327        let property = Property {
3328            value: Some(value.clone()),
3329            writable: true,
3330            // Enumerable, despite the accessor it shadows not being. The reference installs
3331            // it that way and six cases check it (`setter-creates-own-property` and friends).
3332            enumerable: true,
3333            configurable: true,
3334            ..Property::default()
3335        };
3336        if !self.object_define_own_property(&receiver, key, property)? {
3337            return Err(self.type_error("the receiver refused the definition"));
3338        }
3339        Ok(Value::Undefined)
3340    }
3341
3342    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3343    ///
3344    /// The indices of a typed array are not properties at all — they are bytes in the
3345    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3346    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3347    /// enumerable and configurable, so a definition can only ever change the *value*, and
3348    /// every other descriptor is refused rather than applied.
3349    ///
3350    /// The order of the checks is the spec's, and two of them are load-bearing:
3351    ///
3352    /// * the index is validated **before** the value is converted, because the conversion
3353    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3354    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3355    ///   happens when the index was valid on the way in;
3356    /// * the store is attempted even when the index has gone out of bounds by the time the
3357    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3358    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3359    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3360    ///
3361    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3362    /// the existing element, which is harmless here: every valid index is already
3363    /// writable, enumerable and configurable, so a `false` in the merged property can only
3364    /// have come from the descriptor having named `false`.
3365    fn integer_indexed_define_own_property(
3366        &mut self,
3367        object: &Gc<JsObject>,
3368        numeric: f64,
3369        property: &Property,
3370    ) -> JsResult<bool> {
3371        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3372        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3373        if !typed_array_index_is_valid(object, numeric) {
3374            return Ok(false);
3375        }
3376        // Step 6: the indices are data properties, so an accessor descriptor is refused
3377        // rather than converted. `Object.defineProperty` turns the `false` into a
3378        // `TypeError`; `Reflect.defineProperty` reports it.
3379        if property.is_accessor() {
3380            return Ok(false);
3381        }
3382        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3383        // definition that asks for anything else cannot be honoured.
3384        if !property.writable || !property.enumerable || !property.configurable {
3385            return Ok(false);
3386        }
3387        // Step 10: only a descriptor that names a value stores anything.
3388        let Some(value) = property.value.clone() else {
3389            return Ok(true);
3390        };
3391        let Some(element) = object.typed_array_element_type() else {
3392            return Ok(false);
3393        };
3394        let stored = self.element_value(element, value)?;
3395        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3396            return Err(self.type_error(reason));
3397        }
3398        Ok(true)
3399    }
3400
3401    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3402    pub fn object_define_own_property(
3403        &mut self,
3404        object: &Gc<JsObject>,
3405        key: &PropertyKey,
3406        property: Property,
3407    ) -> JsResult<bool> {
3408        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3409            return Ok(accepted);
3410        }
3411        // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3412        //
3413        // The only definitions that can succeed are ones describing the property the
3414        // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3415        // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3416        // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3417        // `writable: false`, `configurable: true`, or any name the namespace does not
3418        // export is `false`.
3419        //
3420        // The ordinary path gets the no-change case right by accident — it compares against
3421        // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3422        // is an accessor internally while the definition script writes is a data descriptor.
3423        // Answering here is what makes that attribute-only definition a no-op rather than a
3424        // refusal (`namespace/await-ns-define-own-property`).
3425        if object.module_namespace_marker() {
3426            return self.namespace_define_own_property(object, key, &property);
3427        }
3428        // A proxy always answers above — with `Some` from its trap, or with `None` when
3429        // the trap is absent, and then the definition belongs to the **target**
3430        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3431        // when there is no trap). Falling through to the ordinary path here defined the
3432        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3433        // property the target never saw.
3434        if object.proxy_state().is_some() {
3435            let Some((target, _handler)) = self.proxy_parts(object)? else {
3436                return Err(self.type_error("cannot use a proxy that has been revoked"));
3437            };
3438            return self.object_define_own_property(&target, key, property);
3439        }
3440        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3441        // they accept exactly one descriptor shape. This has to happen before the
3442        // ordinary path, which would happily store a data property next to the buffer —
3443        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3444        // and `TypedArray/prototype/set` are about this section.
3445        if object.typed_array_element_type().is_some()
3446            && let Some(index) = canonical_numeric_index(key)
3447        {
3448            return self.integer_indexed_define_own_property(object, index, &property);
3449        }
3450        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3451        // non-extensible object. The check lives here rather than in the callers because
3452        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3453        // `Array.prototype.filter` uses to store its result, and a species object made
3454        // non-extensible by its own constructor must make that a `TypeError`
3455        // (`target-array-non-extensible`).
3456        // Note the `is_none()`: an already-present property may still be **redefined** on a
3457        // non-extensible object, and only *adding* one is refused (as Distinct from
3458        // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3459        // properties — testing extensibility before looking for the property made every
3460        // `Object.freeze` of an ordinary object refuse its own second step).
3461        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3462            return Ok(false);
3463        }
3464        // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3465        // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3466        // an omitted field is left alone). Merging here rather than at each call site is
3467        // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3468        // the value and `enumerable` in place.
3469        //
3470        // The merge is a no-op when the property is absent: there is nothing to keep.
3471        let was_partial = property.descriptor_fields.is_some();
3472        let property = match property.descriptor_fields {
3473            None => property,
3474            Some(fields) => {
3475                let base = self.object_get_own_property(object, key)?;
3476                let mut merged = base.clone().unwrap_or_default();
3477                // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3478                // descriptor names, and switching kind discards the other half —
3479                // `{set: f}` on a data property is an accessor with no getter, not a data
3480                // property whose `get` happens to be absent.
3481                let wants_accessor = fields.get || fields.set;
3482                let wants_data = fields.value || fields.writable;
3483                if wants_accessor {
3484                    merged.value = None;
3485                    merged.writable = false;
3486                    merged.getter = property.getter.clone();
3487                    merged.setter = property.setter.clone();
3488                } else if wants_data {
3489                    merged.getter = None;
3490                    merged.setter = None;
3491                    if fields.value {
3492                        merged.value = property.value.clone();
3493                    }
3494                    if fields.writable {
3495                        merged.writable = property.writable;
3496                    }
3497                }
3498                if fields.enumerable {
3499                    merged.enumerable = property.enumerable;
3500                }
3501                if fields.configurable {
3502                    merged.configurable = property.configurable;
3503                }
3504                merged.descriptor_fields = None;
3505                merged
3506            }
3507        };
3508        // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3509        // descriptor. `define_property_on` runs the same check before it calls here, so an
3510        // ordinary object is already covered; what is *not* is the forwarding a proxy does
3511        // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3512        // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3513        // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3514        // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3515        // own define would have refused.
3516        //
3517        // Only partial descriptors are validated here. A whole `Property` passed by an
3518        // internal caller (`Property::data(…)`) carries attributes that say nothing about
3519        // what the descriptor "named", and those callers rely on the write landing.
3520        if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3521            // Every branch below is gated on `!existing.configurable`: a *configurable*
3522            // property may be reshaped however the descriptor likes, which is why an
3523            // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3524            // must succeed. Testing only `writable` refused that and broke
3525            // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3526            let same_kind = existing.is_accessor() == property.is_accessor();
3527            if !same_kind {
3528                // Step 4: a non-configurable property may not change kind.
3529                if !existing.configurable {
3530                    return Ok(false);
3531                }
3532            } else if existing.is_accessor() {
3533                // Step 6: an accessor's halves are its value.
3534                if !existing.configurable
3535                    && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3536                        || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3537                {
3538                    return Ok(false);
3539                }
3540            } else if !existing.configurable && !existing.writable {
3541                // Step 7: a non-configurable *and* non-writable data property's value is
3542                // fixed, and it may not become writable again.
3543                if property.writable {
3544                    return Ok(false);
3545                }
3546                let current = existing.value.clone().unwrap_or(Value::Undefined);
3547                let requested = property.value.clone().unwrap_or(Value::Undefined);
3548                if !current.same_value(&requested) {
3549                    return Ok(false);
3550                }
3551            }
3552            // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3553            // is frozen with it.
3554            if !existing.configurable
3555                && (property.configurable || property.enumerable != existing.enumerable)
3556            {
3557                return Ok(false);
3558            }
3559        }
3560        // A host class that intercepts definitions owns the attributes of the properties it
3561        // defines: `_class`-style storage on the native side is the usual reason.
3562        if let Some(exotic) = object.exotic()
3563            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3564        {
3565            return Ok(accepted);
3566        }
3567        // An array index is stored in the element vector, which can hold a plain value and
3568        // nothing else. An accessor — or a data property with non-default attributes —
3569        // therefore has to live in the property table, and the element slot is blanked so
3570        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3571        // {get})` stored the accessor where no read ever looked, and the array kept
3572        // answering its old value.
3573        // An array's `length` is not stored in the property table, so defining it has to
3574        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3575        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3576        // {value: 1})` reported success and changed nothing.
3577        if key.as_str() == Some("length") && object.is_array() {
3578            // `{writable: false}` on `length` does not change the length, but it does make
3579            // it read-only — after which neither a later `{writable: true}` nor a store
3580            // past the end may succeed.
3581            if property.value.is_none() {
3582                if !object.length_writable() && property.writable {
3583                    return Ok(false);
3584                }
3585                object.set_length_writable(property.writable);
3586                return Ok(true);
3587            }
3588            if !object.length_writable() {
3589                return Ok(false);
3590            }
3591        }
3592        if key.as_str() == Some("length")
3593            && object.is_array()
3594            && let Some(value) = property.value.clone()
3595        {
3596            let requested = value.to_number();
3597            let valid = requested.is_finite()
3598                && requested >= 0.0
3599                && requested.fract() == 0.0
3600                && requested <= u32::MAX as f64;
3601            if !valid {
3602                return Err(self.range_error("invalid array length"));
3603            }
3604            // Truncating deletes the elements above the new length, and a non-configurable
3605            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3606            // makes `a.length = 2` fail rather than quietly drop it.
3607            let current = object.array_length().unwrap_or(0);
3608            let requested = requested as usize;
3609            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3610                // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3611                // `[[Writable]]: false` when the descriptor asked for it — the length is
3612                // left at its old value but locked. Returning `false` alone left it
3613                // writable, which `verifyProperty` catches
3614                // (`defineProperties/15.2.3.7-6-a-164`).
3615                if property
3616                    .descriptor_fields
3617                    .is_some_and(|fields| fields.writable)
3618                    && !property.writable
3619                    && object.length_writable()
3620                {
3621                    object.set_length_writable(false);
3622                }
3623                return Ok(false);
3624            }
3625            object.array_set_length(self.heap, requested);
3626            return Ok(true);
3627        }
3628        let plain = property.writable
3629            && property.enumerable
3630            && property.configurable
3631            && !property.is_accessor();
3632        if let Some(index) = key.as_str().and_then(array_index)
3633            && object.is_array()
3634        {
3635            // Growing the array needs a writable `length`: after
3636            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3637            // be added.
3638            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3639                return Ok(false);
3640            }
3641            if plain && property.value.is_some() {
3642                // An ordinary element: the vector is where a read looks first, so it has
3643                // to be the vector that changes — unless the index is too far out to be
3644                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3645                // one property, because past its own limit it stores the index as an
3646                // ordinary key. Falling through to `define_key` below is the same choice,
3647                // and the alternative was worse: the store used to be *dropped* and the
3648                // length left at 0, which is a silent wrong answer.
3649                let value = property.value.clone().unwrap_or(Value::Undefined);
3650                object.delete_key(key);
3651                if object.array_set(self.heap, index as usize, value) {
3652                    return Ok(true);
3653                }
3654                // Past the dense limit the element lives in the table like any property.
3655                object.note_element_descriptor();
3656                object.define_key(key, property);
3657                // A sparse store past the dense limit still extends `length`, which is what
3658                // `a[a.length] = v` relies on — but only extends: shortening would delete
3659                // the sparse properties above the index, including this one.
3660                if index as usize + 1 > object.array_length().unwrap_or(0) {
3661                    object.array_set_length(self.heap, index as usize + 1);
3662                }
3663                return Ok(true);
3664            }
3665            // A non-plain element — an accessor, or an attribute that is not the default —
3666            // lives in the table while the slot becomes a hole. Recording it keeps every
3667            // later `a[i] = v` off the dense path, where the write would have shadowed the
3668            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3669            // replace the accessor with a plain data property.
3670            object.note_element_descriptor();
3671            object.define_key(key, property);
3672            // The slot stays, so `length` does not shrink; a hole is not an element, so
3673            // the table entry is now what a read finds.
3674            object.array_set(self.heap, index as usize, Value::Hole);
3675            // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3676            // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3677            // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3678            // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3679            if index as usize + 1 > object.array_length().unwrap_or(0) {
3680                object.array_set_length(self.heap, index as usize + 1);
3681            }
3682            return Ok(true);
3683        }
3684        object.define_key(key, property);
3685        Ok(true)
3686    }
3687
3688    /// Build a proxy object over `target`, with its traps read from `handler`.
3689    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3690        JsObject::proxy(self.heap, target, handler)
3691    }
3692
3693    /// The `revoke` function for a proxy's slots.
3694    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3695        let revoke = JsObject::function(
3696            self.heap,
3697            Some(self.realm.function_proto.clone()),
3698            Callable::Revoker(slots),
3699        );
3700        // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3701        // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3702        // inherited from `Function.prototype` reads the same but fails the three cases that
3703        // check the own-property list (`revocation-function-{length,name,property-order}`).
3704        revoke.define("length", Property::name_or_length(Value::Int(0)));
3705        revoke.define("name", Property::name_or_length(self.string("")));
3706        revoke
3707    }
3708
3709    /// A new array.
3710    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3711        let array = JsObject::array(
3712            self.heap,
3713            Some(self.realm.array_proto.clone()),
3714            elements.len(),
3715        );
3716        for (index, element) in elements.into_iter().enumerate() {
3717            array.array_set(self.heap, index, element);
3718        }
3719        array
3720    }
3721
3722    /// A new native function object.
3723    ///
3724    /// The observable `name` and `length` are installed as properties here, which is
3725    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3726    /// so `f.name = "x"` behaves like the writable property it is.
3727    /// A native constructor that builds its own instance after validating its arguments.
3728    ///
3729    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3730    /// check runs before `new.target.prototype` is read.
3731    pub fn new_native_ctor(
3732        &self,
3733        name: impl Into<String>,
3734        length: u32,
3735        func: NativeFn,
3736    ) -> Gc<JsObject> {
3737        let function = JsObject::function(
3738            self.heap,
3739            Some(self.realm.function_proto.clone()),
3740            Callable::Native {
3741                func,
3742                own_instance: true,
3743            },
3744        );
3745        function.set_constructible(true);
3746        function.define(
3747            "length",
3748            Property::name_or_length(Value::Int(length as i32)),
3749        );
3750        function.define("name", Property::name_or_length(self.string(name)));
3751        function
3752    }
3753
3754    /// A native constructor that lets `new` build the instance first.
3755    ///
3756    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3757    /// validation that must precede reading `new.target.prototype`, so the object can be
3758    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3759    /// which makes a *method* and therefore not a constructor at all.
3760    pub fn new_native_constructor(
3761        &self,
3762        name: impl Into<String>,
3763        length: u32,
3764        func: NativeFn,
3765    ) -> Gc<JsObject> {
3766        let function = self.new_native(name, length, func);
3767        function.set_constructible(true);
3768        function
3769    }
3770
3771    /// A new host function object: a native closure that carries its own state.
3772    ///
3773    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3774    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3775    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3776    /// this safe: the closure must not capture a `Gc`.
3777    pub fn new_host_function(
3778        &self,
3779        name: impl Into<String>,
3780        length: u32,
3781        func: crate::object::HostFn,
3782    ) -> Gc<JsObject> {
3783        self.new_host_inner(name.into(), length, func, false)
3784    }
3785
3786    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3787    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3788    pub fn new_host_ctor(
3789        &self,
3790        name: impl Into<String>,
3791        length: u32,
3792        func: crate::object::HostFn,
3793    ) -> Gc<JsObject> {
3794        let function = self.new_host_inner(name.into(), length, func, true);
3795        function.set_constructible(true);
3796        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3797        // installs its own methods on it, so it starts as a plain object.
3798        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3799        function.define(
3800            "prototype",
3801            Property {
3802                value: Some(Value::Object(proto)),
3803                writable: true,
3804                enumerable: false,
3805                configurable: false,
3806                ..Property::default()
3807            },
3808        );
3809        function
3810    }
3811
3812    fn new_host_inner(
3813        &self,
3814        name: String,
3815        length: u32,
3816        func: crate::object::HostFn,
3817        own_instance: bool,
3818    ) -> Gc<JsObject> {
3819        let function = JsObject::function(
3820            self.heap,
3821            Some(self.realm.function_proto.clone()),
3822            Callable::Host {
3823                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3824                own_instance,
3825            },
3826        );
3827        function.define(
3828            "length",
3829            Property::name_or_length(Value::Int(length as i32)),
3830        );
3831        function.define("name", Property::name_or_length(self.string(name)));
3832        function
3833    }
3834
3835    /// A callable object with the `length`/`name` a built-in function has, in that order.
3836    ///
3837    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3838    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3839    /// [`JsObject::function`] defines neither, which is why every capability helper built
3840    /// with it reported no own `length` and no own `name` at all.
3841    ///
3842    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3843    /// configurable.
3844    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3845        let function =
3846            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3847        function.define(
3848            "length",
3849            Property::name_or_length(Value::Int(length as i32)),
3850        );
3851        function.define("name", Property::name_or_length(self.string(name)));
3852        function
3853    }
3854
3855    /// A new native function object.
3856    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3857        let function = JsObject::function(
3858            self.heap,
3859            Some(self.realm.function_proto.clone()),
3860            Callable::Native {
3861                func,
3862                own_instance: false,
3863            },
3864        );
3865        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3866        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3867        // `length,name` and this listed `name,length`. A bytecode function already gets it
3868        // the right way round; only native ones were built backwards.
3869        function.define(
3870            "length",
3871            Property::name_or_length(Value::Int(length as i32)),
3872        );
3873        function.define("name", Property::name_or_length(self.string(name)));
3874        function
3875    }
3876
3877    /// A new bound function.
3878    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3879        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3880        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3881        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3882        let constructible = target
3883            .as_object()
3884            .is_some_and(|target| target.is_constructor());
3885        let bound = JsObject::function(
3886            self.heap,
3887            Some(self.realm.function_proto.clone()),
3888            Callable::Bound { target, this, args },
3889        );
3890        bound.set_constructible(constructible);
3891        bound
3892    }
3893
3894    /// A new reference cell.
3895    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3896        Gc::new(self.heap, Cell::new(value))
3897    }
3898
3899    // -- running ------------------------------------------------------------
3900
3901    /// Evaluate `code` as a script body and return its completion value.
3902    /// Compile and run `source` for the engine's own use, returning its completion value.
3903    ///
3904    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3905    /// needs to be a real async function, and the engine already runs those as coroutines,
3906    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3907    ///
3908    /// Differences from [`Self::eval_in_global`], both deliberate:
3909    ///
3910    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3911    ///   being built, and the source is an IIFE that only constructs a closure, so there
3912    ///   is nothing to drain — and draining here would run script-queued jobs in the
3913    ///   middle of `install`.
3914    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3915    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3916    ///   and it should not look like the user wrote something wrong.
3917    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3918        let program = match js_parse::parse_script(source) {
3919            Ok(program) => program,
3920            Err(error) => {
3921                let message = format!("builtin source does not parse: {error}");
3922                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3923            }
3924        };
3925        let mut code = match js_compile::compile_script_with_source(&program, source) {
3926            Ok(code) => code,
3927            Err(error) => {
3928                let message = format!("builtin source does not compile: {}", error.message);
3929                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3930            }
3931        };
3932        // The frame has to name something, and `<builtin>` is what a stack trace through
3933        // this code should say.
3934        code.set_filename("<builtin>");
3935        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3936        let closure_vars = compiled.code.closure_vars.clone();
3937        let env = self.global_env(&closure_vars);
3938        let this = Value::Object(self.realm.global.clone());
3939        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3940    }
3941
3942    /// Run an already-parsed script and drain the microtasks it queued.
3943    ///
3944    /// The drain is what lets an `async` function's body advance past its first `await`
3945    /// before the host sees the result: nothing else pumps the job queue.
3946    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3947        let this = Value::Object(self.realm.global.clone());
3948        self.run_script_with_this(code, this)
3949    }
3950
3951    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3952    ///
3953    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3954    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3955    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3956    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3957    /// state the next script evaluation tripped over.
3958    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3959        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3960        let closure_vars = compiled.code.closure_vars.clone();
3961        let env = self.global_env(&closure_vars);
3962        let callee = Value::Undefined;
3963        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3964        // The script is done, so the microtasks it queued run before the host sees the
3965        // result. Without this an `async` function's body would never advance past its
3966        // first `await`, because nothing else drains the queue.
3967        self.drain_jobs()?;
3968        Ok(result)
3969    }
3970
3971    /// Compile and run `source` in global scope, returning its completion value.
3972    ///
3973    /// This is what `eval` and `new Function` use. Running it as a script means it
3974    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3975    /// for a `Function` body; a *direct* eval that reads a local variable would need
3976    /// the compiler to hand its variable environment over, which is not implemented.
3977    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3978        self.eval_in_global_named(source, EVAL_FILE, false)
3979    }
3980
3981    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3982    ///
3983    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3984    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3985    /// through the code, so they cannot share one constant.
3986    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3987        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3988    }
3989
3990    /// Evaluate `source` as a global script, reported under `file`.
3991    ///
3992    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3993    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3994    /// from inside a C callback, where the interpreter is the running one rather than a
3995    /// context's own.
3996    pub fn eval_in_global_named(
3997        &mut self,
3998        source: &str,
3999        file: &str,
4000        barrier: bool,
4001    ) -> JsResult<Value> {
4002        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4003        // eval-created global binding — configurable, unlike a script's own `var`.
4004        self.eval_depth += 1;
4005        if barrier {
4006            let depth = self.frames.len();
4007            self.trace_barriers.push(depth);
4008        }
4009        let result = self.eval_in_global_inner(source, file);
4010        if barrier {
4011            self.trace_barriers.pop();
4012        }
4013        self.eval_depth -= 1;
4014        result
4015    }
4016
4017    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
4018        let compiled = self.compile_global_script(source, file, false)?;
4019        let strict = compiled.strict;
4020        self.run_eval_script(compiled, strict)
4021    }
4022
4023    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4024    ///
4025    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4026    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4027    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4028    /// direct eval's is.
4029    pub fn eval_script_with_this(
4030        &mut self,
4031        source: &str,
4032        file: &str,
4033        this: Value,
4034    ) -> JsResult<Value> {
4035        let program = match js_parse::parse_script(source) {
4036            Ok(program) => program,
4037            Err(error) => {
4038                return Err(Signal::Throw(self.syntax_error_at(
4039                    file,
4040                    error.span.start.line,
4041                    error.span.start.column,
4042                    &error.message,
4043                )));
4044            }
4045        };
4046        let mut compiled = match js_compile::compile_script(&program) {
4047            Ok(compiled) => compiled,
4048            Err(error) => {
4049                return Err(Signal::Throw(self.syntax_error_at(
4050                    file,
4051                    error.span.start.line,
4052                    error.span.start.column,
4053                    &error.message,
4054                )));
4055            }
4056        };
4057        compiled.set_filename(file);
4058        self.run_script_with_this(compiled, this)
4059    }
4060
4061    /// Parse and compile `source` as a global script, without running it.
4062    ///
4063    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4064    /// before a promise exists to reject — while still evaluating in the same eval context
4065    /// (direct-eval strictness, `new.target`, `super`).
4066    fn compile_global_script(
4067        &mut self,
4068        source: &str,
4069        file: &str,
4070        async_body: bool,
4071    ) -> JsResult<CompiledFunction> {
4072        // A *direct* eval inherits the strictness of the code that called it, which is
4073        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
4074        // implicit global. The caller's frame is the innermost one here, because a
4075        // native function does not push a frame of its own.
4076        let strict = self.current_strict();
4077        // `eval` runs in the caller's function context, so `new.target` is legal here
4078        // even though the source is a bare script — and so is `super.x` when the caller
4079        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4080        // caller's, which is what `special_object 4` already does.
4081        // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4082        // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4083        // context at all. The site is what tells the two apart — an indirect call leaves no
4084        // site behind, since only a bare `eval(...)` is recorded.
4085        let site = self.eval_site_at_cursor();
4086        let private = site
4087            .map(|site| site.private_names.clone())
4088            .unwrap_or_default();
4089        let context = js_parse::EvalContext {
4090            in_method: site.is_some() && self.enclosing_home_object().is_some(),
4091            // `super()` belongs to a derived constructor, and an eval'd body is not a
4092            // constructor at all: the caller frame's `this` is already built.
4093            in_derived_constructor: false,
4094            // Private names are lexically scoped, so a direct `eval` inside a class body
4095            // can see them; see `Interp::eval_private_names`.
4096            private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4097            arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4098            new_target_allowed: site.is_some(),
4099        };
4100        // A *global* eval is not a function body: `new.target` and `super` are out of
4101        // reach there. Its `{async: true}` form differs in the other direction — the body
4102        // may `await` — so the two flags are independent and the reference sets both from
4103        // the eval type rather than from the caller.
4104        let parsed = if async_body {
4105            js_parse::parse_suspensible_global_eval(source, strict)
4106        } else {
4107            js_parse::parse_eval_script_in(source, strict, context)
4108        };
4109        let program = match parsed {
4110            Ok(program) => program,
4111            Err(error) => {
4112                // The message is bare: the position lives in `fileName`,
4113                // `lineNumber`, `columnNumber` and the stack frame above, which is where
4114                // the reference puts it. An `invalid source: L:C: ` prefix made
4115                // `e.message` differ from the reference while the stack already agreed.
4116                return Err(Signal::Throw(self.syntax_error_at(
4117                    file,
4118                    error.span.start.line,
4119                    error.span.start.column,
4120                    &error.message,
4121                )));
4122            }
4123        };
4124        let mut compiled = match if async_body {
4125            js_compile::compile_eval_with_private(&program, &private, true)
4126        } else {
4127            js_compile::compile_eval_with_private(&program, &private, false)
4128        } {
4129            Ok(compiled) => compiled,
4130            // A construct the compiler does not handle yet is reported the same way a
4131            // parse error is: it happens before anything runs, so the trace is the
4132            // position in the source followed by the caller.
4133            Err(error) => {
4134                return Err(Signal::Throw(self.syntax_error_at(
4135                    file,
4136                    error.span.start.line,
4137                    error.span.start.column,
4138                    &error.message,
4139                )));
4140            }
4141        };
4142        compiled.set_filename(file);
4143        Ok(compiled)
4144    }
4145
4146    /// The private names the code at the current position can see, innermost first.
4147    ///
4148    /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4149    /// direct `eval` runs inside its caller's scope, so
4150    /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4151    /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4152    /// here rather than being derivable from the eval'd source.
4153    ///
4154    /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4155    /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4156    /// [`Interp::run_eval_script`] uses for "direct".
4157    fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4158        let frame = self.frames.last()?;
4159        let (line, column) = frame
4160            .code
4161            .code
4162            .position_at(frame.at as u32)
4163            .unwrap_or_default();
4164        // The nearest site at or before the current position: the recorded position of the
4165        // `call` instruction is the callee's, which sits a few columns inside the call
4166        // expression the compiler recorded, so an exact match would never be found.
4167        frame
4168            .code
4169            .code
4170            .eval_sites
4171            .iter()
4172            .filter(|site| (site.line, site.column) <= (line, column))
4173            .max_by_key(|site| (site.line, site.column))
4174    }
4175
4176    /// Run an `eval`'d script in the caller's scope.
4177    ///
4178    /// Three things have to come from the calling frame, because the eval'd code is a
4179    /// script and would otherwise see only the global object:
4180    ///
4181    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4182    /// * `arguments`, exposed as a binding of the eval's own scope, so
4183    ///   `f("arguments.length", 1)` sees the caller's arguments;
4184    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4185    ///   `eval("var v = 1")` into the global object.
4186    ///
4187    /// Locals of the calling function are *not* reachable: that needs the compiler to
4188    /// hand its variable environment over, which this milestone does not do.
4189    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4190        // `this` and `arguments` come from the innermost frame only — those are not
4191        // lexical — while the name bindings come from the whole chain of frames, part
4192        // of it being ordinary scope resolution.
4193        // An arrow has no `this` of its own, so an `eval` inside one inherits the
4194        // enclosing function's receiver — the lexical `this` the arrow was compiled to
4195        // read from its closure.
4196        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4197        // variable environment is the innermost frame of all: an arrow's own body is where
4198        // `var`s declared by an `eval` inside it belong.
4199        let caller_index = self
4200            .frames
4201            .iter()
4202            .rposition(|frame| !frame.code.code.is_arrow)
4203            .or_else(|| self.frames.len().checked_sub(1));
4204        let env_index = self.frames.len().checked_sub(1);
4205        let caller = caller_index.and_then(|index| self.frames.get(index));
4206        let (this, passed) = match caller {
4207            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4208            // No frame at all: the eval is running at the top level, so there is
4209            // nothing to inherit and the global receiver is right.
4210            None => (Value::Object(self.realm.global.clone()), Vec::new()),
4211        };
4212        // Innermost frame first, so the first binding found for a name is the one that
4213        // shadows the rest. A script frame (`<eval>`) contributes nothing.
4214        let mut bindings: Vec<EvalBinding> = Vec::new();
4215        // The calling function's own bindings, resolved by the compiler at the call
4216        // site. That table is the only reliable answer when a name is declared twice in
4217        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4218        // body means, and guessing by declaration order picks the wrong one as soon as
4219        // two loops in a row use the same name.
4220        // Only a *direct* eval sees the caller's scope. The compiler records a site for
4221        // every direct call — a bare `eval(...)` callee — so finding one at the current
4222        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4223        // callee to a value first and leave no site behind.
4224        let mut direct = false;
4225        let mut resolved_here = false;
4226        if let Some(frame) = self.frames.last() {
4227            let (line, column) = frame
4228                .code
4229                .code
4230                .position_at(frame.at as u32)
4231                .unwrap_or_default();
4232            // The nearest site at or before the current position, not an exact match:
4233            // the recorded position of the `call` instruction is the callee's, which
4234            // sits a few columns inside the call expression the compiler recorded. A
4235            // site is unique per call, so "the closest one behind us" identifies it.
4236            if let Some(site) = frame
4237                .code
4238                .code
4239                .eval_sites
4240                .iter()
4241                .filter(|site| (site.line, site.column) <= (line, column))
4242                .max_by_key(|site| (site.line, site.column))
4243            {
4244                direct = true;
4245                resolved_here = true;
4246                for binding in &site.bindings {
4247                    // An enclosing function's frame sits `owner` levels below the one
4248                    // running the call.
4249                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4250                    else {
4251                        continue;
4252                    };
4253                    bindings.push(EvalBinding {
4254                        name: binding.name.clone(),
4255                        frame,
4256                        slot: if binding.is_arg {
4257                            EvalSlot::Arg
4258                        } else {
4259                            EvalSlot::Local
4260                        },
4261                        index: binding.index as usize,
4262                    });
4263                }
4264            }
4265        }
4266        for frame_index in (0..self.frames.len()).rev() {
4267            // Skip the innermost frame's flat scan when the compiler already answered
4268            // for it; an enclosing frame still needs one, because the eval resolves
4269            // those names dynamically.
4270            if resolved_here && frame_index == self.frames.len() - 1 {
4271                continue;
4272            }
4273            let frame = &self.frames[frame_index];
4274            for (index, arg) in frame.code.code.args.iter().enumerate() {
4275                bindings.push(EvalBinding {
4276                    name: arg.name.clone(),
4277                    frame: frame_index,
4278                    slot: EvalSlot::Arg,
4279                    index,
4280                });
4281            }
4282            for (index, local) in frame.code.code.vars.iter().enumerate() {
4283                bindings.push(EvalBinding {
4284                    name: local.name.clone(),
4285                    frame: frame_index,
4286                    slot: EvalSlot::Local,
4287                    index,
4288                });
4289            }
4290        }
4291        let mut seen = BTreeSet::new();
4292        bindings.retain(|binding| seen.insert(binding.name.clone()));
4293
4294        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4295        // elements is all the spec's ordinary uses need.
4296        //
4297        // Known divergence: this is bound for a *global* eval too, where there is no
4298        // caller and the reference throws `'arguments' is not defined`. Deciding properly
4299        // needs "does the calling frame have an `arguments` of its own", which is not
4300        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4301        // script or eval body does not, and `eval(b)` passes the callee as a value so even
4302        // the call-site detection does not answer it. Modelled as a binding in the caller's
4303        // variable environment, this would fall out; that is a larger change than the one
4304        // this comment is attached to.
4305        let arguments = Value::Object(self.new_array(passed));
4306
4307        // Only a *strict* eval gets a variable environment of its own. A sloppy one
4308        // declares its `var`s in the caller's — which for a top-level eval is the global
4309        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4310        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4311        // vanish into a scope nobody reads back from.
4312        let previous_scope = if code_strict {
4313            self.eval_scope.replace(BTreeMap::new())
4314        } else {
4315            None
4316        };
4317        // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4318        // in global scope, where `arguments` means whatever the global object says — which
4319        // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4320        // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4321        // answer the array instead.
4322        let previous_arguments = if direct {
4323            self.eval_arguments.replace(arguments)
4324        } else {
4325            None
4326        };
4327        let previous_with = self.eval_with.replace(self.with_objects());
4328        let inherited_new_target = self
4329            .frames
4330            .iter()
4331            .rev()
4332            .find(|frame| !frame.code.code.is_arrow)
4333            .map(|frame| frame.new_target.clone());
4334        let previous_new_target = self
4335            .eval_new_target
4336            .replace(inherited_new_target.unwrap_or(Value::Undefined));
4337        let eval_cells = self.eval_cells_for(&bindings);
4338        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4339        // A sloppy direct eval declares its `var`s in the caller's variable environment;
4340        // `declare_eval_local` needs to know which frame that is.
4341        // An indirect eval gets the global environment, so nothing of the caller's is
4342        // recorded as the place its `var`s belong.
4343        let previous_caller = self
4344            .eval_caller
4345            .replace(if direct { env_index } else { None });
4346        // The cell-based view of the same bindings, which is what a closure created
4347        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4348        // whose compiler did not put a binding in a cell simply does not appear here —
4349        // reads and writes still work through `eval_bindings`, they just cannot outlive
4350        // the eval.
4351        let previous_eval_scope = self
4352            .active_eval_scope
4353            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4354        let compiled = Gc::new(self.heap, CompiledCode::new(code));
4355        let closure_vars = compiled.code.closure_vars.clone();
4356        // Declaration instantiation is where this belongs: the check needs the caller frame
4357        // (recorded just above) and the eval's own var names, and it raises before any of
4358        // the eval's code runs.
4359        self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4360        let env = self.global_env(&closure_vars);
4361        let callee = Value::Undefined;
4362        // An async body does not run here: it becomes a coroutine and answers a promise,
4363        // which is what makes `await` legal in it. `this` still has to be the caller's
4364        // (for a global eval, the global object), because `this` is not part of `await`.
4365        let result = if compiled.code.kind.is_async() {
4366            self.run_async_body(compiled, env, this)
4367        } else {
4368            self.execute(compiled, env, this, Vec::new(), callee)
4369        };
4370        self.eval_scope = previous_scope;
4371        self.eval_arguments = previous_arguments;
4372        self.eval_with = previous_with;
4373        self.eval_new_target = previous_new_target;
4374        self.eval_bindings = previous_bindings;
4375        self.eval_caller = previous_caller;
4376        self.active_eval_scope = previous_eval_scope;
4377        result
4378    }
4379
4380    /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4381    /// rather than bindings.
4382    ///
4383    /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4384    /// declaration that cannot exist:
4385    ///
4386    /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4387    ///   parameter expressions a separate parameter environment, and `arguments` is bound
4388    ///   implicitly there, so a `var` of that name collides. An arrow that binds no
4389    ///   `arguments` of its own has nothing to collide with and is allowed — see the table in
4390    ///   [`Interp::check_eval_var_named_arguments`].
4391    /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4392    ///   false; the operation is a `TypeError`, and `eval("var x")` with
4393    ///   `Object.preventExtensions(this)` must raise rather than quietly do nothing
4394    ///   (`non-definable-global-var` and its four siblings).
4395    fn check_eval_var_named_arguments(
4396        &self,
4397        closure_vars: &[js_compile::bytecode::ClosureVar],
4398        strict: bool,
4399    ) -> JsResult<()> {
4400        if strict {
4401            return Ok(());
4402        }
4403        // A `var` this eval would declare on the global object, where there is no room for it.
4404        let global = &self.realm.global;
4405        if !global.is_extensible() {
4406            for var in closure_vars {
4407                if var.is_lexical || var.name == "*default*" {
4408                    continue;
4409                }
4410                let declare = matches!(
4411                    var.closure_type,
4412                    js_compile::bytecode::ClosureType::GlobalDecl
4413                );
4414                if declare && global.own_property(&var.name).is_none() {
4415                    return Err(Signal::Throw(self.make_error(
4416                        "TypeError",
4417                        "cannot declare a global in a non-extensible global object",
4418                    )));
4419                }
4420            }
4421        }
4422        // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4423        // global environment, where `var arguments` is an ordinary global.
4424        let Some(caller) = self.eval_caller.flatten() else {
4425            return Ok(());
4426        };
4427        if !closure_vars
4428            .iter()
4429            .any(|var| var.name == "arguments" && !var.is_lexical)
4430        {
4431            return Ok(());
4432        }
4433        // The body of a function is a different environment from its parameter list, and only
4434        // the parameter list is separate from `arguments`.
4435        if !self.in_parameter_list_at(caller) {
4436            return Ok(());
4437        }
4438        let caller_is_arrow = self
4439            .frames
4440            .get(caller)
4441            .is_some_and(|frame| frame.code.code.is_arrow);
4442        // A *parameter* named `arguments`, not merely a binding of that name: a body
4443        // `let arguments` is in the body's environment, which is the one that is separate and
4444        // therefore cannot collide. The slot tells them apart — an argument lives in
4445        // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4446        let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4447            binding.frame == caller
4448                && binding.name == "arguments"
4449                && matches!(binding.slot, EvalSlot::Arg)
4450        });
4451        if caller_is_arrow && !parameter_scope_binds_arguments {
4452            return Ok(());
4453        }
4454        Err(Signal::Throw(self.make_error(
4455            "SyntaxError",
4456            "eval declares 'arguments' in a function's parameter scope",
4457        )))
4458    }
4459
4460    /// The cell-backed subset of `bindings`, in the same priority order.
4461    ///
4462    /// Both lookup routes have to agree — the eval's own reads go through
4463    /// [`Interp::eval_binding_value`] and the closures it builds go through
4464    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4465    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4466    /// is not in a cell simply does not appear: reads and writes still work, they just
4467    /// cannot be handed to a closure that outlives the eval.
4468    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4469        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4470        for binding in bindings {
4471            let Some(frame) = self.frames.get(binding.frame) else {
4472                continue;
4473            };
4474            let cell = match binding.slot {
4475                EvalSlot::Arg => frame
4476                    .code
4477                    .arg_cell
4478                    .get(binding.index)
4479                    .copied()
4480                    .unwrap_or(-1),
4481                EvalSlot::Local => frame
4482                    .code
4483                    .loc_cell
4484                    .get(binding.index)
4485                    .copied()
4486                    .unwrap_or(-1),
4487            };
4488            if cell < 0 {
4489                continue;
4490            }
4491            if let Some(cell) = frame.cells.get(cell as usize) {
4492                names.push((binding.name.clone(), cell.clone()));
4493            }
4494        }
4495        names
4496    }
4497
4498    /// A `SyntaxError` that reports where in the source it happened.
4499    ///
4500    /// Compile-time failures never run, so they have no frame of their own; the
4501    /// reference still puts the position first in the trace, with no function name and
4502    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4503    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4504    /// reference borrows), which is how a script reads the position without parsing
4505    /// the trace.
4506    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4507    ///
4508    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4509    /// `columnNumber`, which is how the reference prints one. A positionless error
4510    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4511    /// the reference raises it from `js_resolve_module`, where there is no position.
4512    pub(crate) fn syntax_error_plain(
4513        &mut self,
4514        error: &js_parse::SyntaxError,
4515        file: &str,
4516    ) -> Value {
4517        if error.positionless {
4518            return self.make_error("SyntaxError", &error.message);
4519        }
4520        self.syntax_error_at(
4521            file,
4522            error.span.start.line,
4523            error.span.start.column,
4524            &error.message,
4525        )
4526    }
4527
4528    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4529        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
4530        let value = self.make_error("SyntaxError", message);
4531        if let Value::Object(object) = &value {
4532            let text = self.string(blamed);
4533            // `stack` is an own data property, and the reference keeps it
4534            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4535            object.define("stack", Property::with_attributes(text, true, false));
4536            let name = self.string(file);
4537            object.define("fileName", Property::with_attributes(name, true, true));
4538            object.define(
4539                "lineNumber",
4540                Property::with_attributes(Value::Int(line as i32), true, true),
4541            );
4542            object.define(
4543                "columnNumber",
4544                Property::with_attributes(Value::Int(column as i32), true, true),
4545            );
4546        }
4547        value
4548    }
4549
4550    /// Run a compiled script whose completion value is a function, returning it.
4551    ///
4552    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4553    /// get the closure out, which keeps the constant-pool plumbing in one place.
4554    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4555        self.run_script(code)
4556    }
4557
4558    /// The environment of a script or of any function compiled at global scope:
4559    /// every entry is a global binding, so each one resolves to the realm's cell.
4560    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4561        let mut cells = Vec::with_capacity(closure_vars.len());
4562        for closure_var in closure_vars {
4563            let cell = match closure_var.closure_type {
4564                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4565                    if closure_var.is_lexical =>
4566                {
4567                    // A lexical declaration: the cell is created here holding the
4568                    // dead-zone marker, which is what makes the binding exist and
4569                    // unreadable before its initialiser runs.
4570                    self.declare_global(&closure_var.name, closure_var.is_const);
4571                    self.realm.globals[&closure_var.name].clone()
4572                }
4573                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4574                    // A `var` or function declaration becomes a property of the global
4575                    // object, and it exists from here on — which is why
4576                    // `print(v); var v = 1` prints `undefined` instead of raising.
4577                    // Declaring it at instantiation time (rather than at the
4578                    // initialiser) is also what makes it non-configurable: the store
4579                    // then lands on an existing property instead of creating one.
4580                    self.declare_var_global(&closure_var.name);
4581                    // The cell is a placeholder that nothing indexes; it cannot be
4582                    // omitted because the slot has to hold something.
4583                    self.new_cell(Value::Undefined)
4584                }
4585                _ => {
4586                    // An undeclared global is read by name; the cell is a
4587                    // placeholder that nothing indexes.
4588                    self.new_cell(Value::Undefined)
4589                }
4590            };
4591            cells.push(cell);
4592        }
4593        Gc::new(
4594            self.heap,
4595            ClosureEnv {
4596                cells,
4597                eval_scope: None,
4598                local_vars: None,
4599                local_phase: 1,
4600            },
4601        )
4602    }
4603
4604    /// Push a frame and run until it returns.
4605    pub(crate) fn execute(
4606        &mut self,
4607        code: Gc<CompiledCode>,
4608        env: Gc<ClosureEnv>,
4609        this: Value,
4610        args: Vec<Value>,
4611        callee: Value,
4612    ) -> JsResult<Value> {
4613        let depth = self.frames.len();
4614        if depth == 0 {
4615            // A throw that reached the host ends the *active* mode: the next one is catchable
4616            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4617            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4618            // for the throw that evaluation will raise.
4619            self.uncatchable = false;
4620        }
4621        self.push_frame(code, env, this, args, callee)?;
4622        loop {
4623            // The fast loop first: it runs whole runs of records with `pc` in a register.
4624            //
4625            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4626            // reads it again — a store, a load and two bounds checks that a loop body does
4627            // not need, because nothing outside the loop can run in between. This is the
4628            // classic split: advance a register, and only spill it when leaving.
4629            //
4630            // `Some(value)` means the function ended by running off the end of its
4631            // instruction array, which is a normal return.
4632            let step = match self.run_fast() {
4633                Ok(Some(value)) => Ok(Step::Return(value)),
4634                Ok(None) => self.step(),
4635                Err(signal) => Err(signal),
4636            };
4637            match step {
4638                Ok(Step::Continue) => {}
4639                Ok(Step::Return(value)) => {
4640                    self.pop_frame();
4641                    // A frame that ended in a `tail_call` hands its value straight to
4642                    // its caller: nothing after the call can run, so every frame above
4643                    // the callee unwinds with the same value. See [`Frame::tail`] —
4644                    // the reference does not reuse frames either, so recursion depth
4645                    // and the stack-overflow limit behave the same way.
4646                    while self.frames.len() > depth && self.frame().tail {
4647                        self.pop_frame();
4648                    }
4649                    if self.frames.len() == depth {
4650                        return Ok(value);
4651                    }
4652                    // The caller resumes with the value on its stack.
4653                    self.frames
4654                        .last_mut()
4655                        .expect("a caller is live")
4656                        .stack
4657                        .push(value);
4658                }
4659                Err(Signal::Throw(value)) => {
4660                    // The host's standing request becomes the active mode for this unwind,
4661                    // and is consumed here so it does not leak into the next throw.
4662                    if self.uncatchable_next {
4663                        self.uncatchable_next = false;
4664                        self.uncatchable = true;
4665                    }
4666                    // An uncatchable throw walks past every `catch` on the way out. The
4667                    // frames are still popped, because the values they hold have to be
4668                    // dropped — only the search for a handler is skipped.
4669                    if self.uncatchable {
4670                        while self.frames.len() > depth {
4671                            self.frames.pop();
4672                        }
4673                        return Err(Signal::Throw(value));
4674                    }
4675                    // A handler lives on the stack of the frame that is throwing —
4676                    // `catch` pushed it there — so this frame gets the first chance
4677                    // to catch before it is popped.
4678                    let value = value;
4679                    loop {
4680                        if self.frames.len() <= depth {
4681                            return Err(Signal::Throw(value));
4682                        }
4683                        if self.catch_here(value.clone()).is_some() {
4684                            break;
4685                        }
4686                        self.frames.pop();
4687                    }
4688                }
4689                // A `yield` in a frame that `execute` is running directly means a
4690                // generator body was entered as an ordinary call, which only happens if
4691                // the generator check in `call_or_push` was bypassed.
4692                Ok(Step::Suspend(_)) => {
4693                    return Err(Signal::Throw(self.make_error(
4694                        "InternalError",
4695                        "a generator body ran as an ordinary call",
4696                    )));
4697                }
4698                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4699            }
4700        }
4701    }
4702
4703    /// Install a handler for `value` if this frame has one, resuming at it.
4704    ///
4705    /// The scan is the reference's: walk the frame's stack downwards looking for the
4706    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4707    /// `0` is an enumerator marker rather than a handler — it exists so that a
4708    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4709    /// here and the unwinding continues.
4710    fn catch_here(&mut self, value: Value) -> Option<()> {
4711        let frame = self.frames.last_mut()?;
4712        while let Some(top) = frame.stack.pop() {
4713            if let Value::CatchOffset(offset) = top {
4714                if offset == 0 {
4715                    continue;
4716                }
4717                frame.stack.push(value);
4718                frame.pc = offset as usize;
4719                return Some(());
4720            }
4721        }
4722        None
4723    }
4724
4725    fn push_frame(
4726        &mut self,
4727        code: Gc<CompiledCode>,
4728        env: Gc<ClosureEnv>,
4729        this: Value,
4730        mut args: Vec<Value>,
4731        callee: Value,
4732    ) -> JsResult<()> {
4733        // Two bounds, and the byte budget is the one that decides in practice. The
4734        // reference's message is `stack overflow` on an `InternalError`, not V8's
4735        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4736        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4737        let frame_cost = Self::frame_cost(&code);
4738        let stack_base = self.stack_used();
4739        if self.frames.len() >= self.max_frames
4740            || stack_base.saturating_add(frame_cost) > self.stack_limit
4741        {
4742            return Err(Signal::Throw(
4743                self.make_error("InternalError", "stack overflow"),
4744            ));
4745        }
4746        let arg_count = code.code.args.len();
4747        // How many were actually passed, which `arguments.length` reports and
4748        // `assert(x)` depends on: a call with one argument must not look like a call
4749        // with one argument and an explicit `undefined`.
4750        let passed = args.len();
4751        // Missing arguments are `undefined` in their slots; extra ones are dropped
4752        // from the slots but still reachable through `arguments`.
4753        //
4754        // A call that passes no more than the declared parameters needs **no** copy:
4755        // after the resize below, `args[..passed]` *is* the passed values. Only the
4756        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4757        // the rare case. This used to copy every call: one `Value` clone per argument
4758        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4759        let passed_overflow = (passed > arg_count).then(|| {
4760            let mut values = self.take_values(passed, Value::Undefined);
4761            values[..passed].clone_from_slice(&args[..passed]);
4762            values
4763        });
4764        // Only when the counts differ, which for the overwhelmingly common call — as many
4765        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4766        // lengths is two length compares and nothing else, but this is the hottest few
4767        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4768        if passed != arg_count {
4769            args.resize(arg_count, Value::Undefined);
4770            args.truncate(arg_count);
4771        }
4772        let cell_count = code.code.var_ref_count as usize;
4773        let mut cells = Vec::with_capacity(cell_count);
4774        for _ in 0..cell_count {
4775            cells.push(self.new_cell(Value::Undefined));
4776        }
4777        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4778        // A captured argument lives in its cell, not in the argument slot, so the
4779        // incoming value has to be moved there before the body runs.
4780        for (slot, cell) in code.arg_cell.iter().enumerate() {
4781            if *cell >= 0
4782                && let Some(value) = args.get(slot).cloned()
4783            {
4784                cells[*cell as usize].set(value);
4785            }
4786        }
4787        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4788        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4789        // reports `object`. Strict mode passes the value through untouched.
4790        let this = if code.code.strict {
4791            this
4792        } else if this.is_nullish() {
4793            Value::Object(self.realm.global.clone())
4794        } else if matches!(this, Value::Object(_)) {
4795            this
4796        } else {
4797            match crate::builtins::this_object(self, &this) {
4798                Ok(boxed) => Value::Object(boxed),
4799                Err(_) => this,
4800            }
4801        };
4802        let stack_depth = code.code.stack_size as usize + 1;
4803        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4804        // out of the same recycle pool the locals did.
4805        let stack = self.take_values(stack_depth, Value::Undefined);
4806        self.frames.push(Frame {
4807            code,
4808            env,
4809            this,
4810            args,
4811            passed_count: passed,
4812            passed_overflow: passed_overflow.map(Box::new),
4813            locals,
4814            cells,
4815            local_vars: None,
4816            // Exactly the depth the compiler computed, so the operand stack never
4817            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4818            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4819            // the buffer between calls, so "exactly" costs nothing after the first one.
4820            stack,
4821            pc: 0,
4822            at: 0,
4823            callee,
4824            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4825            cost: frame_cost,
4826            stack_base,
4827            tail: false,
4828        });
4829        Ok(())
4830    }
4831
4832    /// A value buffer of `len` slots, from the recycle pool when there is one.
4833    ///
4834    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4835    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4836        // A frame with no locals asks for nothing, and that is most frames: taking a
4837        // buffer out of the pool, clearing it and resizing it to zero is four operations
4838        // and a pool pop for an empty `Vec`, which is free to construct.
4839        if len == 0 {
4840            return Vec::new();
4841        }
4842        let mut buffer = self.free_values.pop().unwrap_or_default();
4843        buffer.clear();
4844        buffer.resize(len, fill);
4845        buffer
4846    }
4847
4848    /// Return a finished frame's value buffers for the next call to reuse.
4849    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4850        for mut buffer in [
4851            std::mem::take(&mut frame.locals),
4852            frame
4853                .passed_overflow
4854                .take()
4855                .map(|buffer| *buffer)
4856                .unwrap_or_default(),
4857            std::mem::take(&mut frame.stack),
4858        ] {
4859            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4860            // GC root: it kept every value the frame held reachable, which is invisible
4861            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4862            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4863            // exactly that within one run — the target `{}` of a finished IIFE was still
4864            // in its operand stack, in the pool.
4865            buffer.clear();
4866            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4867            // fill the pool with nothing to offer.
4868            if free_values.len() < RECYCLE_SLOTS
4869                && buffer.capacity() > 0
4870                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4871            {
4872                free_values.push(buffer);
4873            }
4874        }
4875    }
4876
4877    /// Pop a finished frame and keep its buffers.
4878    ///
4879    /// Every place that drops a frame goes through here: a recycled buffer is also where
4880    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4881    /// nothing but the reuse.
4882    fn pop_frame(&mut self) -> Option<()> {
4883        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4884        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4885        let last = self.frames.len().checked_sub(1)?;
4886        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4887        self.frames.truncate(last);
4888        Some(())
4889    }
4890
4891    /// Poll the host's interrupt handler, if one is installed.
4892    ///
4893    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4894    /// one `Option` test, and with no handler installed the whole function is that test —
4895    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4896    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4897    #[inline]
4898    fn check_interrupt(&mut self) -> JsResult<()> {
4899        if self.interrupt.is_none() {
4900            return Ok(());
4901        }
4902        if self.interrupt_counter > 0 {
4903            self.interrupt_counter -= 1;
4904            return Ok(());
4905        }
4906        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4907        // The closure is taken out for the duration so that a handler which re-enters the
4908        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4909        let mut handler = self.interrupt.take().expect("checked above");
4910        let abort = handler();
4911        self.interrupt = Some(handler);
4912        if abort {
4913            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4914            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4915            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4916            // documentation says.
4917            self.uncatchable = true;
4918            return Err(Signal::Throw(
4919                self.make_error("InternalError", "interrupted"),
4920            ));
4921        }
4922        Ok(())
4923    }
4924
4925    /// A memory checkpoint: does the heap still fit under its limit?
4926    ///
4927    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4928    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4929    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4930    /// only at calls would let it run until the machine died, which is the exact failure
4931    /// `--memory-limit` exists to prevent.
4932    ///
4933    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4934    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4935    /// script that catches it, drops the reference and carries on is legitimate: measured
4936    /// on `qjs --memory-limit 1M`, the engine recovers.
4937    fn check_memory(&mut self) -> JsResult<()> {
4938        // One `Cell` read and a predictable branch when no limit is set, and an integer
4939        // compare when one is. Containers report their own growth as it happens
4940        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4941        // walking it here was the first version and it was O(live) per 256 instructions,
4942        // which turned a 100k-element push loop into a five-minute one.
4943        let Some(limit) = self.heap.memory_limit() else {
4944            return Ok(());
4945        };
4946        let used = self.heap.used_bytes();
4947        if used <= limit {
4948            // Back under the limit — a collection or a dropped reference did it. The next
4949            // time it goes over is a new failure, not a repeat of this one.
4950            self.oom_reported_at = 0;
4951            return Ok(());
4952        }
4953        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4954        // block runs normally after `out of memory` — it allocates nothing, so nothing
4955        // fails. A check that re-fired on every instruction made the handler itself throw,
4956        // which is a dead end: the error became unobservable from script.
4957        //
4958        // Comparing against the total at the last report gives the same behaviour: the
4959        // handler runs while the total is unchanged, and the very next allocation over the
4960        // limit fails.
4961        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4962        {
4963            return Ok(());
4964        }
4965        self.oom_reported_at = used;
4966        Err(Signal::Throw(
4967            self.make_error("InternalError", "out of memory"),
4968        ))
4969    }
4970
4971    /// Fail before allocating `payload` bytes, if they would not fit.
4972    ///
4973    /// For the allocations whose size comes from script data — `new Array(n)`,
4974    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4975    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4976    /// answering NULL for the one big request.
4977    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4978        if self.heap.fits(payload) {
4979            return Ok(());
4980        }
4981        Err(Signal::Throw(
4982            self.make_error("InternalError", "out of memory"),
4983        ))
4984    }
4985
4986    /// Bytes of frame state the live call chain accounts for.
4987    pub fn stack_used(&self) -> usize {
4988        match self.frames.last() {
4989            Some(frame) => frame.stack_base + frame.cost,
4990            None => 0,
4991        }
4992    }
4993
4994    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4995    ///
4996    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4997    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4998    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4999    /// instead. That is the whole difference between the two models: it rations C stack, we
5000    /// ration frame state, and both quantities are dominated by the value slots — which is
5001    /// why the two depths come out comparable rather than merely proportional.
5002    fn frame_cost(code: &CompiledCode) -> usize {
5003        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5004        std::mem::size_of::<Frame>()
5005            + std::mem::size_of::<Value>() * slots
5006            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5007    }
5008
5009    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5010    ///
5011    /// Only names the eval created are here: a name the frame already declared statically
5012    /// is written through to its own slot instead, so this cannot shadow a real local.
5013    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5014        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5015        let (local_vars, phase) = self.visible_local_vars()?;
5016        if !local_vars.contains(name) {
5017            return None;
5018        }
5019        local_vars.get(name, phase)
5020    }
5021
5022    /// The variables a direct `eval` declared, as the code currently running sees them.
5023    ///
5024    /// Inside an eval that is the *caller's* set — the eval's own variable environment
5025    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5026    /// else it is the current frame's, falling back to the frame the closure was created
5027    /// in.
5028    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5029    ///
5030    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5031    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5032    /// refcount operations (the clone out of the frame, the drop at the end of the match)
5033    /// just to be asked `is_none`.
5034    fn has_visible_local_vars(&self) -> bool {
5035        let index = match self.eval_caller.flatten() {
5036            Some(caller) => caller,
5037            None => match self.frames.len().checked_sub(1) {
5038                Some(top) => top,
5039                None => return false,
5040            },
5041        };
5042        match self.frames.get(index) {
5043            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5044            None => false,
5045        }
5046    }
5047
5048    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5049        // While an `eval` runs, its own frame is on top but its variable environment is
5050        // the *caller's* — so the caller is what the lookup has to start from.
5051        let (index, phase) = match self.eval_caller.flatten() {
5052            Some(caller) => (
5053                caller,
5054                if self.in_parameter_list_at(caller) {
5055                    0
5056                } else {
5057                    1
5058                },
5059            ),
5060            None => (
5061                self.frames.len().checked_sub(1)?,
5062                if self.in_parameter_list() { 0 } else { 1 },
5063            ),
5064        };
5065        let frame = self.frames.get(index)?;
5066        // The frame's own variables, or — for an arrow, which has no variable environment
5067        // of its own — the one it was created in, which `ClosureEnv` carries.
5068        if let Some(local_vars) = frame.local_vars.clone() {
5069            return Some((local_vars, phase));
5070        }
5071        frame
5072            .env
5073            .local_vars
5074            .clone()
5075            .map(|local_vars| (local_vars, frame.env.local_phase))
5076    }
5077
5078    /// Whether the innermost frame is still evaluating its parameter list.
5079    ///
5080    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5081    /// and a closure created there may only see that much of [`LocalVars`].
5082    fn in_parameter_list(&self) -> bool {
5083        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5084    }
5085
5086    /// [`Interp::in_parameter_list`] for a specific frame.
5087    fn in_parameter_list_at(&self, frame: usize) -> bool {
5088        let Some(frame) = self.frames.get(frame) else {
5089            return false;
5090        };
5091        let code = &frame.code.code;
5092        if !code.has_parameter_expressions {
5093            return false;
5094        }
5095        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5096        // function as its body and let a direct `eval` act accordingly.
5097        if code.body_start == (0, 0) {
5098            return false;
5099        }
5100        match code.position_at(frame.at as u32) {
5101            Some(position) => position < code.body_start,
5102            None => false,
5103        }
5104    }
5105
5106    fn frame(&self) -> &Frame {
5107        self.frames.last().expect("a frame is live")
5108    }
5109
5110    fn frame_mut(&mut self) -> &mut Frame {
5111        self.frames.last_mut().expect("a frame is live")
5112    }
5113
5114    // -- slot access --------------------------------------------------------
5115
5116    /// Move a local's value out, leaving `undefined` in the slot.
5117    ///
5118    /// `None` for a captured slot: its value lives in a cell shared with every closure
5119    /// that closed over it, so it can never be exclusively ours and must not be taken.
5120    ///
5121    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5122    /// for every read and fatal for this one — a clone is exactly the second handle that
5123    /// rules out growing the string in place.
5124    fn take_loc(&mut self, slot: usize) -> Option<Value> {
5125        let frame = self.frames.last_mut()?;
5126        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5127            return None;
5128        }
5129        frame
5130            .locals
5131            .get_mut(slot)
5132            .map(|value| std::mem::replace(value, Value::Undefined))
5133    }
5134
5135    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5136    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5137    ///
5138    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5139    /// it** — the value is put back before the general path runs — so a `valueOf` that
5140    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5141    /// error as it would have without the fusion. This is why the in-place attempt is a
5142    /// `take` and not a `get`: an optimisation that changes what an exception observes is
5143    /// a wrong answer with a good excuse.
5144    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5145        // The take is `matches!`-guarded on the *right* operand only, and the taken value
5146        // is put back on every path that does not append. An earlier version wrote the two
5147        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5148        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5149        // through with its value already taken and dropped: the general path below then
5150        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5151        // A wrong answer, from an optimisation, with every test green.
5152        if matches!(right, Value::String(_))
5153            && let Some(taken) = self.take_loc(slot)
5154        {
5155            if let Value::String(mut left) = taken {
5156                let appended = match left.get_mut() {
5157                    Some(string) => string.append_in_place(
5158                        // The pattern is the one `matches!` just checked.
5159                        match &right {
5160                            Value::String(text) => text,
5161                            _ => unreachable!("guarded above"),
5162                        },
5163                    ),
5164                    None => None,
5165                };
5166                self.put_loc(slot, Value::String(left));
5167                if let Some(added) = appended {
5168                    // The buffer grew where it stood, so the heap's running total has to
5169                    // be told: `measure_used` would report the new length, and the two must
5170                    // agree or the subtraction at free time leaves the counter wrong.
5171                    self.heap.adjust_payload(added as isize);
5172                    return Ok(());
5173                }
5174            } else {
5175                self.put_loc(slot, taken);
5176            }
5177        }
5178        // The two-number case, without an operand stack round trip. Everything below
5179        // this point is the *general* path: push both, call `binary_add`, pop the answer,
5180        // store it — five operations and two `Value` clones for what is one integer add.
5181        // `AddImmLoc` already answers this shape that way; the fusion above it was written
5182        // for string append and never got the numeric half, so `t += i` — a counting loop
5183        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5184        let left = self.get_loc(slot);
5185        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5186            self.put_loc(
5187                slot,
5188                match a.checked_add(*b) {
5189                    Some(sum) => Value::Int(sum),
5190                    None => Value::Float(*a as f64 + *b as f64),
5191                },
5192            );
5193            return Ok(());
5194        }
5195        self.push(left);
5196        self.push(right);
5197        self.binary_add()?;
5198        let value = self.pop();
5199        self.put_loc(slot, value);
5200        Ok(())
5201    }
5202
5203    fn get_arg(&self, slot: usize) -> Value {
5204        self.frame().read_arg(slot)
5205    }
5206
5207    fn put_arg(&mut self, slot: usize, value: Value) {
5208        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5209        if cell == -1 {
5210            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5211                *slot = value;
5212            }
5213        } else {
5214            self.frame().cells[cell as usize].set(value);
5215        }
5216    }
5217
5218    fn get_loc(&self, slot: usize) -> Value {
5219        // The cell mapping is `-1` for every slot that was not captured — which is all of
5220        // them in a function that creates no closure. `Frame::read_loc` tests that first,
5221        // so the common case is one array read and a clone: 20% of every loop iteration
5222        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5223        // sample of `dispatch:arith`).
5224        self.frame().read_loc(slot)
5225    }
5226
5227    fn put_loc(&mut self, slot: usize, value: Value) {
5228        // One borrow instead of three, and the cell check on the frame we already hold.
5229        let frame = self.frames.last_mut().expect("a frame is live");
5230        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5231        if cell < 0 {
5232            if let Some(slot) = frame.locals.get_mut(slot) {
5233                *slot = value;
5234            }
5235        } else if let Some(cell) = frame.cells.get(cell as usize) {
5236            cell.set(value);
5237        }
5238    }
5239
5240    // -- globals ------------------------------------------------------------
5241
5242    /// The name a global-slot operand refers to.
5243    fn global_name(&self, slot: usize) -> String {
5244        self.frame()
5245            .code
5246            .code
5247            .closure_vars
5248            .get(slot)
5249            .map(|c| c.name.clone())
5250            .unwrap_or_default()
5251    }
5252
5253    /// The facts about a global binding that decide where it lives.
5254    ///
5255    /// A script's globals split in two, and the split is observable: `var` and
5256    /// function declarations become properties of the global object (`globalThis.v`
5257    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5258    /// declarations live in the global *lexical* environment and are invisible there
5259    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5260    /// `is_lexical` flag means the answer is already in the bytecode.
5261    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5262        let name = self.global_name(slot);
5263        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5264        // while forwarding a reference through a nested function is built with the
5265        // flags cleared, so `const c` would look like an ordinary `var` from inside a
5266        // closure. Presence in the realm's lexical table is the same fact, recorded
5267        // once, and every slot sees it.
5268        let lexical = self.realm.globals.contains_key(&name);
5269        let is_const = self.realm.lexical_consts.contains(&name);
5270        (name, lexical, is_const)
5271    }
5272
5273    /// The value of `name` in the innermost active `with` object, if any.
5274    ///
5275    /// The active objects are the [`VarKind::With`] locals of every frame still running,
5276    /// innermost frame first and innermost block first within one. Walking frames rather
5277    /// than keeping a separate stack is what makes a closure called from inside a `with`
5278    /// see it, and what keeps the object alive only as long as the block is.
5279    /// The innermost active `with` object that has `name`, if any.
5280    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5281        let objects = self.eval_with.clone().unwrap_or_default();
5282        for object in objects {
5283            let key = self.string(name.to_string());
5284            if self
5285                .has_property(&key, &Value::Object(object.clone()))
5286                .ok()?
5287            {
5288                return Some(object);
5289            }
5290        }
5291        None
5292    }
5293
5294    /// Every active `with` object, innermost first.
5295    fn with_objects(&self) -> Vec<Gc<JsObject>> {
5296        let mut objects = Vec::new();
5297        for frame in self.frames.iter().rev() {
5298            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5299                if var.kind != js_compile::VarKind::With {
5300                    continue;
5301                }
5302                // A captured binding lives in its cell and not in the slot list, so the
5303                // cell is consulted first — a closure created inside the block is exactly
5304                // what makes the object captured. Before the store runs the slot still
5305                // holds `undefined`, and a `with` object is always boxed, so a non-object
5306                // entry is simply not in scope yet.
5307                let value = frame
5308                    .code
5309                    .loc_cell
5310                    .get(index)
5311                    .copied()
5312                    .filter(|cell| *cell >= 0)
5313                    .and_then(|cell| frame.cells.get(cell as usize))
5314                    .map(|cell| cell.get())
5315                    .or_else(|| frame.locals.get(index).cloned());
5316                if let Some(Value::Object(object)) = value {
5317                    objects.push(object);
5318                }
5319            }
5320        }
5321        objects
5322    }
5323
5324    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5325        for object in self.eval_with.clone().unwrap_or_default() {
5326            let key = self.string(name.to_string());
5327            if self.has_property(&key, &Value::Object(object.clone()))? {
5328                return Ok(Some(self.read_field(&Value::Object(object), name)?));
5329            }
5330        }
5331        Ok(None)
5332    }
5333
5334    /// Whether every scope between here and the global object is an ordinary one.
5335    ///
5336    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5337    /// bytecode resolved; when any is live the general path has to run in full order. When
5338    /// none is — every ordinary program — a global read is a property read and nothing
5339    /// else, and that is worth caching.
5340    fn scopes_are_plain(&self) -> bool {
5341        self.eval_caller.is_none()
5342            && self.eval_with.is_none()
5343            && self.eval_arguments.is_none()
5344            && self.eval_bindings.is_empty()
5345            && self.eval_scope.is_none()
5346            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5347            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5348            // its `ClosureEnv`, so the test has to be the same one the general path makes.
5349            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5350            // upstream corpus caught and no unit test did.
5351            && !self.has_visible_local_vars()
5352            && self.frame().env.eval_scope.is_none()
5353    }
5354
5355    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5356        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5357        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5358        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5359        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5360        // borrow outlive the `&mut self` the lookup needs.
5361        //
5362        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5363        // forwarded through a nested function has its flags cleared, so the flag cannot
5364        // be believed.
5365        let code = self.frame().code.clone();
5366        let name = code
5367            .code
5368            .closure_vars
5369            .get(slot)
5370            .map(|c| c.name.as_str())
5371            .unwrap_or_default();
5372        let lexical = self.realm.globals.contains_key(name);
5373        // The common case, first: an ordinary global `var`, with a cache in front of the
5374        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5375        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5376        // cache hit and return without touching any of it.
5377        if !lexical && self.scopes_are_plain() {
5378            return self.get_plain_global(name, slot);
5379        }
5380        if name == "arguments"
5381            && let Some(arguments) = &self.eval_arguments
5382        {
5383            return Ok(arguments.clone());
5384        }
5385        // A `with` block around the *call site* is part of the scope an `eval` sees, so
5386        // the objects live when the eval started are consulted before anything else. The
5387        // snapshot is taken at entry rather than scanning the frames on every read: a
5388        // block that has already finished still leaves its object in the slot, and a
5389        // bytecode read outside the block must not see it.
5390        if let Some(value) = self.with_lookup(name)? {
5391            return Ok(value);
5392        }
5393        // A variable a direct `eval` declared shadows everything the compiler resolved,
5394        // including an enclosing function's binding: the eval put it in the caller's own
5395        // variable environment, which is nearer than any captured scope.
5396        if let Some((local_vars, phase)) = self.visible_local_vars()
5397            && let Some(cell) = local_vars.get(name, phase)
5398        {
5399            return Ok(cell.get());
5400        }
5401        // The frame that called `eval` is the innermost scope the eval'd code sees, so
5402        // its local `a` wins over a global `a`.
5403        if let Some(value) = self.eval_binding_value(name) {
5404            return Ok(value);
5405        }
5406        // A closure created by an `eval` resolves its free names against the bindings
5407        // that eval saw, even after the eval (and its frames) are gone.
5408        if let Some(cell) = self
5409            .frame()
5410            .env
5411            .eval_scope
5412            .as_ref()
5413            .and_then(|scope| scope.get(name))
5414        {
5415            let value = cell.get();
5416            if matches!(value, Value::Uninitialized) {
5417                return Err(self.throw_reference(name));
5418            }
5419            return Ok(value);
5420        }
5421        // A binding declared by the strict `eval` currently running shadows anything
5422        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5423        if let Some(scope) = &self.eval_scope
5424            && let Some(value) = scope.get(name)
5425        {
5426            return Ok(value.clone());
5427        }
5428        if lexical {
5429            // A lexical global is a binding in a side table, so the dead zone is
5430            // visible and it is nowhere on the global object.
5431            if let Some(cell) = self.realm.globals.get(name) {
5432                let value = cell.get();
5433                if matches!(value, Value::Uninitialized) {
5434                    return Err(self.throw_reference(name));
5435                }
5436                return Ok(value);
5437            }
5438            return Err(self.throw_reference(name));
5439        }
5440        // A `var` global is an ordinary property, so the prototype chain and the
5441        // global object's own builtins are all reachable through it.
5442        match self.get_property(&self.realm.global.clone(), name)? {
5443            Some(value) => Ok(value),
5444            None => Err(self.throw_reference(name)),
5445        }
5446    }
5447
5448    /// Read a plain global `var`: a cached own data property, or the full lookup.
5449    ///
5450    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5451    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5452    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5453        let object = self.realm.global.clone();
5454        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5455        if let Some(cached) = &self.global_cache[site]
5456            && object.upgrades_to(&cached.object)
5457            && let Some(value) = object.data_property_at(cached.index, name)
5458        {
5459            return Ok(value);
5460        }
5461        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5462        // chain exactly as before, then remember the answer if it is worth remembering.
5463        let Some(value) = self.get_property(&object, name)? else {
5464            return Err(self.throw_reference(name));
5465        };
5466        if let Some(index) = object.own_data_index(name) {
5467            self.global_cache[site] = Some(GlobalCache {
5468                object: object.downgrade(),
5469                index,
5470            });
5471        }
5472        Ok(value)
5473    }
5474
5475    /// Store to a global binding.
5476    ///
5477    /// Returns a signal when the store is refused: a `const` global may only be
5478    /// written by its initialiser, and a non-configurable `var` global may not be
5479    /// deleted but is always writable.
5480    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5481        let (name, lexical, is_const) = self.global_binding(slot);
5482
5483        // An assignment inside a `with` writes through to the object that supplies the
5484        // name, which for an `eval` means consulting the same chain `get_global` does.
5485        if let Some(owner) = self.with_owner(&name) {
5486            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5487            return Ok(());
5488        }
5489        // A variable the running eval *declared* takes the write before any caller
5490        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5491        // environment even when an enclosing function has a `var c` of its own.
5492        if self.eval_caller.flatten().is_some()
5493            && let Some((local_vars, phase)) = self.visible_local_vars()
5494            && local_vars.contains(&name)
5495            && let Some(cell) = local_vars.get(&name, phase)
5496        {
5497            cell.set(value);
5498            return Ok(());
5499        }
5500        // A binding of the frame that called `eval` takes the write, which is what
5501        // makes `f("a = 3")` change the caller's `a`.
5502        if self.set_eval_binding(&name, &value)? {
5503            return Ok(());
5504        }
5505        // A closure that outlived its `eval` writes through to the same cell it reads.
5506        if let Some(cell) = self
5507            .frame()
5508            .env
5509            .eval_scope
5510            .as_ref()
5511            .and_then(|scope| scope.get(&name))
5512            .cloned()
5513        {
5514            cell.set(value);
5515            return Ok(());
5516        }
5517        // Inside a strict `eval`, a name it declared itself is stored there. An
5518        // *assignment* to a name nobody declared is not a declaration, so it falls
5519        // through: strict mode raises `ReferenceError` for it, which is what
5520        // `eval("1 + (@not_def = 1)")` has to do.
5521        if let Some(scope) = self.eval_scope.as_mut()
5522            && scope.contains_key(&name)
5523        {
5524            scope.insert(name, value);
5525            return Ok(());
5526        }
5527        if lexical {
5528            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5529                if is_const && !matches!(cell.get(), Value::Uninitialized) {
5530                    return Err(self.read_only_global(&name));
5531                }
5532                cell.set(value);
5533                return Ok(());
5534            }
5535            // Writing an undeclared lexical global is a `ReferenceError` in strict
5536            // mode and a silent global creation otherwise; creating the cell here
5537            // keeps both paths from losing the value.
5538            let cell = self.new_cell(value);
5539            self.realm.globals.insert(name, cell);
5540            return Ok(());
5541        }
5542        // A variable a direct `eval` declared in this call shadows the global object, even
5543        // when the global already has a property of that name — `var c = "global"` at the
5544        // top level must not capture `eval("var c = 1")` inside a function.
5545        if let Some((local_vars, phase)) = self.visible_local_vars()
5546            && local_vars.contains(&name)
5547            && let Some(cell) = local_vars.get(&name, phase)
5548        {
5549            cell.set(value);
5550            return Ok(());
5551        }
5552        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5553        // remembered a global's slot index since M12b, but the *store* side never did: it
5554        // converted the name to a `PropertyKey` (two allocations) and then scanned the
5555        // global object's whole table — which holds every builtin — on every assignment to
5556        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5557        // full global lookup per iteration; measured with a counter, `s` as a global made
5558        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5559        //
5560        // Re-validated exactly like the read: same object, same index, still the name, and
5561        // — the one extra check a store needs — still writable. A global that is an
5562        // accessor, non-writable, or inherited fails here and falls through to the full
5563        // path below, which reports the failure the way it always did.
5564        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5565        let global = self.realm.global.clone();
5566        if let Some(cached) = &self.global_cache[site]
5567            && global.upgrades_to(&cached.object)
5568            && global.write_data_at(cached.index, &name, value.clone())
5569        {
5570            return Ok(());
5571        }
5572        match global.own_property(&name) {
5573            // A `var` global is writable, so the store goes straight through — but
5574            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5575            // store (a non-writable or accessor-without-setter global) is a silent
5576            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5577            // split every other assignment has.
5578            Some(_) => {
5579                let on_failure = if self.current_strict() {
5580                    DeleteFailure::Throw
5581                } else {
5582                    DeleteFailure::Ignore
5583                };
5584                let result = self.set_property_with(&global, &name, value, on_failure);
5585                // Teach the cache the slot for a plain writable own data property, which is
5586                // what a declared `var` is. Without this the fast path above could never
5587                // fire for a global that is only ever *written* — its entry would have to
5588                // be put there by a read of the same slot, and a write-only loop has none.
5589                if result.is_ok()
5590                    && let Some(index) = global.own_data_index(&name)
5591                {
5592                    self.global_cache[site] = Some(GlobalCache {
5593                        object: global.downgrade(),
5594                        index,
5595                    });
5596                }
5597                result
5598            }
5599            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5600            // declaration creates a *configurable* property, which is what makes it
5601            // deletable and is the one way a global differs from a declared `var`.
5602            // In strict mode the same store is a `ReferenceError` instead: that is the
5603            // whole point of strict mode, and creating the global silently meant
5604            // `"use strict"; x = 1` looked like it worked.
5605            None => {
5606                if self.current_strict() {
5607                    return Err(self.throw_reference(&name));
5608                }
5609                // A direct eval declares here rather than on the global object: its
5610                // `var`s belong to the caller's variable environment. `declare_eval_local`
5611                // also covers a plain assignment to a variable an earlier eval made.
5612                if let Some(cell) = self.declare_eval_local(&name) {
5613                    cell.set(value);
5614                    return Ok(());
5615                }
5616                global.define_data(&name, value);
5617                Ok(())
5618            }
5619        }
5620    }
5621
5622    /// The value of a binding of the frame that called `eval`, if there is one.
5623    fn eval_binding_value(&self, name: &str) -> Option<Value> {
5624        let binding = self
5625            .eval_bindings
5626            .iter()
5627            .find(|binding| binding.name == name)?;
5628        let owner = self.frames.get(binding.frame)?;
5629        let (slot, index) = (binding.slot, binding.index);
5630        Some(match slot {
5631            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5632                cell if cell >= 0 => owner
5633                    .cells
5634                    .get(cell as usize)
5635                    .map(|cell| cell.get())
5636                    .unwrap_or(Value::Undefined),
5637                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5638            },
5639            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5640                cell if cell >= 0 => owner
5641                    .cells
5642                    .get(cell as usize)
5643                    .map(|cell| cell.get())
5644                    .unwrap_or(Value::Undefined),
5645                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5646            },
5647        })
5648    }
5649
5650    /// Write to a binding of the frame that called `eval`.
5651    ///
5652    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5653    /// matched binding can still refuse the store, which is why this is fallible: a
5654    /// `const` is read-only everywhere, and a named function expression's own name is
5655    /// read-only in strict mode.
5656    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5657        let Some(binding) = self
5658            .eval_bindings
5659            .iter()
5660            .find(|binding| binding.name == name)
5661        else {
5662            return Ok(false);
5663        };
5664        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5665        let strict = self.current_strict();
5666        let Some(owner) = self.frames.get_mut(frame) else {
5667            return Ok(false);
5668        };
5669        match slot {
5670            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5671                cell if cell >= 0 => {
5672                    if let Some(cell) = owner.cells.get(cell as usize) {
5673                        cell.set(value.clone());
5674                    }
5675                }
5676                _ => {
5677                    if let Some(slot) = owner.args.get_mut(index) {
5678                        *slot = value.clone();
5679                    }
5680                }
5681            },
5682            EvalSlot::Local => {
5683                let declared = owner.code.code.vars.get(index);
5684                // A `const` is read-only even through `eval`. The realm records this for
5685                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5686                // the bytecode, so this is where it has to be enforced.
5687                if declared.is_some_and(|var| var.is_const) {
5688                    return Err(self.read_only_local(name));
5689                }
5690                // The name of a named function expression is read-only too, but only
5691                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5692                // such a name is ignored, the same as a direct store would be.
5693                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5694                    return if strict {
5695                        Err(self.read_only_local(name))
5696                    } else {
5697                        Ok(true)
5698                    };
5699                }
5700                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5701                    cell if cell >= 0 => {
5702                        if let Some(cell) = owner.cells.get(cell as usize) {
5703                            cell.set(value.clone());
5704                        }
5705                    }
5706                    _ => {
5707                        if let Some(slot) = owner.locals.get_mut(index) {
5708                            *slot = value.clone();
5709                        }
5710                    }
5711                }
5712            }
5713        }
5714        Ok(true)
5715    }
5716
5717    /// The `TypeError` an assignment to a read-only binding raises.
5718    fn read_only_local(&self, name: &str) -> Signal {
5719        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5720    }
5721
5722    /// Declare `name` as a variable of the frame that called the running `eval`.
5723    ///
5724    /// `None` when there is no direct eval in progress, or it was called from the top
5725    /// level — then the caller's variable environment *is* the global one and the
5726    /// existing path is right.
5727    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5728        let caller = self.eval_caller.flatten()?;
5729        // The bottom frame is the top-level script, whose variable environment *is* the
5730        // global one — so `eval("var x = 1")` at the top level still creates a global.
5731        if caller == 0 {
5732            return None;
5733        }
5734        // A name the eval's *own* variable environment already binds is not a new
5735        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5736        // `arguments`, and creating a second binding would leave the first — the one
5737        // closures read — untouched. A binding of an *outer* frame does not count: a
5738        // declaration shadows it rather than writing through.
5739        if self
5740            .eval_bindings
5741            .iter()
5742            .any(|binding| binding.name == name && binding.frame == caller)
5743        {
5744            return None;
5745        }
5746        let phase = if self.in_parameter_list_at(caller) {
5747            0
5748        } else {
5749            1
5750        };
5751        self.frame_local_vars(caller)?;
5752        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5753        if let Some(cell) = local_vars.get(name, 1) {
5754            return Some(cell);
5755        }
5756        let cell = self.new_cell(Value::Undefined);
5757        Some(local_vars.declare(name, phase, cell))
5758    }
5759
5760    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5761    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5762        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5763            return Some(local_vars.clone());
5764        }
5765        let local_vars = Gc::new(self.heap, LocalVars::new());
5766        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5767        Some(local_vars)
5768    }
5769
5770    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5771    /// property of the global object. Used to decide whether a store inside an
5772    /// `eval` writes through to the realm or declares a binding of its own.
5773    ///
5774    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5775    /// write to `Object.prototype.toString`, and must not shadow it either.
5776    fn global_knows(&mut self, name: &str) -> bool {
5777        if self.realm.globals.contains_key(name) {
5778            return true;
5779        }
5780        self.realm.global.own_property(name).is_some()
5781    }
5782
5783    /// Whether the code currently running is strict.
5784    ///
5785    /// Read off the frame's function, which is where the parser's answer ended up; a
5786    /// native function never runs strict-only checks, and there is no frame at all
5787    /// before the first script.
5788    pub fn current_strict(&self) -> bool {
5789        self.frames
5790            .last()
5791            .is_some_and(|frame| frame.code.code.strict)
5792    }
5793
5794    /// Initialise a declared global, which is what ends its dead zone.
5795    ///
5796    /// A `var` global becomes a property of the global object: writable, so a later
5797    /// assignment goes through, and non-configurable, so `delete` refuses.
5798    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5799        let (name, lexical, _) = self.global_binding(slot);
5800        // A `var` declared by the strict `eval` currently running belongs to the
5801        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5802        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5803        // initialised in place, which is what a re-declaration inside eval does.
5804        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5805            self.eval_scope
5806                .as_mut()
5807                .expect("checked above")
5808                .insert(name, value);
5809            return Ok(());
5810        }
5811        if let Some(scope) = self.eval_scope.as_mut()
5812            && scope.contains_key(&name)
5813        {
5814            scope.insert(name, value);
5815            return Ok(());
5816        }
5817        if lexical {
5818            // The cell exists (created at declaration time) holding the dead-zone
5819            // marker; storing the value is what makes the binding readable.
5820            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5821                cell.set(value);
5822                return Ok(());
5823            }
5824            let cell = self.new_cell(value);
5825            self.realm.globals.insert(name, cell);
5826            return Ok(());
5827        }
5828        let global = self.realm.global.clone();
5829        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5830        // to answer `false` and leave the binding in place. `with_attributes` ties
5831        // `configurable` to `writable`, so the property is built field by field.
5832        global.define(
5833            &name,
5834            Property {
5835                value: Some(value),
5836                writable: true,
5837                enumerable: true,
5838                configurable: false,
5839                ..Property::default()
5840            },
5841        );
5842        Ok(())
5843    }
5844
5845    /// The `TypeError` a store to a `const` global raises.
5846    fn read_only_global(&self, name: &str) -> Signal {
5847        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5848    }
5849
5850    // -- properties ---------------------------------------------------------
5851
5852    /// Read `object[key]`, following the prototype chain.
5853    ///
5854    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5855    /// lookup returns the owner rather than just the value.
5856    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5857        self.get_property_key(object, &PropertyKey::from(key))
5858    }
5859
5860    /// [`Interp::get_property`] with a key that may be a symbol.
5861    pub fn get_property_key(
5862        &mut self,
5863        object: &Gc<JsObject>,
5864        key: &PropertyKey,
5865    ) -> JsResult<Option<Value>> {
5866        self.get_property_key_for(object, None, key)
5867    }
5868
5869    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5870    ///
5871    /// The receiver matters when the property is found on a *prototype*: a getter has to
5872    /// see the object the read started from. For a primitive that is the primitive
5873    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5874    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5875    /// the owner.
5876    pub fn get_property_key_for(
5877        &mut self,
5878        object: &Gc<JsObject>,
5879        receiver: Option<&Value>,
5880        key: &PropertyKey,
5881    ) -> JsResult<Option<Value>> {
5882        // A proxy answers for itself, before any of the shortcuts below: `new
5883        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5884        // have.
5885        if object.proxy_state().is_some() {
5886            let receiver = receiver
5887                .cloned()
5888                .unwrap_or_else(|| Value::Object(object.clone()));
5889            return self.proxy_get(object, &receiver, key);
5890        }
5891        // A host class's `get_property` trap replaces the whole read, prototype walk
5892        // included — that is what makes a native accessor free rather than a JavaScript
5893        // getter call.
5894        if let Some(exotic) = object.exotic() {
5895            let receiver_value = receiver
5896                .cloned()
5897                .unwrap_or_else(|| Value::Object(object.clone()));
5898            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5899                return Ok(Some(value));
5900            }
5901            // With no `get_property` trap, a `get_own_property` trap still answers for the
5902            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5903            // and the hook lives exactly there. A key the trap reports as absent is still
5904            // looked for on the prototype, which is why the search resumes *above*.
5905            if let Some(property) = exotic.get_own_property(self, object, key)? {
5906                return match property {
5907                    Some(property) => self.read_property(property, object, receiver),
5908                    None => match lookup_key_above(object, key) {
5909                        Some((_, property)) => self.read_property(property, object, receiver),
5910                        None => Ok(None),
5911                    },
5912                };
5913            }
5914        }
5915        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5916        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5917        // The `[[Get]]` short-circuit therefore belongs to this one arm.
5918        //
5919        // Constructibility is exactly the split the reference makes: `function f(){}` and
5920        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5921        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5922        // function" — it *is* the predicate, which is why no extra marker is needed.
5923        if let Some(text) = key.as_str()
5924            && (text == "caller" || text == "arguments")
5925            && object.is_constructor()
5926            && object.is_callable()
5927            && !object.is_bound_function()
5928            // …and only when the body is **sloppy**. A strict body reaches the
5929            // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
5930            // whole `Function/15.3.5.4_2-*gs` family is written against
5931            // (`onlyStrict`, so every function in them is strict).
5932            && !object.function_is_strict()
5933            && object.own_property(text).is_none()
5934        {
5935            return Ok(Some(Value::Undefined));
5936        }
5937        // The element-vector and `length` shortcuts are string-only: an array index
5938        // has no symbol spelling.
5939        if let Some(text) = key.as_str() {
5940            if let Some(value) = self.own_element(object, text) {
5941                return Ok(Some(value));
5942            }
5943            // `length` is not stored as a property: an array's length is its element
5944            // count, and keeping one copy of it is what makes `push`/`pop` and
5945            // `a.length = n` agree.
5946            if let Some(length) = object.array_length()
5947                && text == "length"
5948            {
5949                // Not `Value::Int(length as i32)`: see [`length_value`].
5950                return Ok(Some(crate::object::length_value(length)));
5951            }
5952        }
5953        // A proxy or a hooked exotic object anywhere above `object` makes the static
5954        // table walk below wrong: a proxy's own table is *empty by design* (the properties
5955        // live on its target), so the walk skipped that link entirely and everything behind
5956        // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5957        // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5958        // -target-is-proxy.js` are the four.
5959        if Self::chain_needs_dispatch(object) {
5960            return self.walk_get(object, receiver, key);
5961        }
5962        match lookup_key(object, key) {
5963            Some((_, property)) => self.read_property(property, object, receiver),
5964            None => Ok(None),
5965        }
5966    }
5967
5968    /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5969    /// answer for itself.
5970    ///
5971    /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5972    /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5973    /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5974    /// an inherited getter the object the read started from.
5975    fn walk_get(
5976        &mut self,
5977        start: &Gc<JsObject>,
5978        receiver: Option<&Value>,
5979        key: &PropertyKey,
5980    ) -> JsResult<Option<Value>> {
5981        let receiver = receiver
5982            .cloned()
5983            .unwrap_or_else(|| Value::Object(start.clone()));
5984        let mut current = Some(start.clone());
5985        while let Some(holder) = current {
5986            // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5987            // has to ask it, not read its (empty) own-property table. `Object.create(new
5988            // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5989            // instead found nothing.
5990            if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5991                return Ok(Some(value));
5992            }
5993            // A host class's `get_property` trap replaces the whole read for that holder,
5994            // prototype walk included — the same rule `get_property_key_for` applies to the
5995            // first object.
5996            if let Some(exotic) = holder.exotic()
5997                && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5998            {
5999                return Ok(Some(value));
6000            }
6001            if let Some(property) = self.object_get_own_property(&holder, key)? {
6002                return self.read_property(property, &holder, Some(&receiver));
6003            }
6004            current = self.object_prototype_of(&holder)?;
6005        }
6006        Ok(None)
6007    }
6008
6009    /// Whether `object` or anything above it has properties that cannot be read out of a
6010    /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6011    ///
6012    /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6013    /// is the hot path for every property read; this is the check that decides whether it
6014    /// is safe to take it.
6015    fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6016        object
6017            .chain()
6018            .iter()
6019            .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6020    }
6021
6022    /// The value a property read answers.
6023    ///
6024    /// One place rather than three, because an accessor has to run with the *receiver* as
6025    /// `this` whether the descriptor came from the property table, an exotic
6026    /// `get_own_property` trap, or a prototype above one.
6027    fn read_property(
6028        &mut self,
6029        property: Property,
6030        object: &Gc<JsObject>,
6031        receiver: Option<&Value>,
6032    ) -> JsResult<Option<Value>> {
6033        if property.is_accessor() {
6034            match &property.getter {
6035                Some(getter) if !matches!(getter, Value::Undefined) => {
6036                    let receiver = receiver
6037                        .cloned()
6038                        .unwrap_or_else(|| Value::Object(object.clone()));
6039                    self.call_value(getter.clone(), receiver, Vec::new())
6040                        .map(Some)
6041                }
6042                // An accessor with no getter reads as `undefined`.
6043                _ => Ok(Some(Value::Undefined)),
6044            }
6045        } else {
6046            Ok(property.value)
6047        }
6048    }
6049
6050    /// `super.key` — start the search at `proto`, but report to `receiver`.
6051    ///
6052    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6053    /// found on the prototype of a class has to see the *instance* as `this`, and a
6054    /// plain property read off `proto` would lose that.
6055    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6056        let start = self.require_object(proto)?;
6057        let key = self.propkey(key)?;
6058        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6059        if matches!(proto, Value::Null) {
6060            return Ok(Value::Undefined);
6061        }
6062        match lookup_key(&start, &key) {
6063            Some((_, property)) if property.is_accessor() => match &property.getter {
6064                Some(getter) if !matches!(getter, Value::Undefined) => {
6065                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
6066                }
6067                _ => Ok(Value::Undefined),
6068            },
6069            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6070            None => Ok(Value::Undefined),
6071        }
6072    }
6073
6074    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6075    ///
6076    /// A setter found on the prototype runs with `receiver` as `this`; a data property
6077    /// is shadowed by a new own property on the receiver, the same rule an ordinary
6078    /// assignment follows.
6079    fn super_write(
6080        &mut self,
6081        receiver: &Value,
6082        proto: &Value,
6083        key: &Value,
6084        value: Value,
6085    ) -> JsResult<()> {
6086        let target = self.require_object(receiver)?;
6087        let key = self.propkey(key)?;
6088        if !matches!(proto, Value::Null)
6089            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6090        {
6091            if property.is_accessor() {
6092                if let Some(setter) = &property.setter
6093                    && !matches!(setter, Value::Undefined)
6094                {
6095                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6096                }
6097                return Ok(());
6098            }
6099            // A data property on the prototype is writable or not; reading `owner` at
6100            // all is only for the attribute check.
6101            if !property.writable {
6102                return Err(self.type_error(format!("'{key}' is read-only")));
6103            }
6104            let _ = owner;
6105        }
6106        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6107    }
6108
6109    /// The object a `super` operation needs, or the `TypeError` the spec raises.
6110    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6111        match value.as_object() {
6112            Some(object) => Ok(object.clone()),
6113            None => Err(Signal::Throw(
6114                self.make_error("TypeError", "value is not an object"),
6115            )),
6116        }
6117    }
6118
6119    /// Build the class object `define_class` produces.
6120    ///
6121    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6122    /// whose prototype property is a fresh object inheriting from the parent's
6123    /// prototype, and whose own prototype is the parent constructor — which is what makes
6124    /// a static method inherited too.
6125    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6126        let ctor = self.pop();
6127        let parent = self.pop();
6128        let Value::Object(function) = &ctor else {
6129            return Err(Signal::Throw(
6130                self.make_error("TypeError", "class constructor must be a function"),
6131            ));
6132        };
6133        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6134        // but gives the instances no prototype at all.
6135        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6136            match &parent {
6137                Value::Null => (Some(self.realm.function_proto.clone()), None),
6138                Value::Object(parent_class) => {
6139                    if !parent_class.is_callable() {
6140                        return Err(Signal::Throw(
6141                            self.make_error("TypeError", "parent class must be constructor"),
6142                        ));
6143                    }
6144                    let proto = self.get_property(parent_class, "prototype")?;
6145                    match proto {
6146                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6147                        Some(Value::Null) => (Some(parent_class.clone()), None),
6148                        _ => {
6149                            return Err(Signal::Throw(self.make_error(
6150                                "TypeError",
6151                                "parent prototype must be an object or null",
6152                            )));
6153                        }
6154                    }
6155                }
6156                _ => {
6157                    return Err(Signal::Throw(
6158                        self.make_error("TypeError", "parent class must be constructor"),
6159                    ));
6160                }
6161            }
6162        } else {
6163            (
6164                Some(self.realm.function_proto.clone()),
6165                Some(self.realm.object_proto.clone()),
6166            )
6167        };
6168        let proto = self.new_object(parent_proto);
6169        function.set_proto(parent_ctor);
6170        // A class is not callable without `new`, and its `prototype` is not writable —
6171        // both follow from being a class and are what `class A {}; A()` throws on.
6172        function.set_class_constructor(true);
6173        function.set_home_object(None);
6174        self.set_function_name(&ctor, name);
6175        self.define_class_properties(function, &ctor, &proto)?;
6176        Ok((ctor, proto))
6177    }
6178
6179    /// Give the constructor its `prototype` and `length`, and the prototype its
6180    /// `constructor` back-pointer.
6181    fn define_class_properties(
6182        &mut self,
6183        function: &Gc<JsObject>,
6184        ctor: &Value,
6185        proto: &Gc<JsObject>,
6186    ) -> JsResult<()> {
6187        proto.define(
6188            "constructor",
6189            Property::with_attributes(ctor.clone(), true, false),
6190        );
6191        function.define(
6192            "prototype",
6193            Property::prototype_of(Value::Object(proto.clone()), false),
6194        );
6195        if let Some((code, _)) = bytecode_of(function) {
6196            let length = code.code.defined_args;
6197            function.define(
6198                "length",
6199                Property::name_or_length(Value::Int(length as i32)),
6200            );
6201        }
6202        Ok(())
6203    }
6204
6205    /// The own array element `key` names, if this object has one.
6206    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6207        // A typed array's elements live in its buffer, not in a property list: reading one
6208        // goes through the view's element type so a bounds check and a detached buffer are
6209        // both handled there.
6210        //
6211        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6212        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6213        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6214        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6215        // consulted. Testing with `array_index` rejected all three, which let a throwing
6216        // getter installed on `TypedArray.prototype["-1"]` run.
6217        if object.typed_array_parts().is_some() {
6218            let property_key = PropertyKey::from(key);
6219            let numeric = canonical_numeric_index(&property_key)?;
6220            if typed_array_index_is_valid(object, numeric) {
6221                return object.typed_array_element(numeric as usize);
6222            }
6223            // Canonical, but not a valid index: `undefined`, and *final*.
6224            return Some(Value::Undefined);
6225        }
6226        let index = array_index(key)?;
6227        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6228        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6229        // search early, which is why `Array.prototype[1] = 9` could not be seen through
6230        // `[1,,3][1]`.
6231        match object.array_get(index as usize) {
6232            Some(Value::Hole) | None => None,
6233            other => other,
6234        }
6235    }
6236
6237    /// Store `object[key] = value`, honouring setters and inherited properties.
6238    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6239        self.set_property_with(object, key, value, DeleteFailure::Throw)
6240    }
6241
6242    /// Store a property, choosing what to do when the object refuses.
6243    ///
6244    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6245    /// mode, which is the one place assignment differs by mode. Native code (the array
6246    /// methods, `JSON`) always asks for the throw.
6247    pub fn set_property_with(
6248        &mut self,
6249        object: &Gc<JsObject>,
6250        key: &str,
6251        value: Value,
6252        on_failure: DeleteFailure,
6253    ) -> JsResult<()> {
6254        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6255    }
6256
6257    /// [`Interp::set_property_with`] with a key that may be a symbol.
6258    pub fn set_property_with_key(
6259        &mut self,
6260        object: &Gc<JsObject>,
6261        key: &PropertyKey,
6262        value: Value,
6263        on_failure: DeleteFailure,
6264    ) -> JsResult<()> {
6265        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6266    }
6267
6268    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6269    ///
6270    /// The receiver split lives one level up, in
6271    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6272    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6273    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6274    /// stores into `object` itself, which is why the element branch below converts `V`
6275    /// before asking whether the index is valid: `V` may put it back in bounds
6276    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6277    fn set_property_with_key_receiver_aware(
6278        &mut self,
6279        object: &Gc<JsObject>,
6280        key: &PropertyKey,
6281        value: Value,
6282        on_failure: DeleteFailure,
6283    ) -> JsResult<()> {
6284        // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6285        // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6286        // Nothing about the receiver or the value changes that, so the whole operation is
6287        // one answer.
6288        //
6289        // Not implementing it explicitly left the ordinary algorithm in charge, and that
6290        // says "true" for names the namespace does not own as soon as the value matches or
6291        // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6292        // assignment stopped throwing (`await-ns-set-strict`).
6293        if object.module_namespace_marker() {
6294            return match on_failure {
6295                DeleteFailure::Ignore => Ok(()),
6296                DeleteFailure::Throw => Err(self.type_error(format!(
6297                    "cannot assign to property '{key}' of a module namespace object"
6298                ))),
6299            };
6300        }
6301        // A proxy's `set` trap decides, and its `false` means the same thing an
6302        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6303        if object.proxy_state().is_some() {
6304            let receiver = Value::Object(object.clone());
6305            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6306                return match (accepted, on_failure) {
6307                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6308                    (false, DeleteFailure::Throw) => {
6309                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6310                    }
6311                };
6312            }
6313        }
6314        // A host class's `set_property` trap decides for itself. `Some(false)` is a
6315        // refusal and means exactly what a proxy's `false` means.
6316        if let Some(exotic) = object.exotic() {
6317            let receiver = Value::Object(object.clone());
6318            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6319                return match (accepted, on_failure) {
6320                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6321                    (false, DeleteFailure::Throw) => {
6322                        Err(self.type_error(format!("property '{key}' is read-only")))
6323                    }
6324                };
6325            }
6326        }
6327        // The element and `length` shortcuts only exist for string keys: an array
6328        // index has no symbol spelling, and a symbol named `length` is an ordinary
6329        // property.
6330        let text = key.as_str();
6331        // A typed array's elements are a window onto its buffer: the store has to go
6332        // through the view's element type so the value is wrapped (or clamped) and so an
6333        // out-of-range or detached write is a silent no-op, as the spec says.
6334        //
6335        // The key test is `CanonicalNumericIndexString`, like every other index operation
6336        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6337        // does not exist, so they do nothing and leave no own property behind
6338        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6339        // path, which created a property named `"-0"`.
6340        //
6341        // The conversion comes **first**, before the index is checked at all, and that
6342        // order is observable twice over:
6343        //
6344        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6345        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6346        //   then store the converted value;
6347        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6348        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6349        //   run and its exception to escape.
6350        //
6351        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6352        // validity check, not a validity check that skips the conversion. The store itself
6353        // is a no-op when the index is invalid by then, which is why no extra guard is
6354        // needed around `typed_array_set`.
6355        if let Some(element) = object.typed_array_element_type()
6356            && let Some(numeric) = canonical_numeric_index(key)
6357        {
6358            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6359            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6360            // in `Interp`, because it is script-observable and the storage borrow inside
6361            // `typed_array_set` must not be held across it.
6362            let stored = self.element_value(element, value)?;
6363            if typed_array_index_is_valid(object, numeric)
6364                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6365            {
6366                return Err(self.type_error(reason));
6367            }
6368            return Ok(());
6369        }
6370        if let Some(text) = text
6371            && let Some(index) = array_index(text)
6372            && object.is_array()
6373        {
6374            // An accessor defined on an index lives in the property table while the
6375            // element slot is a hole, so the store has to go through the property first.
6376            // Writing the vector directly skipped the setter entirely.
6377            if let Some(existing) = object.own_property_key(key) {
6378                if existing.is_accessor() {
6379                    return match existing.setter.clone() {
6380                        Some(setter) if !matches!(setter, Value::Undefined) => {
6381                            let receiver = Value::Object(object.clone());
6382                            self.call_value(setter, receiver, vec![value]).map(|_| ())
6383                        }
6384                        _ => match on_failure {
6385                            DeleteFailure::Throw => Err(self.type_error(format!(
6386                                "cannot set property '{text}', it has only a getter"
6387                            ))),
6388                            DeleteFailure::Ignore => Ok(()),
6389                        },
6390                    };
6391                }
6392                if !existing.writable {
6393                    return match on_failure {
6394                        DeleteFailure::Throw => {
6395                            Err(self.type_error(format!("'{text}' is read-only")))
6396                        }
6397                        DeleteFailure::Ignore => Ok(()),
6398                    };
6399                }
6400            }
6401            {
6402                // Growing the array needs a writable `length`.
6403                if (index as usize) >= object.array_length().unwrap_or(0)
6404                    && !object.length_writable()
6405                {
6406                    return match on_failure {
6407                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6408                        DeleteFailure::Ignore => Ok(()),
6409                    };
6410                }
6411                // Adding an index past the end makes the array longer, which a
6412                // non-extensible array refuses.
6413                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6414                    return match on_failure {
6415                        DeleteFailure::Throw => Err(self.type_error(format!(
6416                            "cannot add property '{key}', object is not extensible"
6417                        ))),
6418                        DeleteFailure::Ignore => Ok(()),
6419                    };
6420                }
6421                if object.element_is_locked(index) {
6422                    return match on_failure {
6423                        DeleteFailure::Throw => {
6424                            Err(self.type_error(format!("'{key}' is read-only")))
6425                        }
6426                        DeleteFailure::Ignore => Ok(()),
6427                    };
6428                }
6429                // The element vector is only half of `[[Set]]` for an index: the
6430                // prototype chain is consulted first, and a setter there answers instead
6431                // of the element store. This branch used to write the element directly, so
6432                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6433                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6434                // the reference calls the setter and the array keeps no own index.
6435                //
6436                // An *exotic* prototype has no entry to find, because its indices live
6437                // outside the property table — `Object.setPrototypeOf([], typedArray)`
6438                // then looked like "nothing on the chain" and the store created the
6439                // element, where the view's `[[Set]]` answers `true` and does nothing for
6440                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6441                // checks the array's `length` stays 0). So the dispatch comes first.
6442                if !object.has_own_key(key)
6443                    && let Some(proto) = object.proto()
6444                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6445                {
6446                    let receiver = Value::Object(object.clone());
6447                    let accepted =
6448                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6449                    return if accepted {
6450                        Ok(())
6451                    } else {
6452                        match on_failure {
6453                            DeleteFailure::Throw => {
6454                                Err(self.type_error(format!("'{key}' is read-only")))
6455                            }
6456                            DeleteFailure::Ignore => Ok(()),
6457                        }
6458                    };
6459                }
6460                if let Some((owner, property)) = lookup_key(object, key)
6461                    && !owner.ptr_eq(object)
6462                {
6463                    match &property {
6464                        property if property.is_accessor() => {
6465                            match &property.setter {
6466                                Some(setter) if !matches!(setter, Value::Undefined) => {
6467                                    let receiver = Value::Object(object.clone());
6468                                    self.call_value(setter.clone(), receiver, vec![value])?;
6469                                }
6470                                _ => {
6471                                    return match on_failure {
6472                                        DeleteFailure::Throw => Err(self.type_error(format!(
6473                                            "cannot set property '{text}', it has only a getter"
6474                                        ))),
6475                                        DeleteFailure::Ignore => Ok(()),
6476                                    };
6477                                }
6478                            }
6479                            return Ok(());
6480                        }
6481                        property if !property.writable => {
6482                            return match on_failure {
6483                                DeleteFailure::Throw => {
6484                                    Err(self.type_error(format!("'{text}' is read-only")))
6485                                }
6486                                DeleteFailure::Ignore => Ok(()),
6487                            };
6488                        }
6489                        _ => {}
6490                    }
6491                }
6492                if object.array_set(self.heap, index as usize, value.clone()) {
6493                    return Ok(());
6494                }
6495                // Past the dense limit the slot is too far out to be worth one `Value`
6496                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6497                // constant time by keeping the index as an ordinary property. The store
6498                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6499                // to a legal program.
6500                object.define_key(key, Property::with_attributes(value, true, true));
6501                // Extend, never shorten: the index may be *inside* the current length (a
6502                // huge `length` with a sparse store), and shortening would delete the
6503                // sparse properties above it — including the one just stored.
6504                if index as usize + 1 > object.array_length().unwrap_or(0) {
6505                    object.array_set_length(self.heap, index as usize + 1);
6506                }
6507                return Ok(());
6508            }
6509        }
6510        if text == Some("length") && object.is_array() {
6511            // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6512            // test. A `valueOf` that locks `length` on its second call therefore turns the
6513            // store into a refused write rather than a silent success
6514            // (`length/define-own-prop-length-coercion-order-set`).
6515            let rounded = self.coerce_array_length_twice(&value)?;
6516            if !object.length_writable() {
6517                return match on_failure {
6518                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6519                    DeleteFailure::Ignore => Ok(()),
6520                };
6521            }
6522            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6523            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6524            // answered `NaN`, which left the assignment silently ignored
6525            // (`S15.4.5.2_A3_T2`).
6526            let _ = rounded;
6527            let length = self.to_js_number(&value)?;
6528            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6529            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6530            // `RangeError`s; the old code only tested "finite and non-negative" and then
6531            // truncated, so `[].length = 4294967297` quietly produced a length no array can
6532            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6533            let valid = length.is_finite()
6534                && length >= 0.0
6535                && length.fract() == 0.0
6536                && length <= u32::MAX as f64;
6537            if !valid {
6538                return Err(self.range_error("invalid array length"));
6539            }
6540            {
6541                let length = length as usize;
6542                // `a.length = n` with `n` below a non-configurable element cannot
6543                // drop that element, so the whole assignment fails. The spec makes
6544                // this a `TypeError` rather than a silent no-op, in any mode.
6545                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6546                    // Sloppy mode stops the truncation at the blocking element
6547                    // instead of failing; strict mode raises.
6548                    // Both modes stop at the blocking element; they differ in
6549                    // whether that is reported. The reference truncates *then*
6550                    // throws, so the array is left in the shortened state.
6551                    object.array_truncate(self.heap, blocked + 1);
6552                    return match on_failure {
6553                        DeleteFailure::Throw => {
6554                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
6555                        }
6556                        DeleteFailure::Ignore => Ok(()),
6557                    };
6558                }
6559                object.array_set_length(self.heap, length);
6560                return Ok(());
6561            }
6562        }
6563        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6564        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6565        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6566        //
6567        // The prototype step is a dispatch, not a lookup. Walking the chain here and
6568        // applying whatever came back is the same thing for an ordinary prototype and
6569        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6570        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6571        // answers "not mine, the receiver is not me" without touching the buffer. This
6572        // code used to find nothing owned by `o`, find no property on the view either,
6573        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6574        // object and never converted (`key-is-valid-index-prototype-chain-set`,
6575        // `key-is-canonical-invalid-index-prototype-chain-set`).
6576        //
6577        // The read-only and accessor rules of step 1 are what make
6578        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6579        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6580        let own = match self.lookup_for_write(object, key)? {
6581            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6582            _ => None,
6583        };
6584        if let Some(property) = own {
6585            if property.is_accessor() {
6586                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6587                    Some(setter) => {
6588                        let receiver = Value::Object(object.clone());
6589                        self.call_value(setter, receiver, vec![value])?;
6590                        Ok(())
6591                    }
6592                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6593                    // Sloppy code swallows that refusal, strict code raises — the same
6594                    // rule the read-only *data* property below follows, and skipping it
6595                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6596                    // return silently. The reference answers `TypeError: 'x' is
6597                    // read-only`.
6598                    None => match on_failure {
6599                        DeleteFailure::Throw => {
6600                            Err(self.type_error(format!("'{key}' is read-only")))
6601                        }
6602                        DeleteFailure::Ignore => Ok(()),
6603                    },
6604                };
6605            }
6606            // An own non-writable data property stops here: nothing may change it.
6607            if !property.writable {
6608                return match on_failure {
6609                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6610                    DeleteFailure::Ignore => Ok(()),
6611                };
6612            }
6613            // An existing writable own property keeps its attributes: only the value
6614            // moves. Redefining instead would reset them, which is how a
6615            // non-configurable global `var` used to become deletable.
6616            if object.write_value_key(key, value.clone()) {
6617                return Ok(());
6618            }
6619        }
6620        // Step 2: hand the store to the prototype, with `object` as the receiver.
6621        if let Some(proto) = object.proto() {
6622            let receiver = Value::Object(object.clone());
6623            let accepted =
6624                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6625            return if accepted {
6626                Ok(())
6627            } else {
6628                match on_failure {
6629                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6630                    DeleteFailure::Ignore => Ok(()),
6631                }
6632            };
6633        }
6634        // Step 3: create one, and a non-extensible object cannot.
6635        if !object.is_extensible() {
6636            return match on_failure {
6637                DeleteFailure::Throw => Err(self.type_error(format!(
6638                    "cannot add property {key}, object is not extensible"
6639                ))),
6640                DeleteFailure::Ignore => Ok(()),
6641            };
6642        }
6643        object.define_data_key(key, value);
6644        Ok(())
6645    }
6646
6647    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6648    ///
6649    /// The distinction the fast path above does not need: it is called with the store's
6650    /// receiver already being the object it writes to. Here `object` is the one whose
6651    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6652    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6653    /// and not a write to `object`.
6654    ///
6655    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6656    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6657    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6658    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6659    /// descriptor on the prototype refuses instead, which is the same rule that keeps
6660    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6661    ///
6662    /// Answers `false` where the spec says `false`; the caller turns that into the
6663    /// strict-mode `TypeError` or the sloppy-mode silence.
6664    fn ordinary_set_with_receiver(
6665        &mut self,
6666        object: &Gc<JsObject>,
6667        receiver: &Value,
6668        key: &PropertyKey,
6669        value: Value,
6670        on_failure: DeleteFailure,
6671    ) -> JsResult<bool> {
6672        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6673        if object.proxy_state().is_some() {
6674            return Ok(self
6675                .proxy_set(object, key, value, receiver)?
6676                .unwrap_or(true));
6677        }
6678        // A host class decides for itself, with the receiver the caller named.
6679        if let Some(exotic) = object.exotic()
6680            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6681        {
6682            return Ok(accepted);
6683        }
6684        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6685        // rather than the receiver, but the receiver may still *be* the view:
6686        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6687        // itself as receiver, and then the first half applies — convert `V` once, store
6688        // if the index is valid, answer `true` either way. The conversion is the observable
6689        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6690        //
6691        // Only the second half, a view that is *not* the receiver, skips the conversion
6692        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6693        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6694        // below with the value still unconverted.
6695        if object.typed_array_element_type().is_some()
6696            && let Some(numeric) = canonical_numeric_index(key)
6697        {
6698            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6699                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6700                return Ok(true);
6701            }
6702            if !typed_array_index_is_valid(object, numeric) {
6703                return Ok(true);
6704            }
6705        }
6706        let own = self.object_get_own_property(object, key)?;
6707        if let Some(own) = own {
6708            if own.is_accessor() {
6709                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6710                    Some(setter) => {
6711                        self.call_value(setter, receiver.clone(), vec![value])?;
6712                        Ok(true)
6713                    }
6714                    None => Ok(false),
6715                };
6716            }
6717            // A non-writable data descriptor refuses, own or inherited. Either way the
6718            // receiver must not gain a shadowing property.
6719            if !own.writable {
6720                return Ok(false);
6721            }
6722            // Step 1.d: the *receiver's* own descriptor decides whether it can be
6723            // created or written, and it is created as an ordinary data property.
6724            let Some(receiver_object) = receiver.as_object().cloned() else {
6725                return Ok(false);
6726            };
6727            return match self.object_get_own_property(&receiver_object, key)? {
6728                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6729                Some(existing) => self.object_define_own_property(
6730                    &receiver_object,
6731                    key,
6732                    Property {
6733                        value: Some(value),
6734                        ..existing
6735                    },
6736                ),
6737                None => {
6738                    self.object_define_own_property(&receiver_object, key, Property::data(value))
6739                }
6740            };
6741        }
6742        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6743        if let Some(proto) = object.proto() {
6744            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6745        }
6746        // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6747        // *default* data descriptor here, so control falls into step 2 exactly as if the
6748        // target had owned a writable property — which means the **receiver's** own
6749        // descriptor is asked for before the write. Skipping that question went straight to
6750        // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6751        // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6752        // exactly those calls).
6753        let Some(receiver_object) = receiver.as_object().cloned() else {
6754            return Ok(false);
6755        };
6756        match self.object_get_own_property(&receiver_object, key)? {
6757            Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6758            Some(existing) => self.object_define_own_property(
6759                &receiver_object,
6760                key,
6761                Property {
6762                    value: Some(value),
6763                    ..existing
6764                },
6765            ),
6766            None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6767        }
6768    }
6769
6770    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6771    ///
6772    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6773    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6774    /// a virtual accessor gets its setter run without implementing `set_property` at all.
6775    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6776    /// the prototype, so the walk resumes above the object.
6777    fn lookup_for_write(
6778        &mut self,
6779        object: &Gc<JsObject>,
6780        key: &PropertyKey,
6781    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6782        let Some(exotic) = object.exotic() else {
6783            return Ok(lookup_key(object, key));
6784        };
6785        Ok(match exotic.get_own_property(self, object, key)? {
6786            Some(Some(property)) => Some((object.clone(), property)),
6787            Some(None) => lookup_key_above(object, key),
6788            None => lookup_key(object, key),
6789        })
6790    }
6791
6792    /// Delete `object[key]`.
6793    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6794        self.delete_property_key(object, &PropertyKey::from(key))
6795    }
6796
6797    /// [`Interp::delete_property`] with a key that may be a symbol.
6798    pub fn delete_property_key(
6799        &mut self,
6800        object: &Gc<JsObject>,
6801        key: &PropertyKey,
6802    ) -> JsResult<bool> {
6803        // A proxy decides for itself, and may even throw; the invariant checks live in
6804        // `proxy_delete`.
6805        if let Some(answer) = self.proxy_delete(object, key)? {
6806            return Ok(answer);
6807        }
6808        // A host class's `delete_property` trap decides; `false` is a refusal, which the
6809        // caller reports as a failed delete.
6810        if let Some(exotic) = object.exotic()
6811            && let Some(answer) = exotic.delete_property(self, object, key)?
6812        {
6813            return Ok(answer);
6814        }
6815        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6816        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6817        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6818        // one answers `false` because the elements are non-configurable. The prototype
6819        // chain is not consulted either, which is what makes a throwing getter on
6820        // `TypedArray.prototype["-1"]` stay unrun.
6821        if object.typed_array_parts().is_some()
6822            && object.proxy_state().is_none()
6823            && let Some(numeric) = canonical_numeric_index(key)
6824        {
6825            return Ok(!typed_array_index_is_valid(object, numeric));
6826        }
6827        let mapped_index = key.as_str().and_then(array_index);
6828        if let Some(index) = mapped_index
6829            && let Some(length) = object.array_length()
6830            && (index as usize) < length
6831        {
6832            // An accessor defined on an index lives in the property table rather than the
6833            // element vector, so both have to be cleared: `delete` after
6834            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6835            object.delete_key(key);
6836            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6837            // index stops answering `in`.
6838            if object.element_is_undeletable(index) {
6839                return Ok(false);
6840            }
6841            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6842            // so a later `defineProperty(arguments, "0", {value})` writes to the object
6843            // and no longer through to the parameter. A refused delete leaves the
6844            // mapping alone.
6845            object.drop_mapped_argument(index as usize);
6846            object.array_set(self.heap, index as usize, Value::Hole);
6847            return Ok(true);
6848        }
6849        // An array's `length` is a non-configurable own property that lives outside the
6850        // property table, so `delete_key` finds nothing and reports success — `Reflect
6851        // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6852        // §10.4.4.1 step 3 refuses it.
6853        if key.as_str() == Some("length") && object.array_length().is_some() {
6854            return Ok(false);
6855        }
6856        // The same for an object that is not an array: only a delete that actually
6857        // removed the property ends the alias.
6858        let deleted = object.delete_key(key);
6859        if deleted && let Some(index) = mapped_index {
6860            object.drop_mapped_argument(index as usize);
6861        }
6862        Ok(deleted)
6863    }
6864
6865    // -- proxy traps --------------------------------------------------------
6866    //
6867    // A proxy's internal methods all look the same: ask the handler for the trap, call it
6868    // with the target and the operation's own arguments, then check the answer against
6869    // the target. The checks are not decoration — they are what stops a proxy from
6870    // reporting a `non-configurable` property as missing, which would let a frozen object
6871    // be rewritten by standing in front of it.
6872
6873    /// The target and handler of `object`, or `None` when it is not a proxy.
6874    ///
6875    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6876    /// one has to fail: the slots the traps would have been read from are gone.
6877    pub(crate) fn proxy_parts(
6878        &mut self,
6879        object: &Gc<JsObject>,
6880    ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6881        let Some(state) = object.proxy_state() else {
6882            return Ok(None);
6883        };
6884        let state = state.borrow();
6885        match (&state.target, &state.handler) {
6886            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6887            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6888        }
6889    }
6890
6891    /// Call `handler[name]`, or answer `None` when the trap is absent.
6892    ///
6893    /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6894    /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6895    /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6896    /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6897    /// one per trap plus the `target-is-proxy` variants.
6898    ///
6899    /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6900    /// this cannot simply be "any non-callable means no trap".
6901    fn proxy_trap(
6902        &mut self,
6903        handler: &Value,
6904        name: &str,
6905        args: Vec<Value>,
6906    ) -> JsResult<Option<Value>> {
6907        let Value::Object(table) = handler else {
6908            return Err(self.type_error("proxy handler is not an object"));
6909        };
6910        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6911        match trap {
6912            Value::Undefined | Value::Null => Ok(None),
6913            Value::Object(function) if function.is_callable() => {
6914                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6915                Ok(Some(answer))
6916            }
6917            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6918        }
6919    }
6920
6921    /// Whether the target's own property `key` is one it refuses to lose.
6922    ///
6923    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6924    /// its value behind the target's back.
6925    ///
6926    /// A **method**, not a free function, because §10.5.1's invariants say
6927    /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6928    /// property table directly finds nothing (a proxy's table is empty by design), so every
6929    /// invariant check silently passed for a proxy target. That is what
6930    /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6931    /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6932    /// where an array's elements and its `length` — both fixed, both outside the table —
6933    /// are covered.
6934    fn fixed_property(
6935        &mut self,
6936        target: &Gc<JsObject>,
6937        key: &PropertyKey,
6938    ) -> JsResult<Option<Property>> {
6939        Ok(self
6940            .object_get_own_property(target, key)?
6941            .filter(|property| !property.configurable))
6942    }
6943
6944    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6945    fn proxy_get(
6946        &mut self,
6947        object: &Gc<JsObject>,
6948        receiver: &Value,
6949        key: &PropertyKey,
6950    ) -> JsResult<Option<Value>> {
6951        let Some((target, handler)) = self.proxy_parts(object)? else {
6952            return Ok(None);
6953        };
6954        let key_value = self.key_value(key);
6955        let Some(result) = self.proxy_trap(
6956            &handler,
6957            "get",
6958            vec![Value::Object(target.clone()), key_value, receiver.clone()],
6959        )?
6960        else {
6961            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6962            // inherited getter still sees the proxy.
6963            return Ok(Some(
6964                self.get_property_key_for(&target, Some(receiver), key)?
6965                    .unwrap_or(Value::Undefined),
6966            ));
6967        };
6968        if let Some(fixed) = self.fixed_property(&target, key)? {
6969            if fixed.is_accessor() {
6970                // A fixed accessor with no getter must read as `undefined`.
6971                let has_getter = fixed
6972                    .getter
6973                    .as_ref()
6974                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
6975                if !has_getter && !matches!(result, Value::Undefined) {
6976                    return Err(self.type_error(format!(
6977                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
6978                    )));
6979                }
6980            } else if !fixed.writable {
6981                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6982                if !fixed_value.same_value(&result) {
6983                    return Err(self.type_error(format!(
6984                        "proxy 'get' disagrees with the non-configurable property '{key}'"
6985                    )));
6986                }
6987            }
6988        }
6989        Ok(Some(result))
6990    }
6991
6992    /// `[[Set]]` on a proxy.
6993    ///
6994    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6995    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6996    /// read-only store has.
6997    fn proxy_set(
6998        &mut self,
6999        object: &Gc<JsObject>,
7000        key: &PropertyKey,
7001        value: Value,
7002        receiver: &Value,
7003    ) -> JsResult<Option<bool>> {
7004        let Some((target, handler)) = self.proxy_parts(object)? else {
7005            return Ok(None);
7006        };
7007        let key_value = self.key_value(key);
7008        let Some(result) = self.proxy_trap(
7009            &handler,
7010            "set",
7011            vec![
7012                Value::Object(target.clone()),
7013                key_value,
7014                value.clone(),
7015                receiver.clone(),
7016            ],
7017        )?
7018        else {
7019            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7020            // given — not the target. `OrdinarySet` step 3 is
7021            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7022            // object whose prototype is a typed array has to reach the proxy's own
7023            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7024            // calls and expects exactly one. Storing on the target instead put the value
7025            // in the target and never consulted the trap.
7026            let accepted = self.ordinary_set_with_receiver(
7027                &target,
7028                receiver,
7029                key,
7030                value,
7031                DeleteFailure::Ignore,
7032            )?;
7033            return Ok(Some(accepted));
7034        };
7035        if !result.to_boolean() {
7036            return Ok(Some(false));
7037        }
7038        if let Some(fixed) = self.fixed_property(&target, key)? {
7039            if fixed.is_accessor() {
7040                let has_setter = fixed
7041                    .setter
7042                    .as_ref()
7043                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
7044                if !has_setter {
7045                    return Err(self.type_error(format!(
7046                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7047                    )));
7048                }
7049            } else if !fixed.writable {
7050                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7051                if !fixed_value.same_value(&value) {
7052                    return Err(self.type_error(format!(
7053                        "proxy 'set' changed the non-configurable property '{key}'"
7054                    )));
7055                }
7056            }
7057        }
7058        // A new property cannot appear on a target that refuses new properties.
7059        if self.object_get_own_property(&target, key)?.is_none()
7060            && !self.object_is_extensible(&target)?
7061        {
7062            return Err(self.type_error(format!(
7063                "proxy 'set' added '{key}' to a non-extensible target"
7064            )));
7065        }
7066        Ok(Some(true))
7067    }
7068
7069    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7070    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7071        let Some((target, handler)) = self.proxy_parts(object)? else {
7072            return Ok(None);
7073        };
7074        let key_value = self.key_value(key);
7075        let Some(result) = self.proxy_trap(
7076            &handler,
7077            "has",
7078            vec![Value::Object(target.clone()), key_value],
7079        )?
7080        else {
7081            return Ok(Some(self.has_own_or_inherited(&target, key)?));
7082        };
7083        if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7084            return Err(self.type_error(format!(
7085                "proxy 'has' denied the non-configurable property '{key}'"
7086            )));
7087        }
7088        // A non-extensible target cannot grow, so every own property it *has* is fixed.
7089        if !result.to_boolean()
7090            && !self.object_is_extensible(&target)?
7091            && self.object_get_own_property(&target, key)?.is_some()
7092        {
7093            return Err(self.type_error(format!(
7094                "proxy 'has' denied the own property '{key}' of a non-extensible target"
7095            )));
7096        }
7097        Ok(Some(result.to_boolean()))
7098    }
7099
7100    /// `[[Delete]]` on a proxy.
7101    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7102        let Some((target, handler)) = self.proxy_parts(object)? else {
7103            return Ok(None);
7104        };
7105        let key_value = self.key_value(key);
7106        let Some(result) = self.proxy_trap(
7107            &handler,
7108            "deleteProperty",
7109            vec![Value::Object(target.clone()), key_value],
7110        )?
7111        else {
7112            return Ok(Some(self.delete_property_key(&target, key)?));
7113        };
7114        if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7115            return Err(self.type_error(format!(
7116                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7117            )));
7118        }
7119        if result.to_boolean()
7120            && !self.object_is_extensible(&target)?
7121            && self.object_get_own_property(&target, key)?.is_some()
7122        {
7123            return Err(self.type_error(format!(
7124                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7125            )));
7126        }
7127        Ok(Some(result.to_boolean()))
7128    }
7129
7130    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7131    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7132        let Some((target, handler)) = self.proxy_parts(object)? else {
7133            return Ok(None);
7134        };
7135        let Some(result) =
7136            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7137        else {
7138            // No trap: the target's own keys, already in the order an object reports.
7139            return Ok(Some(self.object_own_property_keys(&target)?));
7140        };
7141        // `CreateListFromArrayLike` with the string-or-symbol restriction.
7142        let list = self.list_from_array_like(&result, true)?;
7143        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7144        for value in list {
7145            let key = self.propkey(&value)?;
7146            if keys.contains(&key) {
7147                return Err(self.type_error(format!(
7148                    "proxy 'ownKeys' returned the duplicate key '{key}'"
7149                )));
7150            }
7151            keys.push(key);
7152        }
7153        // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7154        // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7155        // table is empty, which made every check below vacuous.
7156        let target_keys = self.object_own_property_keys(&target)?;
7157        let extensible = self.object_is_extensible(&target)?;
7158        for key in &target_keys {
7159            if keys.contains(key) {
7160                continue;
7161            }
7162            if self.fixed_property(&target, key)?.is_some() {
7163                return Err(self.type_error(format!(
7164                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7165                )));
7166            }
7167            if !extensible {
7168                return Err(self.type_error(format!(
7169                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7170                )));
7171            }
7172        }
7173        if !extensible {
7174            // §10.5.11 step 12: the lists must match one for one, in any order.
7175            if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7176            {
7177                return Err(
7178                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7179                );
7180            }
7181        }
7182        Ok(Some(keys))
7183    }
7184
7185    /// `[[GetOwnProperty]]` on a proxy.
7186    fn proxy_get_own_property(
7187        &mut self,
7188        object: &Gc<JsObject>,
7189        key: &PropertyKey,
7190    ) -> JsResult<Option<Option<Property>>> {
7191        let Some((target, handler)) = self.proxy_parts(object)? else {
7192            return Ok(None);
7193        };
7194        let key_value = self.key_value(key);
7195        let Some(result) = self.proxy_trap(
7196            &handler,
7197            "getOwnPropertyDescriptor",
7198            vec![Value::Object(target.clone()), key_value],
7199        )?
7200        else {
7201            // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7202            // property table. Two things ride on that choice: a target that is itself a
7203            // proxy has to re-dispatch (its own table is empty, so reading it reported
7204            // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7205            // indices and `length` live outside the table and need the ordinary synthesis.
7206            // `object_get_own_property` does both.
7207            return Ok(Some(self.object_get_own_property(&target, key)?));
7208        };
7209        // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7210        // `ToPropertyDescriptor` runs, because that operation would box the primitive
7211        // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7212        // empty descriptor instead of refusing.
7213        if !matches!(result, Value::Undefined | Value::Object(_)) {
7214            return Err(self.type_error(
7215                "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7216            ));
7217        }
7218        let target_desc = self.object_get_own_property(&target, key)?;
7219        let extensible = self.object_is_extensible(&target)?;
7220        let Some(descriptor) = (match result {
7221            Value::Undefined => None,
7222            _ => Some(self.property_from_descriptor(&result)?),
7223        }) else {
7224            // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7225            // descriptor is configurable *and* the target can still grow back.
7226            if let Some(target_desc) = &target_desc {
7227                if !target_desc.configurable {
7228                    return Err(self.type_error(format!(
7229                        "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7230                    )));
7231                }
7232                if !extensible {
7233                    return Err(self.type_error(format!(
7234                        "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7235                    )));
7236                }
7237            }
7238            return Ok(Some(None));
7239        };
7240        // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7241        // which is a stronger requirement than "the target is not contradicting it" — the
7242        // four branches below are each one test262 case.
7243        if !descriptor.configurable {
7244            let Some(target_desc) = &target_desc else {
7245                return Err(self.type_error(format!(
7246                    "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7247                )));
7248            };
7249            if target_desc.configurable {
7250                return Err(self.type_error(format!(
7251                    "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7252                )));
7253            }
7254            let target_is_data = !target_desc.is_accessor();
7255            let result_is_data = !descriptor.is_accessor();
7256            if result_is_data && !target_is_data {
7257                return Err(self.type_error(format!(
7258                    "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7259                )));
7260            }
7261            if target_is_data && !target_desc.writable {
7262                if !result_is_data {
7263                    return Err(self.type_error(format!(
7264                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7265                    )));
7266                }
7267                if descriptor.writable {
7268                    return Err(self.type_error(format!(
7269                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7270                    )));
7271                }
7272                let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7273                let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7274                if !fixed_value.same_value(&reported) {
7275                    return Err(self.type_error(format!(
7276                        "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7277                    )));
7278                }
7279            }
7280            // Step 16.d: a reported *read-only* data property needs a real read-only data
7281            // property behind it. Missing this let a trap bolt a frozen property onto a
7282            // writable target intent (`resultdesc-is-not-configurable-not-writable-
7283            // targetdesc-is-writable`).
7284            if result_is_data && !descriptor.writable {
7285                if !target_is_data {
7286                    return Err(self.type_error(format!(
7287                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7288                    )));
7289                }
7290                if target_desc.writable {
7291                    return Err(self.type_error(format!(
7292                        "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7293                    )));
7294                }
7295            }
7296            if descriptor.is_accessor() {
7297                // Step 16.e: a getter the target does not have may not be invented, and
7298                // vice versa.
7299                let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7300                    (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7301                    (Some(a), Some(b)) => a.same_value(b),
7302                    _ => false,
7303                };
7304                if !same(&target_desc.getter, &descriptor.getter)
7305                    || !same(&target_desc.setter, &descriptor.setter)
7306                {
7307                    return Err(self.type_error(format!(
7308                        "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7309                    )));
7310                }
7311            }
7312        }
7313        // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7314        // where the target's own is locked. Without it a handler could advertise
7315        // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7316        // that believed it would try to redefine something it cannot.
7317        if descriptor.configurable
7318            && let Some(target_desc) = &target_desc
7319            && !target_desc.configurable
7320        {
7321            return Err(self.type_error(format!(
7322                "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7323            )));
7324        }
7325        // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7326        // through the trap either, however well-formed the descriptor is. This is the
7327        // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7328        // the frozen target does not own.
7329        if !extensible {
7330            let Some(target_desc) = &target_desc else {
7331                return Err(self.type_error(format!(
7332                    "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7333                )));
7334            };
7335            if target_desc.is_accessor() == descriptor.is_accessor() {
7336                let target_is_data = !target_desc.is_accessor();
7337                let result_is_data = !descriptor.is_accessor();
7338                if target_is_data && !target_desc.writable && descriptor.writable {
7339                    return Err(self.type_error(format!(
7340                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7341                    )));
7342                }
7343                if !result_is_data && !target_is_data {
7344                    let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7345                        (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7346                        (Some(a), Some(b)) => a.same_value(b),
7347                        _ => false,
7348                    };
7349                    if !same(&target_desc.getter, &descriptor.getter)
7350                        || !same(&target_desc.setter, &descriptor.setter)
7351                    {
7352                        return Err(self.type_error(format!(
7353                            "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7354                        )));
7355                    }
7356                }
7357            }
7358        }
7359        Ok(Some(Some(descriptor)))
7360    }
7361
7362    /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7363    ///
7364    /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7365    /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7366    /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7367    /// for a data property. `Property` cannot express "this field is absent", so the whole
7368    /// property path is skipped and the descriptor is assembled here field by field.
7369    ///
7370    /// `current` is the property the trap reported, used only to tell a data property from
7371    /// an accessor.
7372    pub fn proxy_seal_property(
7373        &mut self,
7374        object: &Gc<JsObject>,
7375        key: &PropertyKey,
7376        frozen: bool,
7377        current: &Property,
7378    ) -> JsResult<bool> {
7379        let Some((_target, handler)) = self.proxy_parts(object)? else {
7380            return Err(self.type_error("not a proxy"));
7381        };
7382        let descriptor = self.new_object(None);
7383        descriptor.define_data("configurable", Value::Bool(false));
7384        if frozen && !current.is_accessor() {
7385            descriptor.define_data("writable", Value::Bool(false));
7386        }
7387        let key_value = self.key_value(key);
7388        let target = object
7389            .proxy_state()
7390            .and_then(|state| state.borrow().target.clone());
7391        let Some(target) = target else {
7392            return Err(self.type_error("cannot use a proxy that has been revoked"));
7393        };
7394        let Some(result) = self.proxy_trap(
7395            &handler,
7396            "defineProperty",
7397            vec![Value::Object(target), key_value, Value::Object(descriptor)],
7398        )?
7399        else {
7400            // No trap means the definition belongs to the target; `false` is its answer.
7401            return Ok(false);
7402        };
7403        Ok(result.to_boolean())
7404    }
7405
7406    /// `[[DefineOwnProperty]]` on a proxy.
7407    fn proxy_define_property(
7408        &mut self,
7409        object: &Gc<JsObject>,
7410        key: &PropertyKey,
7411        property: Property,
7412    ) -> JsResult<Option<bool>> {
7413        let Some((target, handler)) = self.proxy_parts(object)? else {
7414            return Ok(None);
7415        };
7416        let key_value = self.key_value(key);
7417        let descriptor = self.descriptor_from_property(&property);
7418        let Some(result) = self.proxy_trap(
7419            &handler,
7420            "defineProperty",
7421            vec![Value::Object(target.clone()), key_value, descriptor],
7422        )?
7423        else {
7424            // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7425            // going" answer and `object_define_own_property` turns it into exactly that
7426            // forwarding — see the note there. (Reading it as "not a proxy" would define
7427            // the property on the proxy object itself, whose table is empty and which no
7428            // read ever consults.)
7429            return Ok(None);
7430        };
7431        if !result.to_boolean() {
7432            return Ok(Some(false));
7433        }
7434        // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7435        // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7436        // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7437        // and treating them alike made four cases pass a descriptor the target contradicts.
7438        let target_desc = self.object_get_own_property(&target, key)?;
7439        let extensible = self.object_is_extensible(&target)?;
7440        let named = property
7441            .descriptor_fields
7442            .unwrap_or(crate::object::DescriptorFields {
7443                value: false,
7444                writable: false,
7445                enumerable: false,
7446                configurable: false,
7447                get: false,
7448                set: false,
7449            });
7450        if named.configurable && !property.configurable {
7451            let Some(target_desc) = &target_desc else {
7452                return Err(self.type_error(format!(
7453                    "proxy 'defineProperty' invented the non-configurable '{key}'"
7454                )));
7455            };
7456            if target_desc.configurable {
7457                return Err(self.type_error(format!(
7458                    "proxy 'defineProperty' made '{key}' non-configurable"
7459                )));
7460            }
7461        }
7462        // Step 11's other half: reporting that a property was made *configurable* needs a
7463        // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7464        // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7465        // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7466        // target`).
7467        if named.configurable
7468            && property.configurable
7469            && let Some(target_desc) = &target_desc
7470            && !target_desc.configurable
7471        {
7472            return Err(
7473                self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7474            );
7475        }
7476        // Step 12: a property cannot be reported *made writable* when the target's copy is
7477        // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7478        // the trap is allowed to claim a definition it did not perform, as long as the
7479        // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7480        // legal, and refusing it broke the commonest way to seed a proxy).
7481        if named.writable
7482            && property.writable
7483            && let Some(target_desc) = &target_desc
7484            && !target_desc.writable
7485        {
7486            return Err(self.type_error(format!(
7487                "proxy 'defineProperty' made the read-only '{key}' writable"
7488            )));
7489        }
7490        // Step 13: making a property read-only needs an existing read-only property.
7491        if named.writable
7492            && !property.writable
7493            && let Some(target_desc) = &target_desc
7494            && !target_desc.is_accessor()
7495            && target_desc.writable
7496        {
7497            return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7498        }
7499        // Step 14: a non-writable, non-configurable property's value is fixed.
7500        if named.value
7501            && let Some(target_desc) = &target_desc
7502            && !target_desc.is_accessor()
7503            && !target_desc.writable
7504            && !target_desc.configurable
7505        {
7506            let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7507            let reported = property.value.clone().unwrap_or(Value::Undefined);
7508            if !fixed_value.same_value(&reported) {
7509                return Err(self.type_error(format!(
7510                    "proxy 'defineProperty' changed the value of '{key}'"
7511                )));
7512            }
7513        }
7514        // Step 15: a non-extensible target cannot grow.
7515        if target_desc.is_none() && !extensible {
7516            return Err(self.type_error(format!(
7517                "proxy 'defineProperty' added '{key}' to a non-extensible target"
7518            )));
7519        }
7520        Ok(Some(true))
7521    }
7522
7523    /// `[[GetPrototypeOf]]` on a proxy.
7524    fn proxy_get_prototype_of(
7525        &mut self,
7526        object: &Gc<JsObject>,
7527    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7528        let Some((target, handler)) = self.proxy_parts(object)? else {
7529            return Ok(None);
7530        };
7531        let Some(result) = self.proxy_trap(
7532            &handler,
7533            "getPrototypeOf",
7534            vec![Value::Object(target.clone())],
7535        )?
7536        else {
7537            // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7538            // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7539            // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7540            // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7541            // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7542            return Ok(Some(self.object_prototype_of(&target)?));
7543        };
7544        let proto = match &result {
7545            Value::Null => None,
7546            Value::Object(proto) => Some(proto.clone()),
7547            _ => {
7548                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7549            }
7550        };
7551        if !self.object_is_extensible(&target)? {
7552            let actual = self.object_prototype_of(&target)?;
7553            if !same_proto(proto.as_ref(), actual.as_ref()) {
7554                return Err(self.type_error(
7555                    "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7556                ));
7557            }
7558        }
7559        Ok(Some(proto))
7560    }
7561
7562    /// `[[SetPrototypeOf]]` on a proxy.
7563    fn proxy_set_prototype_of(
7564        &mut self,
7565        object: &Gc<JsObject>,
7566        proto: Option<Gc<JsObject>>,
7567    ) -> JsResult<Option<bool>> {
7568        let Some((target, handler)) = self.proxy_parts(object)? else {
7569            return Ok(None);
7570        };
7571        let proto_value = match &proto {
7572            Some(proto) => Value::Object(proto.clone()),
7573            None => Value::Null,
7574        };
7575        let Some(result) = self.proxy_trap(
7576            &handler,
7577            "setPrototypeOf",
7578            vec![Value::Object(target.clone()), proto_value],
7579        )?
7580        else {
7581            // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7582            // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7583            // its stored prototype overwritten behind its back.
7584            return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7585        };
7586        if result.to_boolean()
7587            && !self.object_is_extensible(&target)?
7588            && !same_proto(
7589                Some(&proto).and_then(|p| p.clone()).as_ref(),
7590                self.object_prototype_of(&target)?.as_ref(),
7591            )
7592        {
7593            return Err(self.type_error(
7594                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7595            ));
7596        }
7597        Ok(Some(result.to_boolean()))
7598    }
7599
7600    /// `[[IsExtensible]]` on a proxy.
7601    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7602        let Some((target, handler)) = self.proxy_parts(object)? else {
7603            return Ok(None);
7604        };
7605        let Some(result) = self.proxy_trap(
7606            &handler,
7607            "isExtensible",
7608            vec![Value::Object(target.clone())],
7609        )?
7610        else {
7611            return Ok(Some(self.object_is_extensible(&target)?));
7612        };
7613        // The answer is not the proxy's to invent: it must agree with the target, or a
7614        // script could learn `false` while the target keeps accepting new properties.
7615        if result.to_boolean() != self.object_is_extensible(&target)? {
7616            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7617        }
7618        Ok(Some(result.to_boolean()))
7619    }
7620
7621    /// `[[PreventExtensions]]` on a proxy.
7622    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7623        let Some((target, handler)) = self.proxy_parts(object)? else {
7624            return Ok(None);
7625        };
7626        let Some(result) = self.proxy_trap(
7627            &handler,
7628            "preventExtensions",
7629            vec![Value::Object(target.clone())],
7630        )?
7631        else {
7632            // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7633            // its answer can be `false`.
7634            return Ok(Some(self.object_prevent_extensions(&target)?));
7635        };
7636        if result.to_boolean() && self.object_is_extensible(&target)? {
7637            return Err(self.type_error(
7638                "proxy 'preventExtensions' reported success but the target is still extensible",
7639            ));
7640        }
7641        Ok(Some(result.to_boolean()))
7642    }
7643
7644    /// `[[Call]]` on a proxy, through the `apply` trap.
7645    fn proxy_apply(
7646        &mut self,
7647        object: &Gc<JsObject>,
7648        this: Value,
7649        args: Vec<Value>,
7650    ) -> JsResult<Option<Value>> {
7651        let Some((target, handler)) = self.proxy_parts(object)? else {
7652            return Ok(None);
7653        };
7654        // The trap gets the arguments as one array, which is the shape the spec passes
7655        // and the shape `apply` traps are written against (`args[0]` is the first one).
7656        let arguments = self.new_array(args.clone());
7657        let this_for_trap = this.clone();
7658        let Some(result) = self.proxy_trap(
7659            &handler,
7660            "apply",
7661            vec![
7662                Value::Object(target.clone()),
7663                this_for_trap,
7664                Value::Object(arguments),
7665            ],
7666        )?
7667        else {
7668            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7669        };
7670        Ok(Some(result))
7671    }
7672
7673    /// `[[Construct]]` on a proxy, through the `construct` trap.
7674    fn proxy_construct(
7675        &mut self,
7676        object: &Gc<JsObject>,
7677        args: Vec<Value>,
7678        new_target: &Value,
7679    ) -> JsResult<Option<Value>> {
7680        let Some((target, handler)) = self.proxy_parts(object)? else {
7681            return Ok(None);
7682        };
7683        if !target.is_callable() {
7684            return Err(self.type_error("proxy target is not a constructor"));
7685        }
7686        let arguments = self.new_array(args.clone());
7687        let Some(result) = self.proxy_trap(
7688            &handler,
7689            "construct",
7690            vec![
7691                Value::Object(target.clone()),
7692                Value::Object(arguments),
7693                new_target.clone(),
7694            ],
7695        )?
7696        else {
7697            return Ok(Some(self.construct(
7698                Value::Object(target),
7699                new_target.clone(),
7700                args,
7701            )?));
7702        };
7703        if !matches!(result, Value::Object(_)) {
7704            return Err(self.type_error("proxy 'construct' must return an object"));
7705        }
7706        Ok(Some(result))
7707    }
7708
7709    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7710    pub(crate) fn has_own_or_inherited(
7711        &mut self,
7712        object: &Gc<JsObject>,
7713        key: &PropertyKey,
7714    ) -> JsResult<bool> {
7715        // The object itself first: it may be a proxy, and then the answer is its trap's.
7716        if let Some(answer) = self.proxy_has(object, key)? {
7717            return Ok(answer);
7718        }
7719        // An integer-indexed exotic object answers a canonical numeric index from
7720        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7721        // prototype chain. That is observable twice: a view the buffer has been resized
7722        // away from has no indices, so `2 in view` is `false` even when
7723        // `Object.getPrototypeOf(view)[2]` exists (what
7724        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7725        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7726        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7727        // goes through here, which is why the same rule is repeated in `has_property_key`
7728        // rather than living only there.
7729        if object.typed_array_parts().is_some()
7730            && let Some(numeric) = canonical_numeric_index(key)
7731        {
7732            return Ok(typed_array_index_is_valid(object, numeric));
7733        }
7734        // A host class answers `in` for its own keys, which may live nowhere in a property
7735        // table — `"x" in point` is true because the class says so, not because a property
7736        // exists.
7737        if let Some(exotic) = object.exotic()
7738            && let Some(answer) = exotic.has_property(self, object, key)?
7739        {
7740            return Ok(answer);
7741        }
7742        // `has_own` rather than `own_property_key`: an array's elements and its derived
7743        // `length` are invisible to the property table, and `Array.prototype` is an array.
7744        // A host class's `get_own_property` counts too, because the reference's
7745        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7746        // lives — a class with only `get_own_property` answers `in` through it.
7747        if self.exotic_has_own(object, key)? {
7748            return Ok(true);
7749        }
7750        // A hole is *not* the end of the search: the chain may still have the key, which
7751        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7752        for ancestor in object.chain() {
7753            // A proxy further up the chain answers for itself.
7754            if let Some(answer) = self.proxy_has(&ancestor, key)? {
7755                return Ok(answer);
7756            }
7757            // Same for a host class: a prototype may be one, and `in` reaches it.
7758            if let Some(exotic) = ancestor.exotic()
7759                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7760            {
7761                return Ok(answer);
7762            }
7763            if self.exotic_has_own(&ancestor, key)? {
7764                return Ok(true);
7765            }
7766        }
7767        Ok(false)
7768    }
7769
7770    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7771    /// trap included.
7772    ///
7773    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7774    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7775    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7776        if let Some(exotic) = object.exotic()
7777            && let Some(answer) = exotic.get_own_property(self, object, key)?
7778        {
7779            return Ok(answer.is_some());
7780        }
7781        Ok(has_own(object, key))
7782    }
7783
7784    /// `CreateListFromArrayLike`, optionally restricted to property keys.
7785    ///
7786    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7787    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7788    /// `TypeError` instead of a property named `"1.5"`.
7789    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7790        let object = self.object_from(value)?;
7791        let length = self
7792            .get_property(&object, "length")?
7793            .map(|value| value.to_number())
7794            .unwrap_or(0.0);
7795        if !length.is_finite() || length < 0.0 {
7796            return Err(self.type_error("invalid array-like length"));
7797        }
7798        let length = length as usize;
7799        let mut items = Vec::with_capacity(length.min(1024));
7800        for index in 0..length {
7801            let item = self
7802                .get_property(&object, &index.to_string())?
7803                .unwrap_or(Value::Undefined);
7804            if keys_only && matches!(&item, Value::Symbol(_)) {
7805                items.push(item);
7806                continue;
7807            }
7808            if keys_only && !matches!(&item, Value::String(_)) {
7809                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7810            }
7811            items.push(item);
7812        }
7813        Ok(items)
7814    }
7815
7816    /// A `Property` from the descriptor object a trap returned.
7817    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7818        let object = self.object_from(value)?;
7819        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7820            interp.get_property(&object, name)
7821        };
7822        let getter = field(self, "get")?;
7823        let setter = field(self, "set")?;
7824        let accessor = getter.is_some() || setter.is_some();
7825        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7826            Ok(interp
7827                .get_property(&object, name)?
7828                .is_some_and(|value| value.to_boolean()))
7829        };
7830        let enumerable = boolean(self, "enumerable")?;
7831        let configurable = boolean(self, "configurable")?;
7832        if accessor {
7833            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7834                return Err(
7835                    self.type_error("a descriptor cannot be both a data property and an accessor")
7836                );
7837            }
7838            Ok(Property {
7839                getter: getter.or(Some(Value::Undefined)),
7840                setter: setter.or(Some(Value::Undefined)),
7841                enumerable,
7842                configurable,
7843                writable: false,
7844                value: None,
7845                descriptor_fields: None,
7846            })
7847        } else {
7848            Ok(Property {
7849                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7850                writable: boolean(self, "writable")?,
7851                enumerable,
7852                configurable,
7853                getter: None,
7854                setter: None,
7855                descriptor_fields: None,
7856            })
7857        }
7858    }
7859
7860    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7861    fn descriptor_from_property(&mut self, property: &Property) -> Value {
7862        let object = self.new_object(None);
7863        // A partial descriptor names only some fields, and the trap must see exactly those:
7864        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7865        // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7866        // case, where every field is present.
7867        let fields = property.descriptor_fields;
7868        let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7869            fields.is_none_or(|fields| field(&fields))
7870        };
7871        if property.is_accessor() {
7872            let getter = property.getter.clone().unwrap_or(Value::Undefined);
7873            let setter = property.setter.clone().unwrap_or(Value::Undefined);
7874            object.define_data("get", getter);
7875            object.define_data("set", setter);
7876        } else {
7877            if names(|fields| fields.value) {
7878                let value = property.value.clone().unwrap_or(Value::Undefined);
7879                object.define_data("value", value);
7880            }
7881            if names(|fields| fields.writable) {
7882                object.define_data("writable", Value::Bool(property.writable));
7883            }
7884        }
7885        if names(|fields| fields.enumerable) {
7886            object.define_data("enumerable", Value::Bool(property.enumerable));
7887        }
7888        if names(|fields| fields.configurable) {
7889            object.define_data("configurable", Value::Bool(property.configurable));
7890        }
7891        Value::Object(object)
7892    }
7893
7894    // -- calling ------------------------------------------------------------
7895
7896    /// Call `callee` with `this` and `args`.
7897    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7898        let Value::Object(function) = &callee else {
7899            // `typeof x === "function"` is not enough to make `x()` legal: only a
7900            // callable object is. `null` and `undefined` need no special wording
7901            // here — their `ToString` already reads the way the reference's does.
7902            let what = format!("{} is not a function", callee.to_js_string());
7903            return Err(Signal::Throw(self.make_error("TypeError", &what)));
7904        };
7905        // A proxy of a function is called through its `apply` trap. It has no
7906        // `ObjectKind::Function` of its own, so this has to come before the dispatch
7907        // below, and a proxy of a non-function has nothing to forward to.
7908        if function.proxy_state().is_some() {
7909            return match self.proxy_apply(function, this, args)? {
7910                Some(result) => Ok(result),
7911                None => Err(Signal::Throw(
7912                    self.make_error("TypeError", "proxy target is not callable"),
7913                )),
7914            };
7915        }
7916        let callable = function.with(|data| match &data.kind {
7917            ObjectKind::Function(callable) => match callable {
7918                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7919                // The `Rc` is cloned out so the borrow of this object's data is released
7920                // before the closure runs: the closure may touch the same object.
7921                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7922                Callable::Bound {
7923                    target,
7924                    this,
7925                    args: leading,
7926                } => Some(NativeCall::Bound {
7927                    target: target.clone(),
7928                    this: this.clone(),
7929                    leading: leading.clone(),
7930                }),
7931                Callable::Bytecode { code, env } => {
7932                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
7933                }
7934                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7935                Callable::PromiseResolve(promise) => {
7936                    Some(NativeCall::PromiseResolve(promise.clone()))
7937                }
7938                Callable::PromiseReject(promise) => {
7939                    Some(NativeCall::PromiseReject(promise.clone()))
7940                }
7941                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7942                    state: state.clone(),
7943                }),
7944                Callable::ThenShim {
7945                    handler,
7946                    resolve,
7947                    reject,
7948                    fulfilled,
7949                } => Some(NativeCall::ThenShim {
7950                    handler: handler.clone(),
7951                    resolve: resolve.clone(),
7952                    reject: reject.clone(),
7953                    fulfilled: *fulfilled,
7954                }),
7955                Callable::AwaitResume {
7956                    coroutine,
7957                    promise,
7958                    kind,
7959                } => Some(NativeCall::AwaitResume {
7960                    coroutine: coroutine.clone(),
7961                    promise: promise.clone(),
7962                    kind: *kind,
7963                }),
7964                Callable::CombinatorSettle {
7965                    state,
7966                    index,
7967                    fulfilled,
7968                } => Some(NativeCall::CombinatorSettle {
7969                    state: state.clone(),
7970                    index: *index,
7971                    fulfilled: *fulfilled,
7972                }),
7973                Callable::FinallyShim {
7974                    callback,
7975                    fulfilled,
7976                    constructor,
7977                } => Some(NativeCall::FinallyShim {
7978                    callback: callback.clone(),
7979                    fulfilled: *fulfilled,
7980                    constructor: constructor.clone(),
7981                }),
7982                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7983                Callable::CompletedReturn {
7984                    generator,
7985                    promise,
7986                    rejected,
7987                } => Some(NativeCall::CompletedReturn {
7988                    generator: generator.clone(),
7989                    promise: promise.clone(),
7990                    rejected: *rejected,
7991                }),
7992                Callable::YieldResult {
7993                    generator,
7994                    promise,
7995                    done,
7996                } => Some(NativeCall::YieldResult {
7997                    generator: generator.clone(),
7998                    promise: promise.clone(),
7999                    done: *done,
8000                }),
8001                Callable::DisposeStep {
8002                    remaining,
8003                    promise,
8004                    error,
8005                    rejected,
8006                    awaited,
8007                    needs_await,
8008                } => Some(NativeCall::DisposeStep {
8009                    remaining: remaining.clone(),
8010                    promise: promise.clone(),
8011                    error: error.clone(),
8012                    rejected: *rejected,
8013                    awaited: *awaited,
8014                    needs_await: *needs_await,
8015                }),
8016                Callable::GeneratorResume {
8017                    generator,
8018                    promise,
8019                    kind,
8020                } => Some(NativeCall::GeneratorResume {
8021                    generator: generator.clone(),
8022                    promise: promise.clone(),
8023                    kind: *kind,
8024                }),
8025                Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8026                Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8027                Callable::SettlePromise {
8028                    promise,
8029                    value,
8030                    rejected,
8031                } => Some(NativeCall::SettlePromise {
8032                    promise: promise.clone(),
8033                    value: value.clone(),
8034                    rejected: *rejected,
8035                }),
8036            },
8037            _ => None,
8038        });
8039        match callable {
8040            Some(NativeCall::Host(func)) => {
8041                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8042                // function by name rather than stopping at the caller.
8043                let frame_less = function
8044                    .own_property("_frame_less")
8045                    .and_then(|property| property.value)
8046                    .is_some_and(|value| value.to_boolean());
8047                let outer = if frame_less {
8048                    None
8049                } else {
8050                    self.native_frames
8051                        .push((function.clone(), self.frames.len()));
8052                    Some(self.current_native.replace(function.clone()))
8053                };
8054                // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8055                // constructor reads it through `current_new_target` because it is handed
8056                // `undefined` for `this`. Taking the parked value here is what stops a
8057                // *plain* call made from inside a constructor body from seeing the
8058                // enclosing `new.target`.
8059                let parked = self.pending_new_target.take();
8060                let result = {
8061                    let outer_new_target = std::mem::replace(
8062                        &mut self.active_new_target,
8063                        parked.unwrap_or(Value::Undefined),
8064                    );
8065                    let result = {
8066                        let mut body = func.borrow_mut();
8067                        body(self, this, &args)
8068                    };
8069                    self.active_new_target = outer_new_target;
8070                    result
8071                };
8072                if !frame_less {
8073                    self.native_frames.pop();
8074                    self.current_native = outer.flatten();
8075                }
8076                result
8077            }
8078            Some(NativeCall::Native(func)) => {
8079                // A function marked `_frame_less` is one the reference implements
8080                // without a call frame — `eval` is the only one so far.
8081                let frame_less = function
8082                    .own_property("_frame_less")
8083                    .and_then(|property| property.value)
8084                    .is_some_and(|value| value.to_boolean());
8085                let outer = if frame_less {
8086                    None
8087                } else {
8088                    self.native_frames
8089                        .push((function.clone(), self.frames.len()));
8090                    Some(self.current_native.replace(function.clone()))
8091                };
8092                let parked = self.pending_new_target.take();
8093                let outer_new_target = std::mem::replace(
8094                    &mut self.active_new_target,
8095                    parked.unwrap_or(Value::Undefined),
8096                );
8097                let result = func(self, this, &args);
8098                self.active_new_target = outer_new_target;
8099                if !frame_less {
8100                    self.native_frames.pop();
8101                    self.current_native = outer.flatten();
8102                }
8103                result
8104            }
8105            Some(NativeCall::Revoker(slots)) => {
8106                // Idempotent: revoking twice answers `undefined` again rather than
8107                // complaining, which is what the spec says and what a `finally` block
8108                // relies on.
8109                let mut state = slots.borrow_mut();
8110                state.target = None;
8111                state.handler = None;
8112                Ok(Value::Undefined)
8113            }
8114            Some(NativeCall::PromiseResolve(promise)) => {
8115                // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8116                // else, so a resolve after a reject does nothing *and* a resolve after a
8117                // resolve-with-thenable does nothing — the promise is still `Pending` then,
8118                // because the adoption is a queued job.
8119                let value = args.first().cloned().unwrap_or(Value::Undefined);
8120                if !self.claim_resolution(&promise) {
8121                    return Ok(Value::Undefined);
8122                }
8123                // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8124                // the resolve function performs `RejectPromise` and returns `undefined`.
8125                // (`ResolvePromise` itself throws as well, so the engine's own callers see
8126                // it; only this wrapper swallows it.)
8127                let _ = self.resolve_promise_with(&promise, value);
8128                Ok(Value::Undefined)
8129            }
8130            Some(NativeCall::PromiseReject(promise)) => {
8131                let reason = args.first().cloned().unwrap_or(Value::Undefined);
8132                // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8133                if !self.claim_resolution(&promise) {
8134                    return Ok(Value::Undefined);
8135                }
8136                self.reject_promise(&promise, reason);
8137                Ok(Value::Undefined)
8138            }
8139            Some(NativeCall::ThenShim {
8140                handler,
8141                resolve,
8142                reject,
8143                fulfilled,
8144            }) => {
8145                // `PerformPromiseThen` with a capability: run the handler, then settle
8146                // through the capability's own pair. A throw from the handler is the
8147                // rejection, and a throw from the capability's `resolve` is not caught —
8148                // exactly the spec's `?`.
8149                let value = args.first().cloned().unwrap_or(Value::Undefined);
8150                match handler {
8151                    Some(handler) => {
8152                        match self.call_value(handler, Value::Undefined, vec![value]) {
8153                            Ok(result) => {
8154                                self.call_value(resolve, Value::Undefined, vec![result])?;
8155                            }
8156                            Err(Signal::Throw(reason)) => {
8157                                self.call_value(reject, Value::Undefined, vec![reason])?;
8158                            }
8159                            Err(signal) => return Err(signal),
8160                        }
8161                    }
8162                    None => {
8163                        let handler = if fulfilled { resolve } else { reject };
8164                        self.call_value(handler, Value::Undefined, vec![value])?;
8165                    }
8166                }
8167                Ok(Value::Undefined)
8168            }
8169            Some(NativeCall::CapabilityExecutor { state }) => {
8170                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8171                // slot holds a value yet. The test is on the *values*, not on a call count —
8172                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8173                // called-twice`'s first case does exactly that), while a second call after a
8174                // real pair is the `TypeError`.
8175                let defined = |name: &str| {
8176                    state
8177                        .own_property(name)
8178                        .and_then(|property| property.value)
8179                        .is_some_and(|value| !matches!(value, Value::Undefined))
8180                };
8181                if defined("resolve") || defined("reject") {
8182                    return Err(self.type_error("promise capability executor called twice"));
8183                }
8184                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8185                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8186                state.define_data("resolve", resolve);
8187                state.define_data("reject", reject);
8188                Ok(Value::Undefined)
8189            }
8190            Some(NativeCall::CombinatorSettle {
8191                state,
8192                index,
8193                fulfilled,
8194            }) => {
8195                let value = args.first().cloned().unwrap_or(Value::Undefined);
8196                self.settle_combinator(&state, index, fulfilled, value)?;
8197                Ok(Value::Undefined)
8198            }
8199            Some(NativeCall::AwaitResume {
8200                coroutine,
8201                promise,
8202                kind,
8203            }) => {
8204                // Resume *inline*, in the reaction that delivered the value. Deferring it
8205                // by another job inserts a tick between every `await` and its
8206                // continuation, which reorders `await` against unrelated `then` chains —
8207                // `f().then(g)` then runs before `f`'s own next statement.
8208                self.drive_async(
8209                    &coroutine,
8210                    &promise,
8211                    kind,
8212                    args.first().cloned().unwrap_or(Value::Undefined),
8213                )
8214                .map(|()| Value::Undefined)
8215            }
8216            Some(NativeCall::ReturnValue(value)) => Ok(value),
8217            Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8218            Some(NativeCall::FinallyShim {
8219                callback,
8220                fulfilled,
8221                constructor,
8222            }) => {
8223                // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8224                // own value is discarded; what the caller sees is the *original* outcome,
8225                // delayed until `PromiseResolve(C, result)` has settled.
8226                //
8227                // Two details are observable and both have a test:
8228                //
8229                // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8230                //   `PerformPromiseThen`. A callback that returns a thenable with its own
8231                //   `then` must have that `then` called
8232                //   (`resolved-observable-then-calls` counts it);
8233                // * only the **fulfil** handler is supplied. A returned promise that
8234                //   *rejects* rejects the whole `finally`, rather than having its failure
8235                //   swallowed and the original value passed through.
8236                let original = args.first().cloned().unwrap_or(Value::Undefined);
8237                let result = match &callback {
8238                    Some(callback) => {
8239                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8240                    }
8241                    None => Value::Undefined,
8242                };
8243                // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8244                // constructor is reused rather than rewrapped, which is what keeps
8245                // `mp1.finally(() => mp2)` from gaining a layer.
8246                let resolved = self.promise_resolve_for(&constructor, result)?;
8247                let thunk = if fulfilled {
8248                    Callable::ReturnValue(original)
8249                } else {
8250                    Callable::ThrowValue(original)
8251                };
8252                // `length: 0` and `name: ""`, and **not** a constructor — the three things
8253                // `resolved-observable-then-calls-argument` reads off the thunk while it has
8254                // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8255                // function with no `length` at all.
8256                let thunk = self.builtin_function("", 0, thunk);
8257                let then = self.read_field(&resolved, "then")?;
8258                if !matches!(&then, Value::Object(object) if object.is_callable()) {
8259                    return Err(self.type_error("then is not a function"));
8260                }
8261                self.call_value(then, resolved, vec![Value::Object(thunk)])
8262            }
8263            Some(NativeCall::DisposeStep {
8264                remaining,
8265                promise,
8266                error,
8267                rejected,
8268                awaited,
8269                needs_await,
8270            }) => {
8271                let error = if rejected {
8272                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
8273                    self.merge_dispose_error(reason, error)
8274                } else {
8275                    error
8276                };
8277                self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8278                Ok(Value::Undefined)
8279            }
8280            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
8281            Some(NativeCall::CompletedReturn {
8282                generator,
8283                promise,
8284                rejected,
8285            }) => {
8286                let value = args.first().cloned().unwrap_or(Value::Undefined);
8287                let outcome = if rejected {
8288                    AsyncOutcome::Error(value)
8289                } else {
8290                    AsyncOutcome::Value(self.iterator_result(value, true)?)
8291                };
8292                self.settle_async_request(&generator, &promise, outcome)?;
8293                Ok(Value::Undefined)
8294            }
8295            Some(NativeCall::YieldResult {
8296                generator,
8297                promise,
8298                done,
8299            }) => {
8300                let value = args.first().cloned().unwrap_or(Value::Undefined);
8301                let result = self.iterator_result(value, done)?;
8302                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8303                Ok(Value::Undefined)
8304            }
8305            Some(NativeCall::GeneratorResume {
8306                generator,
8307                promise,
8308                kind,
8309            }) => {
8310                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8311                // tick and reorders the generator against other chains.
8312                self.step_async_generator(
8313                    &generator,
8314                    &promise,
8315                    kind,
8316                    args.first().cloned().unwrap_or(Value::Undefined),
8317                )
8318                .map(|()| Value::Undefined)
8319            }
8320            Some(NativeCall::SettlePromise {
8321                promise,
8322                value,
8323                rejected,
8324            }) => {
8325                if rejected {
8326                    self.reject_promise(&promise, value);
8327                } else {
8328                    self.fulfill_promise(&promise, value);
8329                }
8330                Ok(Value::Undefined)
8331            }
8332            Some(NativeCall::Bound {
8333                target,
8334                this: bound_this,
8335                leading,
8336            }) => {
8337                let mut all = leading;
8338                all.extend(args);
8339                self.call_value(target, bound_this, all)
8340            }
8341            Some(NativeCall::Bytecode(code, env)) => {
8342                if code.code.kind.is_generator() {
8343                    return self.new_generator(callee, this, args);
8344                }
8345                if code.code.kind.is_async() {
8346                    // Same coroutine machinery as a generator; the difference is only in
8347                    // what the completion does — see `new_async_function`.
8348                    return self.new_async_function(callee, this, args);
8349                }
8350                self.execute(code, env, this, args, callee)
8351            }
8352            None => Err(Signal::Throw(
8353                self.make_error("TypeError", "not a function"),
8354            )),
8355        }
8356    }
8357
8358    /// Give a freshly built function its own `prototype` object.
8359    ///
8360    /// Every function that can be used with `new` carries one, and its
8361    /// `constructor` points back at the function — a reference cycle, which is
8362    /// exactly what the collector's cycle pass exists to reclaim.
8363    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8364        self.install_function_prototype_with(function, None);
8365    }
8366
8367    /// [`Interp::install_function_prototype`] with an explicit parent for the new
8368    /// `prototype` object.
8369    ///
8370    /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8371    /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8372    /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8373    /// `None` means `%Object.prototype%`.
8374    fn install_function_prototype_with(
8375        &mut self,
8376        function: &Gc<JsObject>,
8377        parent: Option<Gc<JsObject>>,
8378    ) {
8379        let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8380        let prototype = self.new_object(Some(parent));
8381        let constructor = Value::Object(function.clone());
8382        prototype.define(
8383            "constructor",
8384            Property::with_attributes(constructor, true, false),
8385        );
8386        let value = Value::Object(prototype);
8387        function.define("prototype", Property::prototype_of(value, true));
8388    }
8389
8390    /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8391    /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8392    /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8393    ///
8394    /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8395    /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8396    /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8397    /// is `[]` there.
8398    fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8399        let prototype = self.new_object(Some(parent));
8400        let value = Value::Object(prototype);
8401        function.define("prototype", Property::prototype_of(value, true));
8402    }
8403
8404    /// The `[[Prototype]]` a newly created generator object gets:
8405    /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8406    ///
8407    /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8408    /// function's `prototype` is writable, so a script can replace it with anything, and
8409    /// only an *object* is consulted.
8410    fn generator_instance_proto(
8411        &mut self,
8412        function: &Gc<JsObject>,
8413        default: Gc<JsObject>,
8414    ) -> JsResult<Gc<JsObject>> {
8415        match self.get_property(function, "prototype")? {
8416            Some(Value::Object(prototype)) => Ok(prototype),
8417            _ => Ok(default),
8418        }
8419    }
8420
8421    /// A getter or setter that reads or writes the reference cell behind a mapped
8422    /// `arguments` index.
8423    ///
8424    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8425    /// count — which is what the collector treats as "a reference from outside the
8426    /// heap". The closure therefore keeps the cell alive for exactly as long as the
8427    /// accessor is reachable, which is the same lifetime the arguments object has.
8428    ///
8429    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8430    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8431    /// parameter value and the arguments object reaches the closure, never the other
8432    /// way round. Nothing the collector has to see is hidden.
8433    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8434        let name = if is_setter { "set" } else { "get" };
8435        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8436            if is_setter {
8437                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8438                Ok(Value::Undefined)
8439            } else {
8440                Ok(cell.get())
8441            }
8442        };
8443        self.new_host_function(name, 1, Box::new(func))
8444    }
8445
8446    /// The object `special_object` builds.
8447    ///
8448    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8449    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8450    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8451    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8452    /// write through `arguments` does not reach the parameter.
8453    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8454        match magic {
8455            0 | 1 => {
8456                let args = self.frame().passed().to_vec();
8457                let proto = self.realm.object_proto.clone();
8458                let object = self.new_object(Some(proto));
8459                // The marker `Object.prototype.toString` needs: an arguments object is an
8460                // ordinary object apart from reporting `[object Arguments]`, and that has
8461                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8462                // show up ahead of them in a key listing anyway — it is non-enumerable.
8463                self.internal_set(&object, "_class", self.string("Arguments"));
8464                // `length` is writable and configurable but neither enumerable nor a
8465                // plain data property: `Object.keys(arguments)` lists the indices only,
8466                // which is how `{...arguments}` copies them without the length.
8467                object.define(
8468                    "length",
8469                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
8470                );
8471                // `magic == 1` is sloppy mode, where each index is *mapped* to the
8472                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8473                // change `a`, and assigning `a` has to change `arguments[0]`.
8474                //
8475                // The shared storage is the parameter's reference cell. The compiler
8476                // gives every parameter of such a function one (see
8477                // `provide_body_arguments`), and the cell outlives the frame, so this
8478                // keeps working after the arguments object escapes.
8479                //
8480                // The index becomes an accessor rather than a data property. A mapped
8481                // index reports as a plain writable/enumerable data property through
8482                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8483                // the getter/setter pair is only the plumbing underneath.
8484                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8485                    let frame = self.frame();
8486                    frame
8487                        .code
8488                        .arg_cell
8489                        .iter()
8490                        .map(|cell| {
8491                            (*cell >= 0)
8492                                .then(|| frame.cells.get(*cell as usize).cloned())
8493                                .flatten()
8494                        })
8495                        .collect()
8496                } else {
8497                    Vec::new()
8498                };
8499                // Tell the object which indices are mapped, so
8500                // `Object.getOwnPropertyDescriptor` can report them as the data
8501                // properties the spec describes instead of the accessors that
8502                // implement the aliasing.
8503                if magic == 1 {
8504                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8505                    for cell in &mapped_cells {
8506                        table.push(cell.clone());
8507                    }
8508                    object.set_mapped_arguments(table);
8509                }
8510                for (index, value) in args.into_iter().enumerate() {
8511                    match mapped_cells.get(index).cloned().flatten() {
8512                        Some(cell) => {
8513                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8514                            let setter = self.new_mapped_arguments_accessor(cell, true);
8515                            object.define(
8516                                &index.to_string(),
8517                                Property::accessor_with(
8518                                    Some(Value::Object(getter)),
8519                                    Some(Value::Object(setter)),
8520                                    true,
8521                                ),
8522                            );
8523                        }
8524                        None => object.define_data(&index.to_string(), value),
8525                    }
8526                }
8527                // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8528                // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8529                // non-enumerable and non-configurable. It is not a nicety — it is the only
8530                // documented way to reach `%ThrowTypeError%`:
8531                //
8532                //     Object.getOwnPropertyDescriptor(function(){"use strict";
8533                //         return arguments;}(), "callee").get
8534                //
8535                // and the whole `ThrowTypeError/` directory is written against that
8536                // expression. Without it 13 cases failed with `cannot read property 'get'
8537                // of undefined`, which reads like a test harness bug rather than a missing
8538                // accessor.
8539                //
8540                // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8541                // writable data property holding the function being called, and
8542                // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8543                // `hasOwnProperty("callee")` hold there.
8544                if magic == 1 {
8545                    let callee = self.frame().callee.clone();
8546                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8547                    object.define("callee", Property::with_attributes(callee, true, false));
8548                } else if let Some(thrower) = self.realm.throw_type_error.clone()
8549                    && object.own_property("callee").is_none()
8550                {
8551                    object.define(
8552                        "callee",
8553                        Property {
8554                            getter: Some(Value::Object(thrower.clone())),
8555                            setter: Some(Value::Object(thrower)),
8556                            enumerable: false,
8557                            configurable: false,
8558                            ..Property::default()
8559                        },
8560                    );
8561                }
8562                // An arguments object is iterable: `[...arguments]` and
8563                // `for (const a of arguments)` both work, through the *array* iterator
8564                // because the object is array-like. Without this the whole spread form
8565                // reported "not iterable".
8566                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8567                let values = self
8568                    .realm
8569                    .array_proto
8570                    .own_property("values")
8571                    .and_then(|property| property.value);
8572                if let Some(values) = values {
8573                    object.define_key(
8574                        &iterator_key,
8575                        Property::with_attributes(values, true, false),
8576                    );
8577                }
8578                Ok(Value::Object(object))
8579            }
8580            // `this.active_func`: the constructor `super()` resolves against.
8581            //
8582            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8583            // own, so it inherits this from the function it was written in along with `this`
8584            // — and that is a lexical relationship, not a stack one: an arrow that escaped
8585            // the constructor and is called back later (`iter.return = () => super()`) has
8586            // the constructor nowhere on the stack. The compiler therefore reads it out of
8587            // a closure variable of the enclosing function, exactly as the reference does
8588            // with its `this_active_func` local.
8589            2 => Ok(self
8590                .current_callee()
8591                .map_or(Value::Undefined, Value::Object)),
8592            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8593            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8594            // its own either, so the lookup walks out to the nearest non-arrow frame for
8595            // the same reason as `this.active_func` above — without that, `super()` inside
8596            // an arrow passed `undefined` as the new target and the parent constructor was
8597            // then rejected for being invoked without `new`.
8598            3 => Ok(self
8599                .eval_new_target
8600                .clone()
8601                .unwrap_or_else(|| self.frame().new_target.clone())),
8602            // `[[HomeObject]]` of the function being run: what `super` is relative to.
8603            // An arrow has none of its own, so the lookup walks out to the enclosing
8604            // method — which is why `super` works inside an arrow inside a method.
8605            4 => Ok(self
8606                .frames
8607                .iter()
8608                .rev()
8609                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8610                .map_or(Value::Undefined, Value::Object)),
8611            // `import.meta`: the innermost module body's meta object. Outside a module
8612            // the compiler never emits this, so an empty fallback is unreachable rather
8613            // than permissive.
8614            6 => {
8615                let name = self.module_stack.last().cloned();
8616                let meta = name
8617                    .and_then(|name| self.modules.get(&name).cloned())
8618                    .and_then(|module| module.with(|r| r.import_meta.clone()));
8619                Ok(meta.map_or(Value::Undefined, Value::Object))
8620            }
8621            other => Err(Signal::Throw(self.make_error(
8622                "InternalError",
8623                &format!("special_object {other} is not implemented yet"),
8624            ))),
8625        }
8626    }
8627
8628    /// `[[HomeObject]]` of the innermost function that has one, if any.
8629    ///
8630    /// An arrow has none, so the search walks out to the enclosing method — the same
8631    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8632    /// inside a method.
8633    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8634        self.frames
8635            .iter()
8636            .rev()
8637            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8638    }
8639
8640    /// The dispose method a `using` declaration should snapshot, or an error.
8641    ///
8642    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8643    /// is what makes a resource that only knows the synchronous protocol usable in both
8644    /// forms.
8645    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8646        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8647        if value.is_nullish() {
8648            return Ok(Value::Undefined);
8649        }
8650        let Some(object) = value.as_object() else {
8651            return Err(self.type_error("not an object"));
8652        };
8653        let mut method = if await_form {
8654            let found = self.get_property_key(
8655                object,
8656                &self.realm.well_known_key(WellKnown::AsyncDisposable),
8657            )?;
8658            match found {
8659                Some(found) if !found.is_nullish() => Some(found),
8660                _ => self
8661                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8662            }
8663        } else {
8664            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8665        };
8666        let Some(found) = method.take() else {
8667            return Err(self.type_error("value is not disposable"));
8668        };
8669        if found.is_nullish() {
8670            return Err(self.type_error("value is not disposable"));
8671        }
8672        let callable = found.as_object().is_some_and(|object| object.is_callable());
8673        if !callable {
8674            return Err(self.type_error("dispose method is not a function"));
8675        }
8676        Ok(found)
8677    }
8678
8679    /// Call one resource's disposer, folding a failure into `error_state`.
8680    ///
8681    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8682    /// because a captured `using` binding lives in its reference cell and the local slot is
8683    /// stale — a closure over the resource is legal and must not change what is disposed.
8684    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8685        let value = self.get_loc(slot);
8686        let method = self.get_loc(slot + 1);
8687        // A resource that was never initialised — its declaration threw — or that is
8688        // `null`/`undefined` has nothing to dispose.
8689        if value.is_nullish() || matches!(value, Value::Uninitialized) {
8690            return Ok(error_state);
8691        }
8692        if matches!(method, Value::Undefined | Value::Uninitialized) {
8693            return Ok(error_state);
8694        }
8695        match self.call_value(method, value, Vec::new()) {
8696            Ok(_) => Ok(error_state),
8697            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8698            Err(other) => Err(other),
8699        }
8700    }
8701
8702    /// Combine a disposal failure with whatever was already going wrong.
8703    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8704        if matches!(error_state, Value::Uninitialized) {
8705            return new_error;
8706        }
8707        self.new_suppressed_error(new_error, error_state)
8708    }
8709
8710    /// A `SuppressedError` instance built straight from its prototype.
8711    ///
8712    /// Not through the constructor: a script that rewrites
8713    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8714    /// error wrapping.
8715    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8716        let proto = self
8717            .realm
8718            .suppressed_error_proto
8719            .clone()
8720            .unwrap_or_else(|| self.realm.error_proto.clone());
8721        let object = self.new_object(Some(proto));
8722        object.define("error", Property::with_attributes(error, true, true));
8723        object.define(
8724            "suppressed",
8725            Property::with_attributes(suppressed, true, true),
8726        );
8727        object.define(
8728            "message",
8729            Property::with_attributes(self.string("SuppressedError"), true, true),
8730        );
8731        self.internal_set(&object, "_class", self.string("Error"));
8732        self.add_stack(&object);
8733        Value::Object(object)
8734    }
8735
8736    /// Call `callee`, or push its frame and let the main loop run it.
8737    ///
8738    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8739    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8740    /// continues, so `function f(){ return f() }` costs heap and stops at
8741    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8742    /// is entered directly, and natives do not re-enter JavaScript in this
8743    /// milestone.
8744    ///
8745    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8746    /// because the returning frame will.
8747    /// The elements of an array-like value, as a call argument list.
8748    ///
8749    /// `apply` accepts any array-like, not only a real array: the reference reads
8750    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8751    /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8752    ///
8753    /// Used by the paths that take a *length* from script data — the typed-array
8754    /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8755    /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8756    /// `RangeError` rather than a silently clamped count.
8757    pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8758        let number = self.to_js_number(value)?;
8759        if number.is_nan() {
8760            return Ok(0);
8761        }
8762        let number = number.trunc();
8763        if number < 0.0 || number > 9_007_199_254_740_991.0 {
8764            return Err(self.range_error("invalid length"));
8765        }
8766        Ok(number as usize)
8767    }
8768
8769    /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8770    /// other callers that take an argument list from script data.
8771    ///
8772    /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8773    /// constructor and `Array.from` need `ToIndex` instead (see
8774    /// [`Interp::to_index`]), which is why they do not go through here.
8775    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8776        let Some(object) = value.as_object().cloned() else {
8777            if value.is_nullish() {
8778                // `f.apply(this, null)` passes no arguments at all.
8779                return Ok(Vec::new());
8780            }
8781            return Err(self.type_error("createListFromArrayLike called on non-object"));
8782        };
8783        let length = match self.get_property(&object, "length")? {
8784            Some(length) => length.to_number(),
8785            None => 0.0,
8786        };
8787        if !length.is_finite() || length <= 0.0 {
8788            return Ok(Vec::new());
8789        }
8790        let length = (length as usize).min(1_000_000);
8791        let mut args = Vec::with_capacity(length);
8792        for index in 0..length {
8793            let element = self.get_property(&object, &index.to_string())?;
8794            args.push(element.unwrap_or(Value::Undefined));
8795        }
8796        Ok(args)
8797    }
8798
8799    /// Turn a call to a generator function into a generator object.
8800    ///
8801    /// The frame is built exactly as an ordinary call would build it, then detached and
8802    /// stored in the generator before any body instruction runs — which is what makes
8803    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8804    /// is `initial_yield`, the first instruction of every suspending body.
8805    pub fn new_generator(
8806        &mut self,
8807        function: Value,
8808        this: Value,
8809        args: Vec<Value>,
8810    ) -> JsResult<Value> {
8811        let Some(object) = function.as_object().cloned() else {
8812            return Err(self.type_error("not a generator function"));
8813        };
8814        let Some((code, env)) = bytecode_of(&object) else {
8815            return Err(self.type_error("not a generator function"));
8816        };
8817        let is_async = code.code.kind.is_async();
8818        self.push_frame(code, env, this, args, function)?;
8819        let frame = self.frames.pop().expect("push_frame just pushed it");
8820        // A fresh generator is *suspended at start*: the body has not run, so a
8821        // `return`/`throw` on it finishes without executing anything.
8822        let mut state = GeneratorState {
8823            frame: Some(frame),
8824            phase: GeneratorPhase::SuspendedStart,
8825            parked_on_await: false,
8826            parked_on_yield_star: false,
8827            requests: std::collections::VecDeque::new(),
8828            async_busy: false,
8829            is_async,
8830        };
8831        // Run to the first suspension. For a generator that is `initial_yield`, so no
8832        // body code runs; for a malformed body it would be the first `yield`.
8833        // An `async function*` answers an async generator: same coroutine, but its
8834        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8835        let default_proto = if is_async {
8836            self.realm
8837                .async_generator_proto
8838                .clone()
8839                .unwrap_or_else(|| self.realm.generator_proto.clone())
8840        } else {
8841            self.realm.generator_proto.clone()
8842        };
8843        // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8844        // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8845        // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8846        // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8847        let proto = self.generator_instance_proto(&object, default_proto)?;
8848        let generator = self.new_object(Some(proto));
8849        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8850            Ok(_) => {}
8851            Err(error) => return Err(error),
8852        }
8853        generator.with_mut(|data| {
8854            data.kind = ObjectKind::Generator(Box::new(state));
8855        });
8856        Ok(Value::Object(generator))
8857    }
8858
8859    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8860    ///
8861    /// Returns the `{value, done}` object itself rather than the pair, because a
8862    /// `yield*` suspension already has one — the inner iterator's own result — and the
8863    /// protocol says to hand that straight through rather than nest it.
8864    /// Advance a generator and report *why* it parked.
8865    ///
8866    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8867    /// "hand this value to the caller" — but an async generator does: an `await` has to
8868    /// settle before it can answer, while a `yield` is the answer.
8869    fn resume_generator_detailed(
8870        &mut self,
8871        generator: &Gc<JsObject>,
8872        kind: ResumeKind,
8873        value: Value,
8874    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8875        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8876            ObjectKind::Generator(state) => {
8877                let is_async = state.is_async;
8878                Some(std::mem::replace(
8879                    state.as_mut(),
8880                    GeneratorState {
8881                        frame: None,
8882                        phase: GeneratorPhase::Executing,
8883                        parked_on_await: false,
8884                        parked_on_yield_star: false,
8885                        requests: std::collections::VecDeque::new(),
8886                        // **Busy while the body runs**, so a `next()` called *from inside*
8887                        // the body queues instead of being served. §27.6.3.7
8888                        // `AsyncGeneratorResumeNext` returns immediately for the state
8889                        // "executing", and the request is served once the body suspends;
8890                        // with `false` here the re-entrant call found an empty frame and
8891                        // rejected (`request-queue-order-state-executing`).
8892                        async_busy: is_async,
8893                        is_async,
8894                    },
8895                ))
8896            }
8897            _ => None,
8898        }) else {
8899            return Err(self.type_error("not a generator"));
8900        };
8901        let result = self.step_generator(&mut state, kind, value);
8902        // Requests queued *while* the body ran live on the placeholder, because the real
8903        // state is out of the object for the duration. They have to be folded back in
8904        // before the placeholder is overwritten, or the promise they carry never settles.
8905        let queued = generator.with_mut(|data| match &mut data.kind {
8906            ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8907            _ => std::collections::VecDeque::new(),
8908        });
8909        state.requests.extend(queued);
8910        generator.with_mut(|data| {
8911            data.kind = ObjectKind::Generator(Box::new(state));
8912        });
8913        result
8914    }
8915
8916    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8917    ///
8918    /// Returns the `{value, done}` object itself rather than the pair, because a
8919    /// `yield*` suspension already has one — the inner iterator's own result — and the
8920    /// protocol says to hand that straight through rather than nest it.
8921    pub fn resume_generator(
8922        &mut self,
8923        generator: &Gc<JsObject>,
8924        kind: ResumeKind,
8925        value: Value,
8926    ) -> JsResult<Value> {
8927        let (value, done, ready, _reason) =
8928            self.resume_generator_detailed(generator, kind, value)?;
8929        if ready {
8930            return Ok(value);
8931        }
8932        self.iterator_result(value, done)
8933    }
8934
8935    /// `next`/`return`/`throw` on an async generator, which answer a promise.
8936    ///
8937    /// The body is the same coroutine a sync generator runs; what changes is that an
8938    /// `await` inside it has to settle before the method can answer, so the step is
8939    /// driven off the job queue rather than returning inline.
8940    pub fn resume_async_generator(
8941        &mut self,
8942        generator: &Gc<JsObject>,
8943        kind: ResumeKind,
8944        value: Value,
8945    ) -> JsResult<Value> {
8946        let promise = self.new_promise();
8947        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8948        // that order, and the second value must reach the *second* `yield`.
8949        let idle = generator.with_mut(|data| match &mut data.kind {
8950            ObjectKind::Generator(state) => {
8951                state.requests.push_back(AsyncRequest {
8952                    kind,
8953                    value,
8954                    promise: promise.clone(),
8955                });
8956                !state.async_busy
8957            }
8958            _ => false,
8959        });
8960        if idle {
8961            self.next_async_request(generator)?;
8962        }
8963        Ok(Value::Object(promise))
8964    }
8965
8966    /// Serve the front queued request, if the generator is free to run one.
8967    ///
8968    /// A finished generator answers from the queue without running anything:
8969    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8970    /// first, and `throw(e)` rejects.
8971    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8972        enum Front {
8973            Idle,
8974            Run(ResumeKind, Value, Gc<JsObject>),
8975            Finished(ResumeKind, Value, Gc<JsObject>),
8976        }
8977        let front = generator.with_mut(|data| match &mut data.kind {
8978            ObjectKind::Generator(state) => {
8979                let Some(request) = state.requests.front() else {
8980                    return Front::Idle;
8981                };
8982                // Busy means a request is still in flight — awaiting inside the body, not
8983                // finished. Serving another now would interleave two requests.
8984                if state.async_busy && state.phase != GeneratorPhase::Completed {
8985                    return Front::Idle;
8986                }
8987                let kind = request.kind;
8988                let value = request.value.clone();
8989                let promise = request.promise.clone();
8990                state.async_busy = true;
8991                if state.phase == GeneratorPhase::Completed {
8992                    Front::Finished(kind, value, promise)
8993                } else {
8994                    Front::Run(kind, value, promise)
8995                }
8996            }
8997            _ => Front::Idle,
8998        });
8999        match front {
9000            Front::Idle => Ok(()),
9001            Front::Run(kind, value, promise) => {
9002                self.step_async_generator(generator, &promise, kind, value)
9003            }
9004            Front::Finished(kind, value, promise) => match kind {
9005                ResumeKind::Throw => {
9006                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9007                }
9008                ResumeKind::Next | ResumeKind::Start => {
9009                    let result = self.iterator_result(Value::Undefined, true)?;
9010                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9011                }
9012                ResumeKind::Return => {
9013                    // `js_async_generator_completed_return`: the value is awaited before it
9014                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9015                    // finished generator answers `1`, not a promise.
9016                    let resolved = match self.promise_resolve_intrinsic(value) {
9017                        Ok(resolved) => resolved,
9018                        Err(Signal::Throw(reason)) => {
9019                            return self.settle_async_request(
9020                                generator,
9021                                &promise,
9022                                AsyncOutcome::Error(reason),
9023                            );
9024                        }
9025                        Err(other) => return Err(other),
9026                    };
9027                    let done = JsObject::function(
9028                        self.heap,
9029                        Some(self.realm.function_proto.clone()),
9030                        Callable::CompletedReturn {
9031                            generator: generator.clone(),
9032                            promise: promise.clone(),
9033                            rejected: false,
9034                        },
9035                    );
9036                    let failed = JsObject::function(
9037                        self.heap,
9038                        Some(self.realm.function_proto.clone()),
9039                        Callable::CompletedReturn {
9040                            generator: generator.clone(),
9041                            promise: promise.clone(),
9042                            rejected: true,
9043                        },
9044                    );
9045                    let Value::Object(resolved) = resolved else {
9046                        return self.settle_async_request(
9047                            generator,
9048                            &promise,
9049                            AsyncOutcome::Error(Value::Undefined),
9050                        );
9051                    };
9052                    self.perform_then(
9053                        &resolved,
9054                        Some(Value::Object(done)),
9055                        Some(Value::Object(failed)),
9056                    )?;
9057                    Ok(())
9058                }
9059            },
9060        }
9061    }
9062
9063    /// Settle the front request and start the next one.
9064    ///
9065    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9066    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9067    /// generator would strand every later request.
9068    fn settle_async_request(
9069        &mut self,
9070        generator: &Gc<JsObject>,
9071        promise: &Gc<JsObject>,
9072        outcome: AsyncOutcome,
9073    ) -> JsResult<()> {
9074        let settled = generator.with_mut(|data| match &mut data.kind {
9075            ObjectKind::Generator(state) => {
9076                let front = state.requests.front();
9077                debug_assert!(
9078                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9079                    "a request settled outside its turn"
9080                );
9081                state.requests.pop_front();
9082                state.async_busy = false;
9083                true
9084            }
9085            _ => false,
9086        });
9087        if settled {
9088            match outcome {
9089                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9090                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9091            }
9092        }
9093        self.next_async_request(generator)
9094    }
9095
9096    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9097    ///
9098    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9099    /// disposer runs **synchronously** — the reference starts it before returning, which
9100    /// a test can observe by logging after the call — and the rest follow once their
9101    /// predecessor settles.
9102    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9103        let promise = self.new_promise();
9104        // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9105        // any resource at all, because every `await using` resource has the async-dispose
9106        // hint — including the null/undefined ones that have nothing to call. If none of them
9107        // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9108        // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9109        // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9110        let needs_await = !resources.is_empty();
9111        let mut pairs = Vec::with_capacity(resources.len());
9112        for (value, method) in resources {
9113            let pair = self.new_array(vec![value, method]);
9114            pairs.push(Value::Object(pair));
9115        }
9116        let remaining = self.new_array(pairs);
9117        self.dispose_step(
9118            &remaining,
9119            &promise,
9120            Value::Uninitialized,
9121            false,
9122            needs_await,
9123        )?;
9124        Ok(Value::Object(promise))
9125    }
9126
9127    /// One link of the `disposeAsync` chain.
9128    ///
9129    /// Loops while the disposers finish synchronously, and parks on the first thenable it
9130    /// meets — pushing itself back in as the continuation, with the accumulated error
9131    /// carried along so a later failure can still be folded into the `SuppressedError`.
9132    fn dispose_step(
9133        &mut self,
9134        remaining: &Gc<JsObject>,
9135        promise: &Gc<JsObject>,
9136        mut error: Value,
9137        awaited: bool,
9138        needs_await: bool,
9139    ) -> JsResult<()> {
9140        loop {
9141            let length = remaining.array_length().unwrap_or(0);
9142            if length == 0 {
9143                // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9144                // still has to happen. Re-entering this same step past an already-fulfilled
9145                // promise is exactly one tick, and it keeps the folding of `error` in one place.
9146                if needs_await && !awaited {
9147                    let finished = self.new_array(Vec::new());
9148                    let thunk = JsObject::function(
9149                        self.heap,
9150                        Some(self.realm.function_proto.clone()),
9151                        Callable::DisposeStep {
9152                            remaining: finished.clone(),
9153                            promise: promise.clone(),
9154                            error,
9155                            rejected: false,
9156                            awaited: true,
9157                            needs_await: false,
9158                        },
9159                    );
9160                    let tick = self.promise_resolve_value(Value::Undefined)?;
9161                    if let Value::Object(tick) = tick {
9162                        self.perform_then(
9163                            &tick,
9164                            Some(Value::Object(thunk.clone())),
9165                            Some(Value::Object(thunk)),
9166                        )?;
9167                    }
9168                    return Ok(());
9169                }
9170                if matches!(error, Value::Uninitialized) {
9171                    self.fulfill_promise(promise, Value::Undefined);
9172                } else {
9173                    self.reject_promise(promise, error);
9174                }
9175                return Ok(());
9176            }
9177            let Some(Value::Object(pair)) = remaining
9178                .array_get(length - 1)
9179                .filter(|v| !matches!(v, Value::Hole))
9180            else {
9181                remaining.array_truncate(self.heap, length - 1);
9182                continue;
9183            };
9184            remaining.array_truncate(self.heap, length - 1);
9185            let value = pair.array_get(0).unwrap_or(Value::Undefined);
9186            let Some(Value::Object(method)) = pair.array_get(1) else {
9187                continue;
9188            };
9189            if !method.is_callable() {
9190                continue;
9191            }
9192            match self.call_value(Value::Object(method), value, Vec::new()) {
9193                Ok(result) => {
9194                    if !self.is_thenable(&result)? {
9195                        // Finished synchronously; the next disposer is the next iteration.
9196                        continue;
9197                    }
9198                    let awaited = match self.promise_resolve_value(result) {
9199                        Ok(awaited) => awaited,
9200                        Err(Signal::Throw(reason)) => {
9201                            self.reject_promise(promise, reason);
9202                            return Ok(());
9203                        }
9204                        Err(other) => return Err(other),
9205                    };
9206                    let Value::Object(awaited) = awaited else {
9207                        continue;
9208                    };
9209                    let ok = JsObject::function(
9210                        self.heap,
9211                        Some(self.realm.function_proto.clone()),
9212                        Callable::DisposeStep {
9213                            remaining: remaining.clone(),
9214                            promise: promise.clone(),
9215                            error: error.clone(),
9216                            rejected: false,
9217                            awaited: true,
9218                            needs_await,
9219                        },
9220                    );
9221                    let failed = JsObject::function(
9222                        self.heap,
9223                        Some(self.realm.function_proto.clone()),
9224                        Callable::DisposeStep {
9225                            remaining: remaining.clone(),
9226                            promise: promise.clone(),
9227                            error,
9228                            rejected: true,
9229                            awaited: true,
9230                            needs_await,
9231                        },
9232                    );
9233                    self.perform_then(
9234                        &awaited,
9235                        Some(Value::Object(ok)),
9236                        Some(Value::Object(failed)),
9237                    )?;
9238                    return Ok(());
9239                }
9240                Err(Signal::Throw(thrown)) => {
9241                    error = self.merge_dispose_error(thrown, error);
9242                }
9243                Err(other) => return Err(other),
9244            }
9245        }
9246    }
9247
9248    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9249    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9250        let Value::Object(object) = value else {
9251            return Ok(false);
9252        };
9253        Ok(matches!(
9254            self.get_property(object, "then")?,
9255            Some(Value::Object(then)) if then.is_callable()
9256        ))
9257    }
9258
9259    /// One step of an async generator, settling `promise` with an `{value, done}` result.
9260    fn step_async_generator(
9261        &mut self,
9262        generator: &Gc<JsObject>,
9263        promise: &Gc<JsObject>,
9264        kind: ResumeKind,
9265        value: Value,
9266    ) -> JsResult<()> {
9267        // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9268        // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9269        // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9270        // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9271        // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9272        // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9273        // out of the same read, one as a rejection and one as a rethrow.
9274        //
9275        // Narrow on purpose: only a value that is *already a promise* is inspected, so
9276        // nothing changes for `return 1` and the extra read is a plain data-property
9277        // lookup on the intrinsic case.
9278        if kind == ResumeKind::Return
9279            && let Value::Object(object) = &value
9280            && self.promise_state(object).is_some()
9281            && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9282        {
9283            return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9284        }
9285        let stepped = self.resume_generator_detailed(generator, kind, value);
9286        let (value, done, ready, reason) = match stepped {
9287            Ok(stepped) => stepped,
9288            Err(Signal::Throw(reason)) => {
9289                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9290            }
9291            Err(other) => return Err(other),
9292        };
9293        // Only an `await` has to wait before the method can answer.
9294        if !done && reason == Some(SuspendKind::Await) {
9295            let awaited = match self.promise_resolve_value(value) {
9296                Ok(awaited) => awaited,
9297                Err(Signal::Throw(reason)) => {
9298                    return self.settle_async_request(
9299                        generator,
9300                        promise,
9301                        AsyncOutcome::Error(reason),
9302                    );
9303                }
9304                Err(other) => return Err(other),
9305            };
9306            let Value::Object(awaited) = awaited else {
9307                return Ok(());
9308            };
9309            let resumed = JsObject::function(
9310                self.heap,
9311                Some(self.realm.function_proto.clone()),
9312                Callable::GeneratorResume {
9313                    generator: generator.clone(),
9314                    promise: promise.clone(),
9315                    kind: ResumeKind::Next,
9316                },
9317            );
9318            let raised = JsObject::function(
9319                self.heap,
9320                Some(self.realm.function_proto.clone()),
9321                Callable::GeneratorResume {
9322                    generator: generator.clone(),
9323                    promise: promise.clone(),
9324                    kind: ResumeKind::Throw,
9325                },
9326            );
9327            self.perform_then(
9328                &awaited,
9329                Some(Value::Object(resumed)),
9330                Some(Value::Object(raised)),
9331            )?;
9332            return Ok(());
9333        }
9334        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9335        // completes it — both arrive as the settled value rather than as the promise
9336        // object. A plain value skips the round trip, which is also what keeps `yield 1`
9337        // from costing an extra tick.
9338        let awaits_value = self.is_thenable(&value)?;
9339        if awaits_value {
9340            // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9341            // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9342            // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9343            // no `PromiseResolve` appears, so that path keeps the shortcut.
9344            let awaited = match if done {
9345                self.promise_resolve_intrinsic(value)
9346            } else {
9347                self.promise_resolve_value(value)
9348            } {
9349                Ok(awaited) => awaited,
9350                Err(Signal::Throw(reason)) => {
9351                    return self.settle_async_request(
9352                        generator,
9353                        promise,
9354                        AsyncOutcome::Error(reason),
9355                    );
9356                }
9357                Err(other) => return Err(other),
9358            };
9359            let Value::Object(awaited) = awaited else {
9360                return Ok(());
9361            };
9362            // A rejected yield throws *at the yield* inside the body, so the rejection
9363            // resumes the generator rather than the method's promise.
9364            let answer = JsObject::function(
9365                self.heap,
9366                Some(self.realm.function_proto.clone()),
9367                Callable::YieldResult {
9368                    generator: generator.clone(),
9369                    promise: promise.clone(),
9370                    done,
9371                },
9372            );
9373            let raise = JsObject::function(
9374                self.heap,
9375                Some(self.realm.function_proto.clone()),
9376                Callable::GeneratorResume {
9377                    generator: generator.clone(),
9378                    promise: promise.clone(),
9379                    kind: ResumeKind::Throw,
9380                },
9381            );
9382            self.perform_then(
9383                &awaited,
9384                Some(Value::Object(answer)),
9385                Some(Value::Object(raise)),
9386            )?;
9387            return Ok(());
9388        }
9389        let result = if ready {
9390            // `yield*` handed back the inner iterator's own result object.
9391            value
9392        } else {
9393            self.iterator_result(value, done)?
9394        };
9395        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9396    }
9397
9398    /// The `{value, done}` object an iterator method answers with.
9399    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9400        let result = self.new_object(Some(self.realm.object_proto.clone()));
9401        result.define_data("value", value);
9402        result.define_data("done", Value::Bool(done));
9403        Ok(Value::Object(result))
9404    }
9405
9406    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9407    fn step_generator(
9408        &mut self,
9409        state: &mut GeneratorState,
9410        kind: ResumeKind,
9411        value: Value,
9412    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9413        match state.phase {
9414            GeneratorPhase::Executing => {
9415                return Err(self.type_error("cannot invoke a running generator"));
9416            }
9417            GeneratorPhase::Completed => {
9418                // A finished generator answers every resumption without running.
9419                return Ok(match kind {
9420                    ResumeKind::Throw => return Err(Signal::Throw(value)),
9421                    ResumeKind::Return => (value, true, false, None),
9422                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9423                });
9424            }
9425            GeneratorPhase::SuspendedStart => {
9426                if kind != ResumeKind::Next && kind != ResumeKind::Start {
9427                    // The body never started, so there is nothing to unwind or return
9428                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9429                    state.frame = None;
9430                    state.phase = GeneratorPhase::Completed;
9431                    return Ok(match kind {
9432                        ResumeKind::Throw => return Err(Signal::Throw(value)),
9433                        _ => (value, true, false, None),
9434                    });
9435                }
9436            }
9437            GeneratorPhase::SuspendedYield => {}
9438        }
9439
9440        let Some(mut frame) = state.frame.take() else {
9441            return Ok((Value::Undefined, true, false, None));
9442        };
9443        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9444        // number that says which method resumed it; the emitted `if_false` branches on
9445        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9446        let mut raised = None;
9447        match kind {
9448            ResumeKind::Next | ResumeKind::Start => {
9449                if state.phase == GeneratorPhase::SuspendedYield {
9450                    frame.stack.push(value);
9451                    // An `await` resumes with its value alone; only a `yield` gets the
9452                    // magic number that says which of `next`/`return` resumed it.
9453                    if !state.parked_on_await {
9454                        frame.stack.push(Value::Int(RESUME_NEXT));
9455                    }
9456                }
9457            }
9458            ResumeKind::Return => {
9459                // A `return` on a not-yet-started generator is handled above, so this is
9460                // always a real resumption.
9461                frame.stack.push(value);
9462                frame.stack.push(Value::Int(RESUME_RETURN));
9463            }
9464            ResumeKind::Throw => {
9465                // At a `yield*` the exception is *data* for the delegation: the compiled
9466                // code resumes with the value and magic `2` and calls the inner iterator's
9467                // `throw`. Everywhere else it is raised at the suspension point, so the
9468                // body's own handler sees it.
9469                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9470                    frame.stack.push(value);
9471                    frame.stack.push(Value::Int(RESUME_THROW));
9472                } else {
9473                    raised = Some(value);
9474                }
9475            }
9476        }
9477        state.phase = GeneratorPhase::Executing;
9478
9479        let depth = self.frames.len();
9480        self.frames.push(frame);
9481        // A `throw` unwinds from where the frame parked, exactly as if the exception had
9482        // happened at the `yield`.
9483        if let Some(exception) = raised {
9484            if self.catch_here(exception.clone()).is_none() {
9485                self.pop_frame();
9486                state.phase = GeneratorPhase::Completed;
9487                return Err(Signal::Throw(exception));
9488            }
9489        }
9490
9491        // Only the generator's *own* frame ends the generator. The body may call ordinary
9492        // functions, and those push frames of their own: a `Step::Return` from one of them
9493        // is a nested call finishing, not the generator completing. Miscounting that is
9494        // silent — the generator reports the callee's value as its own result and marks
9495        // itself done — so the depth comparison is load-bearing, not defensive.
9496        let own_frame = depth + 1;
9497        loop {
9498            match self.step() {
9499                Ok(Step::Continue) => {}
9500                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9501                    let mut frame = self.frames.pop().expect("a frame is live");
9502                    // `yield` left the value on the stack; `initial_yield` left nothing.
9503                    let yielded = if reason == SuspendKind::Initial {
9504                        Value::Undefined
9505                    } else {
9506                        frame.stack.pop().unwrap_or(Value::Undefined)
9507                    };
9508                    state.frame = Some(frame);
9509                    state.parked_on_await = reason == SuspendKind::Await;
9510                    state.parked_on_yield_star =
9511                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9512                    state.phase = if reason == SuspendKind::Initial {
9513                        GeneratorPhase::SuspendedStart
9514                    } else {
9515                        GeneratorPhase::SuspendedYield
9516                    };
9517                    // `yield*` hands the inner iterator's own result object straight
9518                    // back, so the caller sees one `{value, done}` rather than a nested
9519                    // one — which is why the third field says "already a result".
9520                    return Ok((
9521                        yielded,
9522                        false,
9523                        reason == SuspendKind::YieldStar,
9524                        Some(reason),
9525                    ));
9526                }
9527                Ok(Step::Suspend(_)) => {
9528                    // A `yield` in a frame other than the generator's would mean a
9529                    // generator body entered as an ordinary call, which
9530                    // `call_or_push` prevents.
9531                    self.unwind_to(depth);
9532                    state.phase = GeneratorPhase::Completed;
9533                    return Err(Signal::Throw(self.make_error(
9534                        "InternalError",
9535                        "a generator body ran as an ordinary call",
9536                    )));
9537                }
9538                Ok(Step::Return(value)) => {
9539                    self.pop_frame();
9540                    if self.frames.len() > depth {
9541                        // A nested call finished: hand the value back to its caller and
9542                        // keep running the generator body.
9543                        self.frames
9544                            .last_mut()
9545                            .expect("a caller is live")
9546                            .stack
9547                            .push(value);
9548                        continue;
9549                    }
9550                    state.phase = GeneratorPhase::Completed;
9551                    // The reference closes the generator's closure variables here; ours
9552                    // live in cells the frame owned, which the drop below releases.
9553                    return Ok((value, true, false, None));
9554                }
9555                Err(Signal::Throw(exception)) => {
9556                    // The frame that threw gets the first chance to catch, exactly as in
9557                    // the ordinary call loop; a frame above the generator's is popped and
9558                    // the exception carries on down.
9559                    let exception = exception;
9560                    loop {
9561                        if self.frames.len() <= depth {
9562                            // The generator's own frame is gone, so nothing here caught it.
9563                            state.phase = GeneratorPhase::Completed;
9564                            return Err(Signal::Throw(exception));
9565                        }
9566                        if self.catch_here(exception.clone()).is_some() {
9567                            break;
9568                        }
9569                        self.pop_frame();
9570                    }
9571                }
9572                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9573            }
9574        }
9575    }
9576
9577    /// Pop frames until `depth` are left, keeping their buffers.
9578    fn unwind_to(&mut self, depth: usize) {
9579        while self.frames.len() > depth {
9580            self.pop_frame();
9581        }
9582    }
9583    fn call_or_push(
9584        &mut self,
9585        callee: Value,
9586        this: Value,
9587        args: Vec<Value>,
9588    ) -> JsResult<Option<Value>> {
9589        if let Value::Object(function) = &callee
9590            && let Some((code, env)) = bytecode_of(function)
9591        {
9592            // Calling a generator function does not run anything: it captures the
9593            // arguments in a frame and hands back the generator object.
9594            if code.code.kind.is_generator() {
9595                return self.new_generator(callee, this, args).map(Some);
9596            }
9597            // An async function answers a promise and runs its body as a coroutine, so it
9598            // takes the same path as a plain call into it.
9599            if code.code.kind.is_async() {
9600                return self.new_async_function(callee, this, args).map(Some);
9601            }
9602            self.push_frame(code, env, this, args, callee)?;
9603            return Ok(None);
9604        }
9605        self.call_value(callee, this, args).map(Some)
9606    }
9607
9608    /// `new callee(args)`.
9609    ///
9610    /// A constructor differs from a plain call in three ways: it gets a fresh object
9611    /// as `this` whose prototype is the constructor's `prototype` property, its
9612    /// return value is *replaced* by that object unless it returns an object itself,
9613    /// and a native constructor is expected to initialise the object it is given
9614    /// rather than build one.
9615    pub fn construct(
9616        &mut self,
9617        callee: Value,
9618        new_target: Value,
9619        args: Vec<Value>,
9620    ) -> JsResult<Value> {
9621        // `new` on a bound function constructs its *target*, prepending the arguments
9622        // the bind fixed and ignoring the bound `this` — a bound function is a
9623        // constructor only when its target is one, and `new` always makes a fresh
9624        // object of the target's prototype rather than reusing the bound receiver.
9625        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9626        // ran the body with `this === null` and threw on `this.x = a`.
9627        let mut callee = callee;
9628        let mut new_target = new_target;
9629        let mut args = args;
9630        loop {
9631            let Some(object) = callee.as_object().cloned() else {
9632                return Err(Signal::Throw(
9633                    self.make_error("TypeError", "not a constructor"),
9634                ));
9635            };
9636            // A proxy of a function constructs through its `construct` trap, and the
9637            // trap's answer is the result directly — no fresh object is made here.
9638            if object.proxy_state().is_some() {
9639                return match self.proxy_construct(&object, args, &new_target)? {
9640                    Some(result) => Ok(result),
9641                    None => Err(Signal::Throw(
9642                        self.make_error("TypeError", "proxy target is not a constructor"),
9643                    )),
9644                };
9645            }
9646            // A generator function has no `[[Construct]]`, and the reference names it in
9647            // the message: `new (function* G(){})()` reports "G is not a constructor".
9648            if object.with(|data| match &data.kind {
9649                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9650                    code.code.kind.is_generator()
9651                }
9652                _ => false,
9653            }) {
9654                let name = object
9655                    .own_property("name")
9656                    .and_then(|property| property.value)
9657                    .map(|value| value.to_js_string())
9658                    .unwrap_or_default();
9659                return Err(Signal::Throw(
9660                    self.make_error("TypeError", &format!("{name} is not a constructor")),
9661                ));
9662            }
9663            let bound = object.with(|data| match &data.kind {
9664                ObjectKind::Function(Callable::Bound {
9665                    target,
9666                    args: leading,
9667                    ..
9668                }) => Some((target.clone(), leading.clone())),
9669                _ => None,
9670            });
9671            let Some((target, leading)) = bound else {
9672                // Not a bound function, so this object is the callee. §7.2.4
9673                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9674                // refusals above cover only the built-ins the reference also refuses by
9675                // name. Everything else — a method, an arrow, an async function — has no
9676                // `[[Construct]]` either, and answering "yes" here made
9677                // `new (Array.prototype.map)` build an object instead of throwing.
9678                if !object.is_constructor() {
9679                    let name = object
9680                        .own_property("name")
9681                        .and_then(|property| property.value)
9682                        .map(|value| value.to_js_string())
9683                        .unwrap_or_default();
9684                    return Err(Signal::Throw(
9685                        self.make_error("TypeError", &format!("{name} is not a constructor")),
9686                    ));
9687                }
9688                break;
9689            };
9690            let mut all = leading;
9691            all.extend(args);
9692            args = all;
9693            // A bound function that is its own `new.target` stands in for its target:
9694            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9695            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9696            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9697                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9698                _ => false,
9699            };
9700            if same_wrapper {
9701                new_target = target.clone();
9702            }
9703            callee = target;
9704        }
9705        let Value::Object(function) = &callee else {
9706            unreachable!("the loop above only breaks on an object");
9707        };
9708        // The fresh object's prototype comes from `new.target`, not from the callee: a
9709        // derived constructor reaches here through `super()`, and the instance must be a
9710        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9711        // an object inheriting `D.prototype` rather than `C.prototype`.
9712        let prototype_source = match new_target.as_object() {
9713            Some(target) => target.clone(),
9714            None => function.clone(),
9715        };
9716        // A native constructor builds its own instance, through `new_ctor_instance`, once it
9717        // has validated its arguments. Pre-building one here would read
9718        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9719        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9720        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9721        let is_native = function.native_creates_own_instance();
9722        let this = if is_native {
9723            Value::Undefined
9724        } else {
9725            let prototype = self.get_property(&prototype_source, "prototype")?;
9726            let prototype = match prototype {
9727                Some(Value::Object(proto)) => Some(proto),
9728                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9729                // object, the answer is the realm's *intrinsic* prototype for this
9730                // constructor, not `%Object.prototype%`.
9731                _ => {
9732                    // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9733                    // and that is a `TypeError` for a revoked proxy. Without it, `new
9734                    // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9735                    // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9736                    // trap, so it is already revoked when this fallback runs.
9737                    if prototype_source.proxy_state().is_some() {
9738                        self.proxy_parts(&prototype_source)?;
9739                    }
9740                    let fallback = self.get_property(function, "prototype")?;
9741                    match fallback {
9742                        Some(Value::Object(proto)) => Some(proto),
9743                        _ => Some(self.realm.object_proto.clone()),
9744                    }
9745                }
9746            };
9747            Value::Object(self.new_object(prototype))
9748        };
9749        // `new.target` inside the body is the constructor that was written, so a bound
9750        // function's target sees itself rather than the bound wrapper.
9751        //
9752        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9753        // `?`, so assigning `None` after the call would be skipped and the failed
9754        // `new.target` would stay visible to every later native call. The symptom was a
9755        // native constructor refusing a plain call — `var s = Symbol(); new
9756        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9757        // "FinalizationRegistry is not a constructor".
9758        let outer_new_target = self.pending_new_target.replace(new_target);
9759        let callee = callee.clone();
9760        let result = self.call_value(callee, this.clone(), args);
9761        self.pending_new_target = outer_new_target;
9762        let result = result?;
9763        // A constructor that returns an object overrides `this`; any other return value
9764        // (including `undefined`) is ignored — **except** in a derived constructor, where
9765        // §15.7.1 step 12 makes a non-object return a `TypeError`
9766        // (`Function/internals/Construct/derived-return-val`).
9767        let derived = function.with(|data| match &data.kind {
9768            ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9769                code.code.is_derived_constructor
9770            }
9771            _ => false,
9772        });
9773        Ok(match result {
9774            Value::Object(_) => result,
9775            // A bare `return;` answers `undefined`, which is **legal** even in a derived
9776            // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9777            Value::Undefined => this,
9778            _ if derived => {
9779                return Err(Signal::Throw(self.make_error(
9780                    "TypeError",
9781                    "derived constructor may only return an object or undefined",
9782                )));
9783            }
9784            _ => this,
9785        })
9786    }
9787
9788    /// `new.target` for the call currently being made.
9789    ///
9790    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9791    /// it as `this`), but a *host* constructor that builds its own instance is handed
9792    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9793    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9794    /// it here.
9795    ///
9796    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9797    /// receives for a plain call.
9798    pub fn current_new_target(&self) -> Value {
9799        self.active_new_target.clone()
9800    }
9801
9802    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9803    ///
9804    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9805    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9806    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9807        let constructor = self.realm.errors.get("AggregateError").cloned();
9808        let Some(constructor) = constructor else {
9809            return self.make_error("AggregateError", message);
9810        };
9811        let list = self.new_array(errors);
9812        match self.construct(
9813            Value::Object(constructor.clone()),
9814            Value::Object(constructor),
9815            vec![Value::Object(list), self.string(message)],
9816        ) {
9817            Ok(value) => value,
9818            // A user could have replaced `AggregateError` with something that throws; the
9819            // engine still owes the caller a rejection, so it falls back rather than
9820            // turning `Promise.any`'s rejection into a throw.
9821            Err(_) => self.make_error("AggregateError", message),
9822        }
9823    }
9824
9825    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9826    ///
9827    /// The error classes themselves arrive with the builtins milestone; what
9828    /// matters here is that the thrown value stringifies the way a script printing
9829    /// the caught value expects.
9830    ///
9831    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9832    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9833    /// rely on when they print a caught value.
9834    pub fn make_error(&self, name: &str, message: &str) -> Value {
9835        let proto = self
9836            .realm
9837            .errors
9838            .get(name)
9839            .map(|constructor| self.prototype_of(constructor))
9840            .unwrap_or_else(|| self.realm.error_proto.clone());
9841        let error = self.new_object(Some(proto));
9842        // `name` and `message` are own properties of the instance, which is what
9843        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9844        // `Error`.
9845        error.define(
9846            "name",
9847            Property::with_attributes(self.string(name), true, false),
9848        );
9849        error.define(
9850            "message",
9851            Property::with_attributes(self.string(message), true, false),
9852        );
9853        // The internal class, which is what tells a printer this is an error rather than a
9854        // plain object with `name` and `message` properties. The constructor path sets it
9855        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9856        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9857        // literally `"Error"` in both places — the *name* is read from `name`, which is why
9858        // a `RangeError` still prints as `RangeError`.
9859        self.internal_set(&error, "_class", self.string("Error"));
9860        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9861        // answered `false` from `Error.isError` while a constructed one answered `true`,
9862        // because only the constructor set the slot. The reference answers `true` for both
9863        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9864        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9865        // tests `typeof stack === "string"` to decide on a trailing newline, so every
9866        // engine-thrown error lost its blank line.
9867        self.internal_set(&error, "_error_data", Value::Bool(true));
9868        // The trace is captured where the error is *made*, which is where the reference
9869        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9870        // way out, so a caught engine error already has its stack even if the handler
9871        // never rethrows it.
9872        self.add_stack(&error);
9873        Value::Object(error)
9874    }
9875
9876    /// Give an error object its `stack` property, from the current frame stack.
9877    ///
9878    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9879    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9880    /// `stack` a script set, is not rewritten.
9881    pub fn add_stack(&self, object: &Gc<JsObject>) {
9882        self.add_stack_skipping(object, 0);
9883    }
9884
9885    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9886    ///
9887    /// An `Error` constructor passes 1: the reference builds those traces with
9888    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9889    /// constructor itself, while a `RangeError` raised inside `toISOString` does
9890    /// report `at toISOString (native)`.
9891    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9892        if object.has_own("stack") {
9893            return;
9894        }
9895        // The trace is *captured* here but not installed as a property: `stack` is an
9896        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9897        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9898        // is kept in a hidden slot and the getter materialises it on first read.
9899        //
9900        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9901        // shows it — this is the same discipline `_error_data` and `_class` follow.
9902        let trace = self.stack_trace_skipping(skip);
9903        let text = self.string(trace);
9904        self.internal_set(object, "_stack_trace", text);
9905    }
9906
9907    /// The function object currently being called, if any.
9908    ///
9909    /// A native function is a bare `fn` pointer, so it cannot capture which class
9910    /// it belongs to; it reads that from the callee instead. This is also what a
9911    /// stack trace would use.
9912    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9913        match &self.frames.last()?.callee {
9914            Value::Object(object) => Some(object.clone()),
9915            _ => None,
9916        }
9917    }
9918
9919    /// The `prototype` property of a constructor, falling back to
9920    /// `Object.prototype` for anything that is not shaped like one.
9921    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9922        constructor
9923            .own_property("prototype")
9924            .and_then(|property| property.value)
9925            .and_then(|value| value.as_object().cloned())
9926            .unwrap_or_else(|| self.realm.object_proto.clone())
9927    }
9928
9929    /// Throw a `TypeError` carrying `message`.
9930    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9931        Signal::Throw(self.make_error("TypeError", message.as_ref()))
9932    }
9933
9934    /// Throw a `RangeError` carrying `message`.
9935    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9936        Signal::Throw(self.make_error("RangeError", message.as_ref()))
9937    }
9938
9939    /// A `ReferenceError`, as the value to throw.
9940    ///
9941    /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
9942    /// and its siblings report a `ReferenceError` there, which is what
9943    /// `adopt|defer|move/throws-if-disposed` assert.
9944    pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
9945        Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
9946    }
9947
9948    /// The `ReferenceError` a read of an uninitialised binding raises.
9949    /// The name of the binding `slot` refers to, for an error message.
9950    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9951        match kind {
9952            VarSlot::Loc => self
9953                .frame()
9954                .code
9955                .code
9956                .vars
9957                .get(slot)
9958                .map(|v| v.name.clone()),
9959            VarSlot::Closure => self
9960                .frame()
9961                .code
9962                .code
9963                .closure_vars
9964                .get(slot)
9965                .map(|c| c.name.clone()),
9966        }
9967        .unwrap_or_default()
9968    }
9969
9970    /// Whether `slot` names a `const` binding, which rejects every store after its
9971    /// initialiser.
9972    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9973        match kind {
9974            VarSlot::Loc => self
9975                .frame()
9976                .code
9977                .code
9978                .vars
9979                .get(slot)
9980                .is_some_and(|v| v.is_const),
9981            VarSlot::Closure => self
9982                .frame()
9983                .code
9984                .code
9985                .closure_vars
9986                .get(slot)
9987                .is_some_and(|c| c.is_const),
9988        }
9989    }
9990
9991    /// The `TypeError` a store to a `const` binding raises.
9992    ///
9993    /// `const` is enforced here rather than at compile time because the binding can be
9994    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9995    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9996    /// both halves of what "checked store" means: the dead zone is over, and the
9997    /// binding is writable.
9998    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9999        let name = self.binding_name(slot, kind);
10000        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10001    }
10002
10003    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10004        let name = match kind {
10005            VarSlot::Loc => self
10006                .frame()
10007                .code
10008                .code
10009                .vars
10010                .get(slot)
10011                .map(|v| v.name.clone()),
10012            VarSlot::Closure => self
10013                .frame()
10014                .code
10015                .code
10016                .closure_vars
10017                .get(slot)
10018                .map(|c| c.name.clone()),
10019        }
10020        .unwrap_or_default();
10021        Signal::Throw(self.make_error(
10022            "ReferenceError",
10023            &format!("cannot access '{name}' before initialization"),
10024        ))
10025    }
10026
10027    fn throw_reference(&self, name: &str) -> Signal {
10028        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10029    }
10030
10031    // -- the instruction loop -----------------------------------------------
10032
10033    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10034    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10035    // measured at 16% of a tight arithmetic loop's total time.
10036    #[inline(always)]
10037    fn step(&mut self) -> JsResult<Step> {
10038        // The instruction is already decoded (see [`crate::insn`]), so this is an index
10039        // and a `Copy` read rather than a table lookup plus a width switch. Only the
10040        // borrow lives across the boundary; nothing is cloned.
10041        // **One** borrow of the frame: fetch the record, then advance in the same scope.
10042        // The obvious version borrowed it three times (`last` to read, `last_mut` to
10043        // write, and once more inside the handler), and each is a bounds check plus an
10044        // `Option` unwrap — on the one path every instruction takes.
10045        let Some((insn, next)) = ({
10046            let frame = self
10047                .frames
10048                .last_mut()
10049                .expect("step() is only called with a live frame");
10050            // Past the last instruction is a normal return: the compiler ends a function
10051            // with `return`, and a jump to the end of a block lands here.
10052            let insn = frame.insns().get(frame.pc).copied();
10053            match insn {
10054                None => None,
10055                Some(insn) => {
10056                    // A fused record stands for the next few instructions, so the next
10057                    // `pc` is its width ahead — the instructions it replaces are never
10058                    // dispatched. `at` is the byte offset a stack trace reports; it stays
10059                    // an offset because the line table is keyed by bytes.
10060                    frame.at = insn.offset as usize;
10061                    frame.pc += insn.width();
10062                    Some((insn, frame.pc))
10063                }
10064            }
10065        }) else {
10066            return Ok(Step::Return(Value::Undefined));
10067        };
10068        self.check_memory()?;
10069        self.check_interrupt()?;
10070        if insn.fused == crate::insn::Fused::None {
10071            self.execute_instruction(insn.op, insn.a, insn.b, next)
10072        } else {
10073            self.execute_fused(insn)
10074        }
10075    }
10076
10077    /// Run a fused instruction: several bytecode instructions in one dispatch.
10078    ///
10079    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10080    /// it cannot throw and cannot allocate — and anything else falls back to the real
10081    /// instructions, in their real order, so an exception leaves the operand stack
10082    /// exactly as it would have been.
10083    #[inline]
10084    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10085        use crate::insn::Fused;
10086        let slot = insn.a as usize;
10087        match insn.fused {
10088            // `x = k`: `push k; put_loc x`.
10089            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10090            // `x += k`: `get_loc x; push k; add; put_loc x`.
10091            Fused::AddImmLoc => {
10092                let delta = insn.b as i32;
10093                match self.get_loc(slot) {
10094                    Value::Int(left) => {
10095                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10096                        // that built two `Value`s, called a function, and matched on them
10097                        // again to reach this same `checked_add`. It is the innermost
10098                        // operation of every accumulator in every program.
10099                        let answer = match left.checked_add(delta) {
10100                            Some(sum) => Value::Int(sum),
10101                            None => Value::Float(left as f64 + delta as f64),
10102                        };
10103                        self.put_loc(slot, answer);
10104                    }
10105                    other => {
10106                        self.push(other);
10107                        self.push(Value::Int(delta));
10108                        self.binary_add()?;
10109                        let value = self.pop();
10110                        self.put_loc(slot, value);
10111                    }
10112                }
10113            }
10114            // `x += "literal"` and `x += y`: the two shapes that can append in place.
10115            Fused::AddAtomLoc => {
10116                let text = self.atom_wtf8(insn.b as usize);
10117                let right = self.string_wtf8(text);
10118                self.add_into_loc(slot, right)?;
10119            }
10120            Fused::AddLocLoc => {
10121                let source = (insn.a & 0xFFFF) as usize;
10122                let target = (insn.a >> 16) as usize;
10123                let right = self.get_loc(source);
10124                self.add_into_loc(target, right)?;
10125            }
10126            Fused::AddArgLoc => {
10127                let source = (insn.a & 0xFFFF) as usize;
10128                let target = (insn.a >> 16) as usize;
10129                let right = self.get_arg(source);
10130                self.add_into_loc(target, right)?;
10131            }
10132            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10133            Fused::PostIncLoc => match self.get_loc(slot) {
10134                Value::Int(left) => {
10135                    let answer = match left.checked_add(1) {
10136                        Some(sum) => Value::Int(sum),
10137                        None => Value::Float(left as f64 + 1.0),
10138                    };
10139                    self.put_loc(slot, answer);
10140                }
10141                other => {
10142                    self.push(other);
10143                    let raw = self.pop();
10144                    let (old, updated) = self.advance_numeric(raw, true)?;
10145                    self.push(old);
10146                    self.push(updated);
10147                    let value = self.pop();
10148                    self.put_loc(slot, value);
10149                    self.pop();
10150                }
10151            },
10152            // `if (!(x < arg)) goto target`: a loop header.
10153            //
10154            // The comparison is computed rather than replayed on the operand stack. That
10155            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10156            // that throws: the effects happen in the same order, and a handler truncates
10157            // the stack down to its marker, so the intermediate values are unobservable.
10158            Fused::LtLocArgJump => {
10159                let loc = (insn.a >> 16) as usize;
10160                let arg = (insn.a & 0xFFFF) as usize;
10161                let left = self.get_loc(loc);
10162                let right = self.get_arg(arg);
10163                let taken = match (&left, &right) {
10164                    (Value::Int(left), Value::Int(right)) => !(left < right),
10165                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10166                };
10167                if taken {
10168                    self.frame_mut().pc = insn.b as usize;
10169                }
10170            }
10171            // `i < k` in a loop header, where `k` is an integer literal.
10172            Fused::LtLocImmJump => {
10173                let left = self.get_loc(insn.a as usize);
10174                let right = Value::Int(insn.imm as i32);
10175                let taken = match &left {
10176                    Value::Int(left) => !(*left < insn.imm as i32),
10177                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10178                };
10179                if taken {
10180                    self.frame_mut().pc = insn.b as usize;
10181                }
10182            }
10183            Fused::None => unreachable!("only called for a fused record"),
10184        }
10185        Ok(Step::Continue)
10186    }
10187
10188    /// Run records that cannot call script, cannot throw and cannot change frames.
10189    ///
10190    /// Returns `Some(value)` when the function ran off the end of its instructions (a
10191    /// normal return), and `None` when it stopped in front of an instruction the slow path
10192    /// has to handle — `pc` is written back either way, so `step` resumes at the right
10193    /// place.
10194    ///
10195    /// **The invariant is the whole point.** Every arm here is restricted to work that
10196    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10197    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10198    /// that the memory limit has to see. An opcode whose operands turn out to need any of
10199    /// that **stops the loop** instead of trying, so the slow path gets the instruction
10200    /// untouched and with its operands still on the stack. That is why the fallback is a
10201    /// `break` and not a duplicated slow arm: a second implementation of the same
10202    /// semantics is how a wrong answer gets in with no test noticing.
10203    ///
10204    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10205    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10206    fn run_fast(&mut self) -> JsResult<Option<Value>> {
10207        use crate::insn::Fused;
10208        // The outer loop exists only so a `Call` can come back through here: once a
10209        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10210        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10211        // frame. Re-entering re-reads both from whichever frame is now on top. Every
10212        // other exit from the inner loop returns, so this costs one loop per call.
10213        'outer: loop {
10214            // One reference-count bump per *slow* instruction (a call, an allocation, a
10215            // property access), never one per instruction — that distinction is worth
10216            // two orders of magnitude and was measured as such.
10217            let (code, mut pc) = {
10218                let frame = self.frame();
10219                (frame.code.clone(), frame.pc)
10220            };
10221            let insns = &code.insns;
10222            loop {
10223                let Some(insn) = insns.get(pc).copied() else {
10224                    self.frame_mut().pc = pc;
10225                    return Ok(Some(Value::Undefined));
10226                };
10227                match insn.fused {
10228                    // `x = k`
10229                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10230                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10231                    // object — stops the loop so `binary_add` can decide.
10232                    Fused::AddImmLoc => {
10233                        let slot = insn.a as usize;
10234                        let delta = insn.b as i32;
10235                        let Value::Int(left) = self.get_loc(slot) else {
10236                            return Ok(self.stop(pc));
10237                        };
10238                        let sum = match left.checked_add(delta) {
10239                            Some(sum) => Value::Int(sum),
10240                            None => Value::Float(left as f64 + delta as f64),
10241                        };
10242                        self.put_loc(slot, sum);
10243                    }
10244                    // `x += "literal"` / `x += y`: the operand is a string, so the append
10245                    // either allocates one or grows one. Both are the slow path's business;
10246                    // the fusion's job is only to make the *slot* the sole owner, which is what
10247                    // `execute_fused` needs and what `get_loc` alone destroys.
10248                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10249                        return Ok(self.stop(pc));
10250                    }
10251                    // `x++` on an integer, old value dropped.
10252                    Fused::PostIncLoc => {
10253                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10254                        // value is read in place and overwritten in place, so the reference
10255                        // count it held is released by the same assignment that stores the
10256                        // new one. `get_loc` plus `put_loc` did two borrows, two table
10257                        // lookups and a clone, and this arm is the whole body of a counting
10258                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10259                        let slot = insn.a as usize;
10260                        let frame = self.frames.last_mut().expect("a frame is live");
10261                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10262                        let target = if cell < 0 {
10263                            frame.locals.get_mut(slot)
10264                        } else {
10265                            None
10266                        };
10267                        let Some(target) = target else {
10268                            return Ok(self.stop(pc));
10269                        };
10270                        let Value::Int(left) = *target else {
10271                            return Ok(self.stop(pc));
10272                        };
10273                        *target = match left.checked_add(1) {
10274                            Some(sum) => Value::Int(sum),
10275                            None => Value::Float(left as f64 + 1.0),
10276                        };
10277                    }
10278                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
10279                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10280                    // bound stayed small integers.
10281                    Fused::LtLocArgJump => {
10282                        let loc = (insn.a >> 16) as usize;
10283                        let arg = (insn.a & 0xFFFF) as usize;
10284                        // One borrow for both slots: this arm *is* the whole loop of a
10285                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
10286                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
10287                        // `dispatch:empty-loop`.
10288                        let (left, right) = {
10289                            let frame = self.frame();
10290                            (frame.read_loc(loc), frame.read_arg(arg))
10291                        };
10292                        // Heavily measured: the bound is very often a `Float` even when the
10293                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10294                        // `JSON.parse` or a division is one — so requiring both sides to be
10295                        // `Int` sent every iteration of those loops down the slow path. The
10296                        // comparison below is the same one `relational` makes for two numbers.
10297                        if !is_number(&left) || !is_number(&right) {
10298                            return Ok(self.stop(pc));
10299                        }
10300                        // `if_false` branches on the comparison being false, which is **not**
10301                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10302                        // `>=` is also false and would keep it running forever. Clippy wants the
10303                        // negation folded; that would be a wrong answer.
10304                        let ordered = left.to_number() < right.to_number();
10305                        let take_branch = !ordered;
10306                        if take_branch {
10307                            pc = insn.b as usize;
10308                            continue;
10309                        }
10310                    }
10311                    // The same header with a literal bound: `if (!(x < k)) goto target`.
10312                    // The bound is an immediate, so only the counter needs a type test.
10313                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
10314                    Fused::LtLocImmJump => {
10315                        let left = self.get_loc(insn.a as usize);
10316                        if !is_number(&left) {
10317                            return Ok(self.stop(pc));
10318                        }
10319                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10320                        if take_branch {
10321                            pc = insn.b as usize;
10322                            continue;
10323                        }
10324                    }
10325                    Fused::None => match insn.op {
10326                        // -- branches ---------------------------------------------------
10327                        // A jump is an assignment now, because the target is an instruction
10328                        // index. No arithmetic, no resolution table.
10329                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10330                            let target = insn.a as usize;
10331                            // A **back-edge** is a loop, and it is the only place an
10332                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
10333                            // to a jump to itself and never leaves this loop, so the
10334                            // per-instruction checks in `step` never run. That is exactly the
10335                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
10336                            // nothing to a `for(;;){}` until it did, which is what
10337                            // `tests/c/embed.c` is for.
10338                            //
10339                            // Polling here rather than on every instruction in this loop is
10340                            // also the reference's choice (`OP_goto` calls
10341                            // `js_poll_interrupts`), and it costs one compare per branch
10342                            // instead of one decrement per instruction.
10343                            if target <= pc {
10344                                self.frame_mut().pc = target;
10345                                self.check_memory()?;
10346                                self.check_interrupt()?;
10347                            }
10348                            pc = target;
10349                            continue;
10350                        }
10351                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10352                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10353                            let taken = self.pop().to_boolean();
10354                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10355                            if taken == want {
10356                                pc = insn.a as usize;
10357                                continue;
10358                            }
10359                        }
10360                        // -- slot access -------------------------------------------------
10361                        // A load's slot is already an operand (see `insn::implicit_operand`);
10362                        // a captured one goes through its cell, which runs no script.
10363                        Opcode::GetLoc
10364                        | Opcode::GetLoc8
10365                        | Opcode::GetLoc0
10366                        | Opcode::GetLoc1
10367                        | Opcode::GetLoc2
10368                        | Opcode::GetLoc3 => {
10369                            let value = self.get_loc(insn.a as usize);
10370                            self.push(value);
10371                        }
10372                        Opcode::PutLoc
10373                        | Opcode::PutLoc8
10374                        | Opcode::PutLoc0
10375                        | Opcode::PutLoc1
10376                        | Opcode::PutLoc2
10377                        | Opcode::PutLoc3 => {
10378                            let value = self.pop();
10379                            self.put_loc(insn.a as usize, value);
10380                        }
10381                        Opcode::GetArg
10382                        | Opcode::GetArg0
10383                        | Opcode::GetArg1
10384                        | Opcode::GetArg2
10385                        | Opcode::GetArg3 => {
10386                            let value = self.get_arg(insn.a as usize);
10387                            self.push(value);
10388                        }
10389                        Opcode::PutArg
10390                        | Opcode::PutArg0
10391                        | Opcode::PutArg1
10392                        | Opcode::PutArg2
10393                        | Opcode::PutArg3 => {
10394                            let value = self.pop();
10395                            self.put_arg(insn.a as usize, value);
10396                        }
10397                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
10398                        // for why a non-hole own element is exactly the slow path's answer.
10399                        // The two operands are *peeked*, so a miss leaves the stack as the
10400                        // slow path expects to find it.
10401                        Opcode::GetArrayEl => {
10402                            // One lookup, not two. The guard used `if …is_some()` and the arm
10403                            // then called it again to get the value — two `peek`s, two
10404                            // `array_get`s and two `Value` clones for one element.
10405                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
10406                            // double call was the first version of the `get_field` fast path.
10407                            let Some(value) = self.fast_array_get() else {
10408                                return Ok(self.stop(pc));
10409                            };
10410                            // `a[i]` consumes both operands and leaves the element in their
10411                            // place: one `truncate` and one write, no `pop`/`push` pair.
10412                            let frame = self.frame_mut();
10413                            frame.stack.truncate(frame.stack.len() - 2);
10414                            frame.stack.push(value);
10415                        }
10416                        // `a[i] = v` on a dense array with an integer index: see
10417                        // `fast_array_set` for why the whole store is one step.
10418                        Opcode::PutArrayEl if self.fast_array_set() => {}
10419                        // `o.x` resolved from the inline cache without leaving the loop.
10420                        //
10421                        // The cache is keyed by `(receiver identity, atom, site)` and a
10422                        // monomorphic read re-validates the same chain every iteration, so
10423                        // each one used to cost a `stop(pc)` — a write of `pc` into the
10424                        // frame, a return out of this loop, a re-dispatch through `step` and
10425                        // a re-entry. `property:monomorphic` spent 18% in
10426                        // `read_field_cached` and 21% in `push`, both across that boundary.
10427                        //
10428                        // The site is `pc + width`, which is exactly the `next` the slow arm
10429                        // passes — the two must agree or every fast lookup misses and
10430                        // re-records the same entry forever.
10431                        //
10432                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10433                        // slow arm finds the receiver where it expects it.
10434                        // `name` resolved from the global-variable cache inside the loop.
10435                        //
10436                        // Same shape as `get_field` above and for the same reason: `get_var`
10437                        // was not in the fast loop, so reading a global — which `fib` does
10438                        // once per recursive call, for its own name — cost a `stop(pc)`, a
10439                        // return out of the loop, a `step` re-dispatch and a re-entry, before
10440                        // `get_global` even started its `scopes_are_plain` checks.
10441                        //
10442                        // Everything here is exactly `get_global`'s first branch: not lexical,
10443                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
10444                        // and lets the slow arm decide.
10445                        Opcode::GetVar => {
10446                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10447                                return Ok(self.stop(pc));
10448                            };
10449                            self.push(value);
10450                        }
10451                        Opcode::GetField | Opcode::GetField2 => {
10452                            let Some(value) =
10453                                self.fast_field_get(insn.a as usize, pc + insn.width())
10454                            else {
10455                                return Ok(self.stop(pc));
10456                            };
10457                            if insn.op == Opcode::GetField2 {
10458                                // `get_field2` keeps the receiver for the `call_method` that
10459                                // follows.
10460                                self.push(value);
10461                            } else {
10462                                // `get_field` replaces the receiver, so this is one store over
10463                                // the top slot rather than a `pop` and a `push`: the length
10464                                // never changes, so neither `Vec` arm has a capacity check or a
10465                                // drop to run beyond the one the overwrite itself does.
10466                                let frame = self.frame_mut();
10467                                match frame.stack.last_mut() {
10468                                    Some(slot) => *slot = value,
10469                                    None => return Ok(self.stop(pc)),
10470                                }
10471                            }
10472                        }
10473                        // -- constants ---------------------------------------------------
10474                        Opcode::PushMinus1
10475                        | Opcode::Push0
10476                        | Opcode::Push1
10477                        | Opcode::Push2
10478                        | Opcode::Push3
10479                        | Opcode::Push4
10480                        | Opcode::Push5
10481                        | Opcode::Push6
10482                        | Opcode::Push7
10483                        | Opcode::PushI8
10484                        | Opcode::PushI16
10485                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10486                        // -- stack shuffling ---------------------------------------------
10487                        Opcode::Drop => {
10488                            self.pop();
10489                        }
10490                        // -- arithmetic on two integers ----------------------------------
10491                        //
10492                        // The operands are *looked at* before they are popped, so a non-integer
10493                        // pair leaves the stack exactly as the slow path expects to find it.
10494                        Opcode::Add if self.numeric_pair() => {
10495                            let right = self.pop();
10496                            let left = self.pop();
10497                            // Exactly [`add_numbers`], which is what the slow arm reaches.
10498                            let answer = match (&left, &right) {
10499                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10500                                    Some(sum) => Value::Int(sum),
10501                                    None => Value::Float(*a as f64 + *b as f64),
10502                                },
10503                                _ => Value::Float(left.to_number() + right.to_number()),
10504                            };
10505                            self.push(answer);
10506                        }
10507                        Opcode::Sub
10508                        | Opcode::And
10509                        | Opcode::Or
10510                        | Opcode::Xor
10511                        | Opcode::Shl
10512                        | Opcode::Sar
10513                        | Opcode::Shr
10514                            if self.numeric_pair() =>
10515                        {
10516                            let right = self.pop();
10517                            let left = self.pop();
10518                            let answer =
10519                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
10520                            self.push(answer);
10521                        }
10522                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10523                            if self.numeric_pair() =>
10524                        {
10525                            let right = self.pop();
10526                            let left = self.pop();
10527                            let answer = self
10528                                .relational(insn.op, left, right)
10529                                .expect("numbers cannot throw");
10530                            self.push(answer);
10531                        }
10532                        // -- calls -------------------------------------------------------
10533                        //
10534                        // A plain call: `callee(arg0, …, argN) -> result`.
10535                        //
10536                        // This arm exists because of one measurement. `call:recursion` had
10537                        // **20.4% of its profile in `execute_instruction`** — the *slow*
10538                        // executor — and `fib`'s recursive call is the only thing in that
10539                        // function which is not a fast arm. Every call therefore left this
10540                        // loop via `stop()`, went through `step()`'s dispatch and
10541                        // `execute_instruction`'s match over every opcode, and came back here
10542                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10543                        //
10544                        // Two things make it safe to do here rather than only in the slow path:
10545                        //
10546                        // * the caller's `pc` is stored *before* the call, which is what
10547                        //   `step` does too — so when the callee returns, the caller resumes
10548                        //   after the call and not at it;
10549                        // * `check_memory` runs, because `step` calls it once per instruction
10550                        //   and a call allocates a frame, its locals and its cells. Skipping
10551                        //   the checkpoint here would let a `--memory-limit` script overshoot
10552                        //   by one call per instruction.
10553                        Opcode::Call
10554                        | Opcode::Call0
10555                        | Opcode::Call1
10556                        | Opcode::Call2
10557                        | Opcode::Call3 => {
10558                            let argc = self.argc_operand(insn.op, insn.a);
10559                            let next = pc + insn.width();
10560                            {
10561                                let frame = self
10562                                    .frames
10563                                    .last_mut()
10564                                    .expect("run_fast() is only called with a live frame");
10565                                // `at` is what a stack trace reports for this frame, so a throw
10566                                // inside the callee has to see the call site and not whatever
10567                                // the last `stop()` left there.
10568                                frame.at = insn.offset as usize;
10569                                frame.pc = next;
10570                            }
10571                            self.check_memory()?;
10572                            self.check_interrupt()?;
10573                            let args = self.pop_n(argc);
10574                            let callee = self.pop();
10575                            // A plain call has no receiver; the callee decides what to do with
10576                            // `undefined` (a sloppy function substitutes the global object).
10577                            if let Some(result) =
10578                                self.call_or_push(callee, Value::Undefined, args)?
10579                            {
10580                                // Native, host, generator, async, bound — no frame was pushed,
10581                                // so this loop is still describing the right function. `pc`
10582                                // is advanced by the loop tail like every other arm; only the
10583                                // frame's copy had to be written here, and it already was.
10584                                self.push(result);
10585                            } else {
10586                                // A bytecode callee: its frame is on top now, and `insns` and
10587                                // `pc` both belong to the caller. Start over on the new frame.
10588                                continue 'outer;
10589                            }
10590                        }
10591                        // -- return ------------------------------------------------------
10592                        Opcode::Return => {
10593                            let value = self.pop();
10594                            self.frame_mut().pc = pc + insn.width();
10595                            return Ok(Some(value));
10596                        }
10597                        Opcode::ReturnUndef => {
10598                            self.frame_mut().pc = pc + insn.width();
10599                            return Ok(Some(Value::Undefined));
10600                        }
10601                        // Everything else needs the slow path.
10602                        _ => return Ok(self.stop(pc)),
10603                    },
10604                }
10605                pc += insn.width();
10606            }
10607        }
10608    }
10609
10610    /// Whether the top two operand-stack values are both numbers.
10611    ///
10612    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10613    /// cannot run script, so the arm may not throw and may not change frames.
10614    fn numeric_pair(&self) -> bool {
10615        is_number(&self.peek(0)) && is_number(&self.peek(1))
10616    }
10617
10618    /// `a[i]` for a dense array and an integer index, without the string round trip.
10619    ///
10620    /// The slow path answers this by turning `i` into a string (`propkey` →
10621    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10622    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10623    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10624    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10625    /// without even the cheap `Int` formatting.
10626    ///
10627    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10628    /// unambiguously the one the slow path would give:
10629    ///
10630    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10631    ///   `2^32-1` is the length, not an index),
10632    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10633    ///   typed array or an ordinary object, all of which have their own rules),
10634    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10635    ///   starts walking the prototype chain, and `a[i]` on a hole must find
10636    ///   `Array.prototype[i]` if it exists rather than `undefined`.
10637    ///
10638    /// The last condition is the one that makes this safe rather than merely fast: an own
10639    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10640    /// `get_var` answered from the global-variable cache, or `None`.
10641    ///
10642    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10643    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10644    /// records nothing — the slow arm is about to walk the chain and record it.
10645    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10646        let frame = self.frame();
10647        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10648        // "Lexical" is presence in the realm's table, not the closure var's flag: a
10649        // `GlobalRef` forwarded through a nested function has its flags cleared.
10650        if self.realm.globals.contains_key(name) {
10651            return None;
10652        }
10653        if !self.scopes_are_plain() {
10654            return None;
10655        }
10656        let object = &self.realm.global;
10657        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10658        let cached = self.global_cache[site].as_ref()?;
10659        if !object.upgrades_to(&cached.object) {
10660            return None;
10661        }
10662        object.data_property_at(cached.index, name)
10663    }
10664
10665    /// `o.x` answered entirely from the inline cache, or `None`.
10666    ///
10667    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10668    /// about to do exactly that and recording it twice would rebuild the chain for every
10669    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10670    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10671    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10672        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10673        // an object receiver is a reference-count bump that the answer never needs.
10674        let frame = self.frame();
10675        let object = frame.stack.last()?;
10676        let Value::Object(target) = object else {
10677            return None;
10678        };
10679        // A proxy traps the lookup, so no cache entry ever describes it.
10680        if target.proxy_state().is_some() {
10681            return None;
10682        }
10683        let key = frame.code.atom_keys.get(atom)?;
10684        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10685        if cached.key != *key {
10686            return None;
10687        }
10688        Self::cached_hit(target, cached)
10689    }
10690
10691    fn fast_array_get(&self) -> Option<Value> {
10692        let Value::Int(index) = self.peek(0) else {
10693            return None;
10694        };
10695        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10696        // set for an `i32`.
10697        if index < 0 {
10698            return None;
10699        }
10700        let Value::Object(object) = self.peek(1) else {
10701            return None;
10702        };
10703        match object.array_get(index as usize) {
10704            Some(value) if !matches!(value, Value::Hole) => Some(value),
10705            _ => None,
10706        }
10707    }
10708
10709    /// `a[i] = v` on a dense array with an integer index, as one store.
10710    ///
10711    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10712    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10713    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10714    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10715    /// reference at the time it was measured (14.7x).
10716    ///
10717    /// Every condition here is one the slow path would also have to satisfy before
10718    /// storing into the element vector:
10719    ///
10720    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10721    ///   accepts as an index;
10722    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10723    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10724    ///   one inside a recorded descriptor, reports `false` and the caller stops.
10725    ///
10726    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10727    /// writes the own element too once `array_set` says it did.
10728    fn fast_array_set(&mut self) -> bool {
10729        // Every test runs *before* anything is popped: a refusal has to leave the stack
10730        // exactly as the slow path expects to find it. Popping first and reporting the
10731        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10732        // then ran the slow path with nothing to write.
10733        let Value::Int(index) = self.peek(1) else {
10734            return false;
10735        };
10736        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10737        if index < 0 {
10738            return false;
10739        }
10740        // Only a real array: a typed array's elements live in its buffer, a string-like
10741        // object has no element vector, and `array_set` on either does nothing.
10742        let Value::Object(object) = self.peek(2) else {
10743            return false;
10744        };
10745        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10746            return false;
10747        }
10748        // A non-extensible array reports `false` here, but the *slow* path has to decide
10749        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10750        // that with the key and the stack still intact.
10751        if !object.is_extensible() {
10752            return false;
10753        }
10754        // Inside the logical length, so the store cannot change `length`. Combined with
10755        // extensibility above, the only growth left for `array_set` is filling a hole in
10756        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10757        // shape this fast path exists for. A store past the length would grow the array,
10758        // and whether that is allowed is the slow path's question.
10759        if index as usize >= object.array_length().unwrap_or(0) {
10760            return false;
10761        }
10762        // Only an *own element* can take the inline store. A hole is not an own property,
10763        // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10764        // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10765        // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10766        // the one case this path used to swallow.
10767        //
10768        // The cost is small: `array:indexed` only reads after a 64-element fill, and
10769        // `array:push` appends past the length, which this path already refused.
10770        if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10771        {
10772            return false;
10773        }
10774        // The bound `array_set` refuses past. Checking it here keeps that arm from having
10775        // to report a failure after the operands are gone.
10776        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10777            return false;
10778        }
10779        let value = self.pop();
10780        self.pop();
10781        self.pop();
10782        object.array_store(self.heap, index as usize, value)
10783    }
10784
10785    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10786    fn stop(&mut self, pc: usize) -> Option<Value> {
10787        self.frame_mut().pc = pc;
10788        None
10789    }
10790
10791    fn push(&mut self, value: Value) {
10792        self.frame_mut().stack.push(value);
10793    }
10794
10795    fn pop(&mut self) -> Value {
10796        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10797    }
10798
10799    fn pop_n(&mut self, count: usize) -> Vec<Value> {
10800        let frame = self.frame_mut();
10801        let start = frame.stack.len().saturating_sub(count);
10802        frame.stack.split_off(start)
10803    }
10804
10805    fn peek(&self, back: usize) -> Value {
10806        let frame = self.frame();
10807        frame
10808            .stack
10809            .get(frame.stack.len().wrapping_sub(1 + back))
10810            .cloned()
10811            .unwrap_or(Value::Undefined)
10812    }
10813
10814    #[allow(clippy::too_many_lines)]
10815    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10816        use Opcode::*;
10817        match op {
10818            // -- constants and stack shuffling -----------------------------
10819            Nop => {}
10820            PushMinus1 => self.push(Value::Int(-1)),
10821            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10822                let value = match op {
10823                    Push0 => 0,
10824                    Push1 => 1,
10825                    Push2 => 2,
10826                    Push3 => 3,
10827                    Push4 => 4,
10828                    Push5 => 5,
10829                    Push6 => 6,
10830                    _ => 7,
10831                };
10832                self.push(Value::Int(value));
10833            }
10834            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10835            PushBigintI32 => {
10836                // The immediate form of a `BigInt` literal; the reference has the same
10837                // split between this and a constant-pool entry.
10838                let value = crate::bigint::BigInt::from_i64(a as i64);
10839                self.push(self.bigint(value));
10840            }
10841            PushTrue => self.push(Value::Bool(true)),
10842            PushFalse => self.push(Value::Bool(false)),
10843            PushEmptyString => self.push(self.string("")),
10844            Undefined => self.push(Value::Undefined),
10845            Null => self.push(Value::Null),
10846            Object => {
10847                let proto = self.realm.object_proto.clone();
10848                self.push(Value::Object(self.new_object(Some(proto))));
10849            }
10850            PushThis => {
10851                let this = self.frame().this.clone();
10852                self.push(this);
10853            }
10854            PushConst | PushConst8 => {
10855                let value = self.constant(a as usize)?;
10856                self.push(value);
10857            }
10858            PushAtomValue => {
10859                let text = self.atom_wtf8(a as usize);
10860                self.push(self.string_wtf8(text));
10861            }
10862            Dup => {
10863                let value = self.peek(0);
10864                self.push(value);
10865            }
10866            Dup2 => {
10867                // `a b -> a b a b`
10868                let b = self.peek(0);
10869                let a = self.peek(1);
10870                self.push(a);
10871                self.push(b);
10872            }
10873            Dup3 => {
10874                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10875                // prototype and key while reading the current value through them.
10876                let c = self.peek(0);
10877                let b = self.peek(1);
10878                let a = self.peek(2);
10879                self.push(a);
10880                self.push(b);
10881                self.push(c);
10882            }
10883            Swap => {
10884                // `a b -> b a`
10885                let bottom = self.pop();
10886                let top = self.pop();
10887                self.push(bottom);
10888                self.push(top);
10889            }
10890            Perm3 => {
10891                // `a b c -> b a c`, the reference's reordering for a spread method
10892                // call: `obj func array` becomes the `func this array` that `apply`
10893                // takes.
10894                let c = self.pop();
10895                let b = self.pop();
10896                let a = self.pop();
10897                self.push(b);
10898                self.push(a);
10899                self.push(c);
10900            }
10901            Dup1 => {
10902                let value = self.peek(1);
10903                self.push(value);
10904            }
10905            Drop => {
10906                self.pop();
10907            }
10908            Nip => {
10909                // `a b -> b`
10910                let top = self.pop();
10911                self.pop();
10912                self.push(top);
10913            }
10914            Perm4 => {
10915                // `obj prop a b -> a obj prop b`, the reference's reordering for a
10916                // postfix update of a computed element: it puts the *old* value
10917                // underneath the receiver and key so `put_array_el` can consume them
10918                // and leave the old value as the expression's result.
10919                let d = self.pop();
10920                let c = self.pop();
10921                let b = self.pop();
10922                let a = self.pop();
10923                self.push(c);
10924                self.push(a);
10925                self.push(b);
10926                self.push(d);
10927            }
10928            Insert2 => {
10929                // `obj a -> a obj a`
10930                let value = self.pop();
10931                let object = self.pop();
10932                self.push(value.clone());
10933                self.push(object);
10934                self.push(value);
10935            }
10936            Insert3 => {
10937                // `obj prop a -> a obj prop a`
10938                let value = self.pop();
10939                let key = self.pop();
10940                let object = self.pop();
10941                self.push(value.clone());
10942                self.push(object);
10943                self.push(key);
10944                self.push(value);
10945            }
10946            Insert4 => {
10947                // `this obj prop a -> a this obj prop a`
10948                //
10949                // `put_super_value` consumes all four and yields nothing, so the copy
10950                // underneath is what leaves the assignment an expression value.
10951                let value = self.pop();
10952                let key = self.pop();
10953                let object = self.pop();
10954                let receiver = self.pop();
10955                self.push(value.clone());
10956                self.push(receiver);
10957                self.push(object);
10958                self.push(key);
10959                self.push(value);
10960            }
10961            Swap2 => {
10962                // `a b c d -> c d a b`
10963                let d = self.pop();
10964                let c = self.pop();
10965                let b = self.pop();
10966                let a = self.pop();
10967                self.push(c);
10968                self.push(d);
10969                self.push(a);
10970                self.push(b);
10971            }
10972            Rot3l => {
10973                // `x a b -> a b x`
10974                let b = self.pop();
10975                let a = self.pop();
10976                let x = self.pop();
10977                self.push(a);
10978                self.push(b);
10979                self.push(x);
10980            }
10981            Rot3r => {
10982                // `a b c -> c a b`
10983                let c = self.pop();
10984                let b = self.pop();
10985                let a_value = self.pop();
10986                self.push(c);
10987                self.push(a_value);
10988                self.push(b);
10989            }
10990
10991            Rest => {
10992                // `...rest` in a parameter list: the arguments from index `a` on, as a
10993                // real array. It takes nothing off the stack — the arguments are in the
10994                // frame, not on it.
10995                let frame = self.frame();
10996                let from = a as usize;
10997                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10998                let array = self.new_array(collected);
10999                self.push(Value::Object(array));
11000            }
11001
11002            // -- slots ------------------------------------------------------
11003            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11004                let slot = self.slot_operand(op, a);
11005                let value = self.get_loc(slot);
11006                self.push(value);
11007            }
11008            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11009                let slot = self.slot_operand(op, a);
11010                let value = self.pop();
11011                self.put_loc(slot, value);
11012            }
11013            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11014                let slot = self.slot_operand(op, a);
11015                let value = self.pop();
11016                self.put_loc(slot, value.clone());
11017                self.push(value);
11018            }
11019            // The `_check` forms are the temporal dead zone: they throw when the
11020            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11021            // *reads*, so only the two writes may pop — mishandling that quietly
11022            // consumes the value the caller pushed just before.
11023            GetLocCheck => {
11024                let slot = self.slot_operand(op, a);
11025                let value = self.get_loc(slot);
11026                if matches!(value, Value::Uninitialized) {
11027                    return Err(self.dead_zone(slot, VarSlot::Loc));
11028                }
11029                self.push(value);
11030            }
11031            PutLocCheck | SetLocCheck => {
11032                let slot = self.slot_operand(op, a);
11033                let value = self.pop();
11034                if matches!(value, Value::Uninitialized) {
11035                    return Err(self.dead_zone(slot, VarSlot::Loc));
11036                }
11037                // The initialiser goes through `put_loc`, not this, so any store that
11038                // reaches here is a later assignment — which a `const` refuses.
11039                if self.is_read_only(slot, VarSlot::Loc) {
11040                    return Err(self.read_only(slot, VarSlot::Loc));
11041                }
11042                if op == SetLocCheck {
11043                    self.put_loc(slot, value.clone());
11044                    self.push(value);
11045                } else {
11046                    self.put_loc(slot, value);
11047                }
11048            }
11049            PutLocCheckInit => {
11050                // The one store that *initialises* a lexical slot: `this` in a derived
11051                // constructor, which only exists after `super()` has run. A second
11052                // initialisation is the error the reference reports as
11053                // "'this' can be initialized only once".
11054                let slot = self.slot_operand(op, a);
11055                let value = self.pop();
11056                if !matches!(self.get_loc(slot), Value::Uninitialized) {
11057                    return Err(Signal::Throw(self.make_error(
11058                        "ReferenceError",
11059                        "'this' can be initialized only once",
11060                    )));
11061                }
11062                self.put_loc(slot, value);
11063            }
11064            CheckCtor => {
11065                // A class constructor may only run under `new`, which is what makes
11066                // `class A {}; A()` a TypeError.
11067                if matches!(self.frame().new_target, Value::Undefined) {
11068                    return Err(Signal::Throw(self.make_error(
11069                        "TypeError",
11070                        "class constructors must be invoked with 'new'",
11071                    )));
11072                }
11073            }
11074            InitCtor => {
11075                // The body a derived class gets when it declares no constructor:
11076                // forward every argument to the parent constructor, keeping `new.target`.
11077                if matches!(self.frame().new_target, Value::Undefined) {
11078                    return Err(Signal::Throw(self.make_error(
11079                        "TypeError",
11080                        "class constructors must be invoked with 'new'",
11081                    )));
11082                }
11083                let Some(callee) = self.current_callee() else {
11084                    return Err(Signal::Throw(
11085                        self.make_error("TypeError", "no constructor to inherit from"),
11086                    ));
11087                };
11088                let parent = callee.proto().map_or(Value::Null, Value::Object);
11089                let new_target = self.frame().new_target.clone();
11090                let args = self.frame().passed().to_vec();
11091                let result = self.construct(parent, new_target, args)?;
11092                self.push(result);
11093            }
11094            SetLocUninitialized => {
11095                let slot = self.slot_operand(op, a);
11096                self.put_loc(slot, Value::Uninitialized);
11097            }
11098            CloseLoc => {
11099                // "Close" a binding: give it a *fresh* cell holding the current
11100                // value. Closures created before this point keep the old cell and the
11101                // ones created after see the new one, which is what makes every
11102                // iteration of `for (let i ...)` capture its own `i`, and what freezes
11103                // a block-scoped binding when the block ends.
11104                //
11105                // Clearing the slot instead (which this used to do) broke both: a
11106                // closure over a captured block variable read `undefined`, and a loop
11107                // terminated after one iteration.
11108                let slot = self.slot_operand(op, a);
11109                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11110                if index >= 0 {
11111                    let current = self.frame().cells[index as usize].get();
11112                    let fresh = self.new_cell(current);
11113                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11114                        *cell = fresh;
11115                    }
11116                }
11117            }
11118            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11119                let slot = self.slot_operand(op, a);
11120                let value = self.get_arg(slot);
11121                self.push(value);
11122            }
11123            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11124                let slot = self.slot_operand(op, a);
11125                let value = self.pop();
11126                self.put_arg(slot, value);
11127            }
11128            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11129                let slot = self.slot_operand(op, a);
11130                let value = self.pop();
11131                self.put_arg(slot, value.clone());
11132                self.push(value);
11133            }
11134
11135            // -- closure variables ------------------------------------------
11136            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11137                let slot = self.slot_operand(op, a);
11138                // A name a direct `eval` created shadows the binding the compiler chose.
11139                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11140                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11141                // and only a runtime lookup can know that.
11142                if let Some(cell) = self.eval_created_local(slot) {
11143                    self.push(cell.get());
11144                    return self.step();
11145                }
11146                let value = self.cell_value(slot)?;
11147                self.push(value);
11148            }
11149            GetVarRefCheck => {
11150                let slot = self.slot_operand(op, a);
11151                let value = self.cell_value(slot)?;
11152                if matches!(value, Value::Uninitialized) {
11153                    return Err(self.dead_zone(slot, VarSlot::Closure));
11154                }
11155                self.push(value);
11156            }
11157            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11158                let slot = self.slot_operand(op, a);
11159                let value = self.pop();
11160                if let Some(cell) = self.eval_created_local(slot) {
11161                    cell.set(value);
11162                    return self.step();
11163                }
11164                // Same rule as `PutLocCheck`: a checked store to a captured binding
11165                // refuses a `const` once its initialiser has run.
11166                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
11167                    return Err(self.read_only(slot, VarSlot::Closure));
11168                }
11169                self.set_cell(slot, value)?;
11170            }
11171            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11172                let slot = self.slot_operand(op, a);
11173                let value = self.pop();
11174                if let Some(cell) = self.eval_created_local(slot) {
11175                    cell.set(value.clone());
11176                    self.push(value);
11177                    return self.step();
11178                }
11179                self.set_cell(slot, value.clone())?;
11180                self.push(value);
11181            }
11182
11183            // -- globals ----------------------------------------------------
11184            GetVar => {
11185                let value = self.get_global(a as usize)?;
11186                self.push(value);
11187            }
11188            GetVarUndef => {
11189                let slot = a as usize;
11190                // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11191                // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11192                // and `GetValue`s it, and only the unresolvable case is forgiven).
11193                //
11194                // The distinction is made by asking whether a binding exists at all: a name
11195                // in the realm's lexical table is declared, so a `ReferenceError` from
11196                // reading it is the dead zone talking. Swallowing every error made
11197                // `eval("typeof x; let x;")` print `"undefined"`.
11198                let declared = self.realm.globals.contains_key(&self.global_name(slot));
11199                let value = if declared {
11200                    self.get_global(slot)?
11201                } else {
11202                    match self.get_global(slot) {
11203                        Ok(value) => value,
11204                        Err(Signal::Throw(_)) => Value::Undefined,
11205                        Err(other) => return Err(other),
11206                    }
11207                };
11208                self.push(value);
11209            }
11210            DeleteVar => {
11211                // `delete name` for a name that is not a declared binding. A lexical
11212                // global lives in the reference table and cannot be deleted; anything
11213                // reachable only as a property of the global object is *implicit* —
11214                // `x = 1` with no declaration — and goes away if it is configurable,
11215                // which is what `delete` on an implicit global answers.
11216                let name = self.atom_text(a as usize);
11217                let global = self.realm.global.clone();
11218                let deleted = if self.realm.globals.contains_key(&name) {
11219                    false
11220                } else if global.own_property(&name).is_some() {
11221                    self.delete_property(&global, &name)?
11222                } else {
11223                    true
11224                };
11225                self.push(Value::Bool(deleted));
11226            }
11227            PutVar => {
11228                let value = self.pop();
11229                self.put_global(a as usize, value)?;
11230            }
11231            PutVarInit => {
11232                let slot = a as usize;
11233                let value = self.pop();
11234                self.init_global(slot, value)?;
11235            }
11236
11237            // -- arithmetic -------------------------------------------------
11238            Add => self.binary_add()?,
11239            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11240                let raw_right = self.pop();
11241                let raw_left = self.pop();
11242                // BigInt arithmetic is a separate path, and not only for the type of the
11243                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
11244                // rather than a silent conversion.
11245                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
11246                    let left = self.primitive_of(raw_left)?;
11247                    let right = self.primitive_of(raw_right)?;
11248                    let value = self.bigint_arithmetic(op, left, right)?;
11249                    self.push(value);
11250                } else {
11251                    let right = self.numeric(raw_right)?;
11252                    let left = self.numeric(raw_left)?;
11253                    self.push(arithmetic(op, left, right)?);
11254                }
11255            }
11256            Neg => {
11257                let raw = self.pop();
11258                match raw {
11259                    // A bigint negates exactly, however wide it is.
11260                    Value::BigInt(big) => {
11261                        let negated = big.negate();
11262                        self.push(self.bigint(negated));
11263                    }
11264                    other => {
11265                        let value = self.numeric(other)?;
11266                        self.push(negate(value));
11267                    }
11268                }
11269            }
11270            Plus => {
11271                let value = self.pop();
11272                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11273                // unary plus is defined to produce a *number*, which a bigint cannot
11274                // become without loss. It used to fall through to `NaN`.
11275                if matches!(value, Value::BigInt(_)) {
11276                    return Err(self.type_error("cannot convert bigint to number"));
11277                }
11278                let numeric = self.numeric_of(value)?;
11279                self.push(numeric);
11280            }
11281            Inc => {
11282                let raw = self.pop();
11283                let (_, updated) = self.advance_numeric(raw, true)?;
11284                self.push(updated);
11285            }
11286            Dec => {
11287                let raw = self.pop();
11288                let (_, updated) = self.advance_numeric(raw, false)?;
11289                self.push(updated);
11290            }
11291            PostInc | PostDec => {
11292                // `x -> x x+1`: the *new* value ends up on top, so the store the
11293                // compiler emits right after (`put_var`) writes the incremented
11294                // one, while the old value stays underneath for the expression's
11295                // own result. Getting this backwards makes `i++` a no-op, which
11296                // turns `while (i < 3)` into an infinite loop.
11297                let raw = self.pop();
11298                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11299                self.push(old);
11300                self.push(updated);
11301            }
11302            Not => {
11303                let raw = self.pop();
11304                match raw {
11305                    // `~x` on a bigint is `-x - 1`, exact at any width.
11306                    Value::BigInt(big) => {
11307                        let inverted = big.bitnot();
11308                        self.push(self.bigint(inverted));
11309                    }
11310                    other => {
11311                        let value = self.numeric(other)?;
11312                        self.push(Value::Int(!value.to_int32()));
11313                    }
11314                }
11315            }
11316            Lnot => {
11317                let value = self.pop();
11318                self.push(Value::Bool(!value.to_boolean()));
11319            }
11320
11321            // -- comparison -------------------------------------------------
11322            Lt | Lte | Gt | Gte => {
11323                let right = self.pop();
11324                let left = self.pop();
11325                let answer = self.relational(op, left, right)?;
11326                self.push(answer);
11327            }
11328            Eq | Neq => {
11329                let right = self.pop();
11330                let left = self.pop();
11331                let equal = self.abstract_equals(left, right)?;
11332                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11333            }
11334            StrictEq => {
11335                let right = self.pop();
11336                let left = self.pop();
11337                self.push(Value::Bool(left.strict_equals(&right)));
11338            }
11339            StrictNeq => {
11340                let right = self.pop();
11341                let left = self.pop();
11342                self.push(Value::Bool(!left.strict_equals(&right)));
11343            }
11344            IsUndefined => {
11345                // `=== undefined`, which is what a destructuring default tests. It is
11346                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11347                let value = self.pop();
11348                self.push(Value::Bool(matches!(value, Value::Undefined)));
11349            }
11350            IsUndefinedOrNull => {
11351                let value = self.pop();
11352                self.push(Value::Bool(value.is_nullish()));
11353            }
11354            Typeof => {
11355                let value = self.pop();
11356                self.push(self.string(value.type_of()));
11357            }
11358            ToObject => {
11359                // A destructuring *object* pattern starts here, which is why
11360                // `var {} = null` throws. Only `undefined` and `null` are refused; a
11361                // primitive is boxed.
11362                let value = self.pop();
11363                let object = self.object_from(&value)?;
11364                self.push(Value::Object(object));
11365            }
11366            Instanceof => {
11367                let constructor = self.pop();
11368                let object = self.pop();
11369                let answer = self.instance_of(&object, &constructor)?;
11370                self.push(Value::Bool(answer));
11371            }
11372            In => {
11373                let object = self.pop();
11374                let key = self.pop();
11375                let answer = self.has_property(&key, &object)?;
11376                self.push(Value::Bool(answer));
11377            }
11378
11379            // -- control flow -----------------------------------------------
11380            Goto | Goto8 | Goto16 => {
11381                self.frame_mut().pc = a as usize;
11382            }
11383            IfTrue | IfTrue8 => {
11384                let value = self.pop();
11385                if value.to_boolean() {
11386                    self.frame_mut().pc = a as usize;
11387                }
11388            }
11389            IfFalse | IfFalse8 => {
11390                let value = self.pop();
11391                if !value.to_boolean() {
11392                    self.frame_mut().pc = a as usize;
11393                }
11394            }
11395            Catch => {
11396                // Pushes the handler target onto the value stack; `unwind` finds it.
11397                self.push(Value::CatchOffset(a));
11398            }
11399            Gosub => {
11400                self.push(Value::ReturnAddress(next as u32));
11401                self.frame_mut().pc = a as usize;
11402            }
11403            Ret => {
11404                let value = self.pop();
11405                match value {
11406                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11407                    _ => {
11408                        return Err(Signal::Throw(
11409                            self.make_error("InternalError", "invalid return address"),
11410                        ));
11411                    }
11412                }
11413            }
11414            NipCatch => {
11415                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11416                // including the marker, keeping the top value.
11417                let top = self.pop();
11418                loop {
11419                    match self.pop() {
11420                        Value::CatchOffset(_) | Value::Undefined => break,
11421                        _ => {}
11422                    }
11423                    if self.frame().stack.is_empty() {
11424                        break;
11425                    }
11426                }
11427                self.push(top);
11428            }
11429            Throw => {
11430                let value = self.pop();
11431                return Err(Signal::Throw(value));
11432            }
11433            ThrowError => {
11434                let name = self.atom_text(a as usize);
11435                let (class, message) = match b {
11436                    0 => ("TypeError", format!("'{name}' is read-only")),
11437                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11438                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
11439                    // `delete super.x` is a syntax-level mistake the reference reports
11440                    // with this wording, not a property-access failure.
11441                    3 => (
11442                        "ReferenceError",
11443                        "unsupported reference to 'super'".to_string(),
11444                    ),
11445                    4 => (
11446                        "TypeError",
11447                        "iterator does not have a throw method".to_string(),
11448                    ),
11449                    5 => (
11450                        "ReferenceError",
11451                        "invalid assignment left-hand side".to_string(),
11452                    ),
11453                    _ => ("TypeError", format!("invalid operation on '{name}'")),
11454                };
11455                return Err(Signal::Throw(self.make_error(class, &message)));
11456            }
11457            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11458            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11459            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11460            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11461            Await => return Ok(Step::Suspend(SuspendKind::Await)),
11462            ReturnAsync => {
11463                // The reference's `return_async` returns `undefined` and lets the resume
11464                // machinery pick the real value off `sp[-1]`, which is how it tells a
11465                // completion from a suspension. Carrying the value explicitly says the
11466                // same thing without the implicit stack slot.
11467                let value = self.pop();
11468                return Ok(Step::Return(value));
11469            }
11470            Return => {
11471                let value = self.pop();
11472                return Ok(Step::Return(value));
11473            }
11474            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11475
11476            // -- calls ------------------------------------------------------
11477            Call | Call0 | Call1 | Call2 | Call3 => {
11478                let argc = self.argc_operand(op, a);
11479                let args = self.pop_n(argc);
11480                let callee = self.pop();
11481                // A plain call has no receiver; the callee decides what to do with
11482                // `undefined` (a sloppy function substitutes the global object).
11483                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11484                    self.push(result);
11485                }
11486            }
11487            CallConstructor => {
11488                // `constructor this_obj args… -> object`. The duplicated
11489                // constructor is `new.target`; this milestone does not expose it,
11490                // so the extra copy is simply consumed here.
11491                let argc = a as usize;
11492                let args = self.pop_n(argc);
11493                let new_target = self.pop();
11494                let callee = self.pop();
11495                let result = self.construct(callee, new_target, args)?;
11496                self.push(result);
11497            }
11498            CallMethod => {
11499                let argc = a as usize;
11500                let args = self.pop_n(argc);
11501                let callee = self.pop();
11502                let this = self.pop();
11503                if let Some(result) = self.call_or_push(callee, this, args)? {
11504                    self.push(result);
11505                }
11506            }
11507            Apply => {
11508                // `func this array -> result`, the spread-call form: the compiler
11509                // builds one array of arguments, and all that is left here is to
11510                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11511                let array = self.pop();
11512                let this = self.pop();
11513                let callee = self.pop();
11514                let args = self.array_like_to_args(&array)?;
11515                if a & 1 != 0 {
11516                    let result = self.construct(callee, this, args)?;
11517                    self.push(result);
11518                } else if let Some(result) = self.call_or_push(callee, this, args)? {
11519                    self.push(result);
11520                }
11521            }
11522            TailCall | TailCallMethod => {
11523                // `tail_call` is `call` whose result is returned immediately — the
11524                // reference jumps straight to `done` instead of storing the value and
11525                // running on. The callee still gets its own frame, so deep tail
11526                // recursion hits the stack limit exactly like plain recursion does;
11527                // marking this frame lets the return path unwind without needing
11528                // instructions after the call.
11529                let argc = if op == TailCallMethod {
11530                    a as usize
11531                } else {
11532                    self.argc_operand(op, a)
11533                };
11534                let args = self.pop_n(argc);
11535                let callee = self.pop();
11536                let this = if op == TailCallMethod {
11537                    self.pop()
11538                } else {
11539                    Value::Undefined
11540                };
11541                if let Value::Object(function) = &callee
11542                    && let Some((code, env)) = bytecode_of(function)
11543                {
11544                    // A generator or async body is not run here at all: calling it only
11545                    // *creates* the generator/coroutine, so it must not inherit this
11546                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
11547                    // onto `f`'s frame, and the first `yield`/`await` then reported
11548                    // "a generator body ran as an ordinary call".
11549                    if code.code.kind.is_generator() || code.code.kind.is_async() {
11550                        let value = self.call_value(callee, this, args)?;
11551                        return Ok(Step::Return(value));
11552                    }
11553                    self.frame_mut().tail = true;
11554                    self.push_frame(code, env, this, args, callee)?;
11555                    return Ok(Step::Continue);
11556                }
11557                // A native callee has no frame to reuse, so its value is simply
11558                // returned.
11559                let value = self.call_value(callee, this, args)?;
11560                return Ok(Step::Return(value));
11561            }
11562
11563            // -- objects ----------------------------------------------------
11564            SpecialObject => {
11565                let value = self.special_object(a)?;
11566                self.push(value);
11567            }
11568            PrivateSymbol => {
11569                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11570                // symbol each time it is evaluated, which is why the compiler evaluates it
11571                // once (at class definition) and stores it in a class-scope binding.
11572                let name = self.atom_text(a as usize);
11573                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11574                self.push(Value::Symbol(symbol));
11575            }
11576            GetPrivateField => {
11577                // `obj symbol -> value`. A missing private field is a TypeError, which is what
11578                // makes `#x` inaccessible on any object not built by this class.
11579                let symbol = self.pop();
11580                let object = self.pop();
11581                let value = self.read_private_field(&object, &symbol)?;
11582                self.push(value);
11583            }
11584            PutPrivateField => {
11585                // `obj value symbol ->`, and the store is a plain assignment to a property the
11586                // class already created, so there is no setter to consult.
11587                let symbol = self.pop();
11588                let value = self.pop();
11589                let object = self.pop();
11590                self.write_private_field(&object, &symbol, value)?;
11591            }
11592            DefinePrivateField => {
11593                // `obj symbol value -> obj`: a field initialiser creates the property, and
11594                // redefining one is a TypeError ("already exists").
11595                let value = self.pop();
11596                let symbol = self.pop();
11597                let object = self.pop();
11598                self.define_private_field(&object, &symbol, value)?;
11599                self.push(object);
11600            }
11601            PrivateIn => {
11602                // `obj key -> bool`: `#x in o`. The second operand decides which question is
11603                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11604                // is a field, so this is an own-property test; a *function* is a method or
11605                // accessor, so this is a brand check.
11606                let key = self.pop();
11607                let object = self.pop();
11608                let Some(target) = object.as_object() else {
11609                    return Err(Signal::Throw(
11610                        self.make_error("TypeError", "invalid 'in' operand"),
11611                    ));
11612                };
11613                let present = match &key {
11614                    Value::Object(_) => self.check_brand(target, &key)?,
11615                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11616                };
11617                self.push(Value::Bool(present));
11618            }
11619            AddBrand => {
11620                // `obj home ->`: create the class brand on `home` if it has none, then give
11621                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11622                // class definition: only the prototype's copy of the symbol is wanted.
11623                let home = self.pop();
11624                let object = self.pop();
11625                self.add_brand(&object, &home)?;
11626            }
11627            CheckBrand => {
11628                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11629                // Both stay, because the caller needs them — `nip` halves a read into its
11630                // value and `call_method` uses the pair as receiver and callee.
11631                let function = self.peek(0);
11632                let object = self.peek(1);
11633                let Some(target) = object.as_object() else {
11634                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11635                };
11636                if !self.check_brand(target, &function)? {
11637                    return Err(Signal::Throw(
11638                        self.make_error("TypeError", "invalid brand on object"),
11639                    ));
11640                }
11641            }
11642            GetLength => {
11643                // `get_length` is the `.length` read; an array and a string answer
11644                // from their own length, anything else from the property.
11645                let target = self.pop();
11646                let value = match &target {
11647                    Value::Object(object) => match object.array_length() {
11648                        Some(length) => crate::object::length_value(length),
11649                        None => self.read_field(&target, "length")?,
11650                    },
11651                    Value::String(text) => Value::Int(text.utf16_len() as i32),
11652                    _ => self.read_field(&target, "length")?,
11653                };
11654                self.push(value);
11655            }
11656            GetField | GetField2 => {
11657                let object = self.pop();
11658                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11659                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11660                // just below is what lets the borrow outlive the `&mut self` the lookup
11661                // needs — one refcount bump instead of a key clone plus its drop, on the
11662                // hottest property path there is: every `o.x` and every `o.m()` receiver.
11663                let code = self.frame().code.clone();
11664                let key = &code.atom_keys[a as usize];
11665                let value = self.read_field_cached(&object, key, next)?;
11666                if op == GetField2 {
11667                    self.push(object);
11668                }
11669                self.push(value);
11670            }
11671            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11672                let key = self.pop();
11673                let object = self.pop();
11674                let key = self.propkey(&key)?;
11675                let value = self.read_field_key(&object, &key)?;
11676                if matches!(op, GetArrayEl2 | GetArrayEl3) {
11677                    self.push(object);
11678                }
11679                if op == GetArrayEl3 {
11680                    // The key goes back in its *value* form, which the compiler stores
11681                    // into the target of a destructuring assignment.
11682                    self.push(match &key {
11683                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11684                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
11685                    });
11686                }
11687                self.push(value);
11688            }
11689            PutField => {
11690                let value = self.pop();
11691                let object = self.pop();
11692                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11693                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11694                // only reads. `this.value = …` is the write half of the hottest loop in
11695                // `property:method-call`, and `own_property_key` was 4.8% of the case.
11696                let code = self.frame().code.clone();
11697                let key = &code.atom_keys[a as usize];
11698                self.write_field_key(&object, key, value)?;
11699            }
11700            PutArrayEl => {
11701                let value = self.pop();
11702                let key = self.pop();
11703                let object = self.pop();
11704                let key = self.propkey(&key)?;
11705                self.write_field_key(&object, &key, value)?;
11706            }
11707            DefineField => {
11708                let value = self.pop();
11709                let object = self.pop();
11710                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11711                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11712                // three U+FFFD — a property under a different name from the one
11713                // `o["\uD800"]` reads.
11714                let code = self.frame().code.clone();
11715                let key = code.atom_keys[a as usize].clone();
11716                // No naming here. `{m: function(){}}` is named by the *compiler*, which
11717                // emits `set_name` — and only where `NamedEvaluation` applies, so
11718                // `{m: (0, function(){})}` stays anonymous. Naming every function that
11719                // reaches a property definition got that case wrong, and the compiler is
11720                // the only place that can tell the two apart.
11721                if let Some(target) = object.as_object() {
11722                    // Only an *array* stores into the element vector. A numeric key
11723                    // on an ordinary object is an ordinary property, which is what
11724                    // makes `{1: 'a'}` iterate as a key rather than disappear.
11725                    let stored = target.is_array()
11726                        && key.as_str().and_then(array_index).is_some_and(|index| {
11727                            target.array_set(self.heap, index as usize, value.clone())
11728                        });
11729                    if !stored {
11730                        target.define_data_key(&key, value);
11731                    }
11732                }
11733                self.push(object);
11734            }
11735            DefineArrayEl => {
11736                // `obj key value -> obj key`. The *value* form of the key is what goes
11737                // back on the stack — the compiler stores it into the pattern's binding —
11738                // so the symbol is not stringified on the way through.
11739                let value = self.pop();
11740                let key_value = self.pop();
11741                let object = self.peek(0);
11742                let key = self.propkey(&key_value)?;
11743                self.write_field_key(&object, &key, value)?;
11744                self.push(key_value);
11745            }
11746            SetHomeObject => {
11747                // `obj func -> obj func`: records the object a method was defined on so
11748                // `super` inside it resolves against that object's prototype.
11749                let function = self.peek(0);
11750                let home = self.peek(1);
11751                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11752                    function.set_home_object(Some(home.clone()));
11753                }
11754            }
11755            Regexp => {
11756                // `pattern flags -> regexp`. A literal compiles here rather than through the
11757                // constructor, which is both what the reference's dedicated opcode is for
11758                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11759                let flags = self.pop();
11760                let pattern = self.pop();
11761                let pattern = self.to_js_string(&pattern)?;
11762                let flags = self.to_js_string(&flags)?;
11763                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11764                self.push(Value::Object(object));
11765            }
11766            UsingDisposeInit => {
11767                // The error state a disposal accumulates into. Uninitialised means "no
11768                // failure yet"; anything else is the exception being propagated.
11769                self.push(Value::Uninitialized);
11770            }
11771            UsingCheck => {
11772                // `value -> value, method`: validate and snapshot the disposer now, so a
11773                // later change to `Symbol.dispose` cannot change what gets called, and so a
11774                // value that is not disposable fails before the body runs.
11775                let value = self.pop();
11776                let method = self.using_method_for(&value, a as u8 == 1)?;
11777                self.push(value);
11778                self.push(method);
11779            }
11780            UsingDispose => {
11781                // `error_state -> error_state'`: dispose the variable at `slot` — its value
11782                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11783                // the pending error.
11784                let slot = self.slot_operand(op, a);
11785                let error_state = self.pop();
11786                let merged = self.using_dispose_once(slot, error_state)?;
11787                self.push(merged);
11788            }
11789            UsingDisposeMerge => {
11790                let new_error = self.pop();
11791                let error_state = self.pop();
11792                let merged = self.merge_dispose_error(new_error, error_state);
11793                self.push(merged);
11794            }
11795            UsingDisposeEnd => {
11796                // A disposal that failed replaces the block's normal completion, so the
11797                // error state becomes a real throw here rather than at the call site.
11798                let error_state = self.pop();
11799                if !matches!(error_state, Value::Uninitialized) {
11800                    return Err(Signal::Throw(error_state));
11801                }
11802            }
11803            UsingDisposeAsync => {
11804                // `await using` needs a promise to await and this runtime has no
11805                // `Promise` builtin, so the disposer is called synchronously and its result
11806                // discarded. That is correct for a disposer that returns nothing and is
11807                // reported as a gap rather than silently skipped.
11808                let slot = self.slot_operand(op, a);
11809                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11810                self.push(error_state);
11811            }
11812            GetSuper => {
11813                // `obj -> obj's prototype`: the starting point of a `super` lookup.
11814                let object = self.pop();
11815                let proto = match &object {
11816                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11817                    _ => Value::Null,
11818                };
11819                self.push(proto);
11820            }
11821            GetSuperValue => {
11822                // `receiver proto key -> value`, searching from `proto` but reporting to
11823                // `receiver`, which is what `super.g` must do for a getter to see `this`.
11824                //
11825                // Three values in, one out: the receiver is *consumed*, not left under the
11826                // result. Leaving it there was invisible for `super.x` in `return` or
11827                // statement position (the result is what gets popped) and corrupted the
11828                // frame everywhere else — `print(super.x)` left the class where the call
11829                // opcode looks for the receiver and called the class itself.
11830                let key = self.pop();
11831                let proto = self.pop();
11832                let receiver = self.pop();
11833                let value = self.super_read(&receiver, &proto, &key)?;
11834                self.push(value);
11835            }
11836            PutSuperValue => {
11837                // `receiver proto key value ->`: a store that starts at `proto` but
11838                // assigns to `receiver`.
11839                let value = self.pop();
11840                let key = self.pop();
11841                let proto = self.pop();
11842                let receiver = self.pop();
11843                self.super_write(&receiver, &proto, &key, value)?;
11844            }
11845            DefineClass => {
11846                // `parent ctor -> ctor proto`: the constructor becomes the class and a
11847                // fresh prototype object lands on top for the methods to go on.
11848                let name = self.atom_text(a as usize);
11849                let (ctor, proto) = self.define_class(&name, b)?;
11850                self.push(ctor);
11851                self.push(Value::Object(proto));
11852            }
11853            DefineClassComputed => {
11854                // `parent ctor key -> ctor proto key`: the computed name stays put so
11855                // `define_field`-style consumers can still read it.
11856                let key = self.pop();
11857                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11858                let (ctor, proto) = self.define_class(&name, b)?;
11859                self.push(ctor);
11860                self.push(Value::Object(proto));
11861                self.push(key);
11862            }
11863            DefineMethod => {
11864                let function = self.pop();
11865                let object = self.pop();
11866                // The exact key, like `define_field`: a quoted method key may hold an
11867                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11868                // that `o["\uD800"]` finds.
11869                let code = self.frame().code.clone();
11870                let key = code.atom_keys[a as usize].clone();
11871                // A method's `[[HomeObject]]` is the object it was defined on, which is
11872                // what `super` inside it resolves against.
11873                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11874                    function.set_home_object(Some(object.clone()));
11875                }
11876                if let Some(text) = key.as_wtf8() {
11877                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11878                } else {
11879                    self.set_function_name(
11880                        &function,
11881                        &key_with_accessor_prefix(&key.to_string(), b),
11882                    );
11883                }
11884                if let Some(array) = object.as_object() {
11885                    define_function_property(array, &key, function, b);
11886                }
11887                self.push(object);
11888            }
11889            DefineMethodComputed => {
11890                let function = self.pop();
11891                let key = self.pop();
11892                let object = self.pop();
11893                let key = self.propkey(&key)?;
11894                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11895                // the name: `super` inside a computed method resolves through it. Without
11896                // this, `class B extends A { [k]() { return super.m() } }` read the
11897                // home object as null and threw.
11898                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11899                    function.set_home_object(Some(object.clone()));
11900                }
11901                match key.as_wtf8() {
11902                    Some(text) => {
11903                        let name = accessor_prefixed(text, a);
11904                        self.set_function_name_wtf8(&function, &name);
11905                    }
11906                    None => self.set_function_name(
11907                        &function,
11908                        &key_with_accessor_prefix(&key.to_string(), a),
11909                    ),
11910                }
11911                if let Some(array) = object.as_object() {
11912                    define_function_property(array, &key, function, a);
11913                }
11914                self.push(object);
11915            }
11916            SetProto => {
11917                let proto = self.pop();
11918                let object = self.pop();
11919                if let Some(target) = object.as_object() {
11920                    target.set_proto(proto.as_object().cloned());
11921                }
11922                self.push(object);
11923            }
11924            CopyDataProperties => {
11925                let exclusion = self.pop();
11926                let source = self.pop();
11927                let target = self.peek(0);
11928                self.copy_properties(&target, &source, &exclusion)?;
11929                self.push(source);
11930                self.push(exclusion);
11931            }
11932            ToPropkey => {
11933                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11934                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11935                // ordinary `"Symbol(b)"` property.
11936                let value = self.pop();
11937                let key = match self.propkey(&value)? {
11938                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11939                    PropertyKey::String(text) => self.string_wtf8(text),
11940                };
11941                self.push(key);
11942            }
11943            SetName => {
11944                let function = self.peek(0);
11945                let name = self.atom_wtf8(a as usize);
11946                self.set_function_name_wtf8(&function, &name);
11947            }
11948            SetNameComputed => {
11949                let key = self.peek(1);
11950                let function = self.peek(0);
11951                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11952                self.set_function_name(&function, &name);
11953            }
11954
11955            // -- arrays -----------------------------------------------------
11956            ArrayFrom => {
11957                let count = a as usize;
11958                let elements = self.pop_n(count);
11959                let array = self.new_array(elements);
11960                self.push(Value::Object(array));
11961            }
11962            Append => {
11963                // `array index iterable -> array new_index`
11964                let iterable = self.pop();
11965                self.pop();
11966                let array = self.peek(0);
11967                let added = self.append_enumerate(&array, &iterable)?;
11968                self.push(Value::Int(added));
11969            }
11970
11971            // -- iteration --------------------------------------------------
11972            ForInStart => {
11973                let value = self.pop();
11974                let record = self.for_in_record(&value)?;
11975                self.push(Value::Object(record));
11976            }
11977            ForInNext => {
11978                // `record -> record key done`. The flag is *done*, not "found":
11979                // the compiler tests it with `if_false` to jump back into the body,
11980                // so reporting `true` while keys remain would end the loop at once.
11981                let record = self.peek(0);
11982                match self.for_in_advance(&record)? {
11983                    Some(key) => {
11984                        let text = self.string(key);
11985                        self.push(text);
11986                        self.push(Value::Bool(false));
11987                    }
11988                    None => {
11989                        self.push(Value::Undefined);
11990                        self.push(Value::Bool(true));
11991                    }
11992                }
11993            }
11994            ForOfStart => {
11995                let value = self.pop();
11996                let iterator = self.get_iterator(&value)?;
11997                self.push(iterator.object);
11998                self.push(iterator.next);
11999                self.push(Value::CatchOffset(0));
12000            }
12001            ForOfNext => {
12002                // `iter next catch_offset -> iter next catch_offset value done`.
12003                //
12004                // The operand is how many values sit *above* the iterator triple: a
12005                // destructuring rest element keeps its target array and running index
12006                // there while draining the iterator, so the triple is not at the top.
12007                let extra = a as usize;
12008                let iterator_slot = 2 + extra;
12009                // An exhausted iterator is replaced by `undefined` (see below), so a
12010                // second step must not call `next` again — `Array.from` and a
12011                // destructuring pattern both keep stepping past the end.
12012                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
12013                    (Value::Undefined, true)
12014                } else {
12015                    let iterator = Iterator {
12016                        object: self.peek(iterator_slot),
12017                        next: self.peek(1 + extra),
12018                    };
12019                    self.iterator_step(&iterator)?
12020                };
12021                if done {
12022                    // The result's `value` is meaningless once the iterator is done:
12023                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12024                    // rather than binding the generator's return value.
12025                    let top = self.frame().stack.len() - 1 - iterator_slot;
12026                    self.frame_mut().stack[top] = Value::Undefined;
12027                    self.push(Value::Undefined);
12028                    self.push(Value::Bool(true));
12029                } else {
12030                    self.push(value);
12031                    self.push(Value::Bool(false));
12032                }
12033            }
12034            IteratorNext => {
12035                // `iter next catch val -> iter next catch val'`: replace the argument with
12036                // the result of `next(val)`. The triple below stays put, which is why the
12037                // three instructions of the `yield*` loop all address the stack the same way.
12038                let value = self.pop();
12039                let object = self.peek(2);
12040                let next = self.peek(1);
12041                let result = self.call_value(next, object, vec![value])?;
12042                self.push(result);
12043            }
12044            IteratorCall => {
12045                // `iter next catch val -> iter next catch val' flag`.
12046                //
12047                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12048                // The flag is `true` when the method was missing, which is how the
12049                // caller learns that the inner iterator cannot take part in the
12050                // unwinding.
12051                let value = self.pop();
12052                let object = self.peek(2);
12053                let key = if a & 1 != 0 { "throw" } else { "return" };
12054                let method = self.read_field(&object, key)?;
12055                if matches!(method, Value::Undefined | Value::Null) {
12056                    self.push(value);
12057                    self.push(Value::Bool(true));
12058                } else {
12059                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12060                    let result = self.call_value(method, object, argument)?;
12061                    self.push(result);
12062                    self.push(Value::Bool(false));
12063                }
12064            }
12065            IteratorCheckObject => {
12066                if !matches!(self.peek(0), Value::Object(_)) {
12067                    return Err(Signal::Throw(
12068                        self.make_error("TypeError", "iterator must return an object"),
12069                    ));
12070                }
12071            }
12072            IteratorClose => {
12073                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12074                // calling the iterator's `return` so it can release whatever it holds.
12075                //
12076                // The catch offset goes first, so an exception from `return` is not caught
12077                // by the loop being abandoned. This used to pop the three operands and call
12078                // nothing at all, which made `break` out of a `for of` invisible to an
12079                // iterator with a `return` method.
12080                self.pop();
12081                self.pop();
12082                let iterator = self.pop();
12083                if !matches!(iterator, Value::Undefined) {
12084                    let method = self.read_field(&iterator, "return")?;
12085                    if !matches!(method, Value::Undefined | Value::Null) {
12086                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
12087                        // §7.4.6: a `return` that answers a non-object is a TypeError.
12088                        if !matches!(result, Value::Object(_)) {
12089                            return Err(Signal::Throw(
12090                                self.make_error("TypeError", "iterator must return an object"),
12091                            ));
12092                        }
12093                    }
12094                }
12095            }
12096            Import => {
12097                // `import(specifier, options)`: the options slot is on top. Both are
12098                // `GetValue`-ed by the compiler, which is why this pops values rather than
12099                // references — and why the validation of `options` (§13.3.10.1 step 10)
12100                // happens inside `dynamic_import`, where its failures can be turned into a
12101                // rejection instead of a throw.
12102                let options = self.pop();
12103                let specifier = self.pop();
12104                let promise = self.dynamic_import(specifier, options)?;
12105                self.push(promise);
12106            }
12107            ForAwaitOfStart => {
12108                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12109                // `Symbol.iterator` fallback.
12110                let value = self.pop();
12111                let iterator = self.get_async_iterator(&value)?;
12112                self.push(iterator.object);
12113                self.push(iterator.next);
12114                self.push(Value::CatchOffset(0));
12115            }
12116            ForAwaitOfNext => {
12117                // `for await` steps the iterator and leaves the *result* wrapped in a
12118                // promise, so the `await` the compiler emits right after this can suspend
12119                // on it. Unwrapping happens in `iterator_get_value_done`.
12120                let extra = a as usize;
12121                let iterator_slot = 2 + extra;
12122                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12123                    Value::Undefined
12124                } else {
12125                    let iterator = Iterator {
12126                        object: self.peek(iterator_slot),
12127                        next: self.peek(1 + extra),
12128                    };
12129                    let next = iterator.next.clone();
12130                    self.call_value(next, iterator.object, Vec::new())?
12131                };
12132                let promise = self.promise_resolve_value(result)?;
12133                self.push(promise);
12134            }
12135            IteratorGetValueDone => {
12136                // `result -> value done`. A missing result object means the iterator was
12137                // already exhausted, which the loop treats as `done`.
12138                let result = self.pop();
12139                let done = match &result {
12140                    Value::Object(object) => self
12141                        .get_property(object, "done")?
12142                        .is_some_and(|value| value.to_boolean()),
12143                    _ => true,
12144                };
12145                if done {
12146                    // Clear the iterator object so the `iterator_close` the loop emits on
12147                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12148                    // on normal completion, and this is where a normal completion is
12149                    // recognised — the same trick `for_of_next` uses, which also replaces
12150                    // the slot with `undefined`.
12151                    //
12152                    // The layout is fixed because only `for await` emits this opcode:
12153                    // `iter next catch [result]`, so the iterator is three below the top.
12154                    let depth = self.frame().stack.len();
12155                    if depth >= 3 {
12156                        self.frame_mut().stack[depth - 3] = Value::Undefined;
12157                    }
12158                    self.push(Value::Undefined);
12159                    self.push(Value::Bool(true));
12160                } else {
12161                    let Value::Object(object) = &result else {
12162                        self.push(Value::Undefined);
12163                        self.push(Value::Bool(true));
12164                        return Ok(Step::Continue);
12165                    };
12166                    let value = self
12167                        .get_property(object, "value")?
12168                        .unwrap_or(Value::Undefined);
12169                    self.push(value);
12170                    self.push(Value::Bool(false));
12171                }
12172            }
12173
12174            Delete => {
12175                // `delete obj[key]`, where the key was just pushed. Deleting an array
12176                // index leaves a *hole* rather than closing the gap, and a
12177                // non-configurable property answers `false` and stays.
12178                let key = self.pop();
12179                let target = self.pop();
12180                let key = self.propkey(&key)?;
12181                let text_label = key.as_str().unwrap_or("").to_string();
12182                let deleted = match &target {
12183                    Value::Object(object) => {
12184                        let object = object.clone();
12185                        self.delete_property_key(&object, &key)?
12186                    }
12187                    // A string's `length` and its index properties are
12188                    // non-configurable, so deleting one answers `false`.
12189                    Value::String(text) => {
12190                        !(text_label == "length"
12191                            || array_index(&text_label)
12192                                .is_some_and(|index| (index as usize) < text.utf16_len()))
12193                    }
12194                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
12195                    // object to delete from, and only a *boxable* primitive has one.
12196                    Value::Undefined | Value::Null => {
12197                        return Err(Signal::Throw(
12198                            self.make_error("TypeError", "cannot convert to object"),
12199                        ));
12200                    }
12201                    // Any other primitive has no own properties; deleting nothing
12202                    // succeeds.
12203                    _ => true,
12204                };
12205                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12206                // `TypeError` rather than a `false` result. Sloppy mode silently reports
12207                // the refusal, which is why the same statement throws here but not there.
12208                if !deleted && self.current_strict() {
12209                    return Err(Signal::Throw(
12210                        self.make_error("TypeError", "cannot delete property"),
12211                    ));
12212                }
12213                self.push(Value::Bool(deleted));
12214            }
12215
12216            // -- exceptions and bookkeeping ---------------------------------
12217            Fclosure | Fclosure8 => {
12218                let value = self.closure(a as usize)?;
12219                self.push(value);
12220            }
12221
12222            other => {
12223                let name = other.info().name;
12224                return Err(Signal::Throw(self.make_error(
12225                    "InternalError",
12226                    &format!("{name} is not implemented yet"),
12227                )));
12228            }
12229        }
12230        Ok(Step::Continue)
12231    }
12232
12233    // -- operand helpers ----------------------------------------------------
12234
12235    /// The slot index an operand names, taking short forms into account.
12236    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12237        use Opcode::*;
12238        match op {
12239            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12240            | SetVarRef0 => 0,
12241            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12242            | SetVarRef1 => 1,
12243            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12244            | SetVarRef2 => 2,
12245            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12246            | SetVarRef3 => 3,
12247            _ => a as usize,
12248        }
12249    }
12250
12251    /// The argument count of a call, taking `call0`…`call3` into account.
12252    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12253        use Opcode::*;
12254        match op {
12255            Call0 => 0,
12256            Call1 => 1,
12257            Call2 => 2,
12258            Call3 => 3,
12259            _ => a as usize,
12260        }
12261    }
12262
12263    /// The atom's name as a property key.
12264    ///
12265    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12266    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12267    /// `String::clone` was a heap allocation and a copy — per property access.
12268    /// The atom at `index`, as a property key.
12269    ///
12270    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12271    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12272    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12273    /// 5.3% of `property:monomorphic`.
12274    /// The atom's text, exactly — including an unpaired surrogate.
12275    ///
12276    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12277    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12278    /// `atom_text` below is for the other kind of use, where the atom is a key in the
12279    /// engine's own tables.
12280    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12281        self.frame()
12282            .code
12283            .code
12284            .atoms
12285            .get(index)
12286            .map(|atom| match atom {
12287                Atom::Str(text) => text.clone(),
12288                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12289                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12290                Atom::Null => crate::value::Wtf8::new(String::new()),
12291            })
12292            .unwrap_or_default()
12293    }
12294
12295    fn atom_text(&self, index: usize) -> String {
12296        self.frame()
12297            .code
12298            .code
12299            .atoms
12300            .get(index)
12301            .map(|atom| match atom {
12302                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12303                // compare it to an identifier, and a surrogate-bearing name is reachable
12304                // through `atom_wtf8` where it matters.
12305                Atom::Str(text) => text.to_string_lossy().into_owned(),
12306                Atom::Index(value) => value.to_string(),
12307                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12308                // `throw_error`, `delete super.x`) never read it.
12309                Atom::Null => String::new(),
12310            })
12311            .unwrap_or_default()
12312    }
12313
12314    fn constant(&mut self, index: usize) -> JsResult<Value> {
12315        let constant = self.frame().code.code.cpool.get(index).cloned();
12316        Ok(match &constant {
12317            Some(Constant::Number(number)) => Value::Float(*number),
12318            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12319            Some(Constant::BigInt { digits, radix }) => {
12320                match crate::bigint::BigInt::from_radix(digits, *radix) {
12321                    Some(big) => self.bigint(big),
12322                    // A literal the parser accepted is always parseable; a failure here
12323                    // would be a compiler bug, so it reads as an `InternalError`.
12324                    None => {
12325                        return Err(Signal::Throw(
12326                            self.make_error("InternalError", "unparseable bigint literal"),
12327                        ));
12328                    }
12329                }
12330            }
12331            Some(Constant::Function(_)) => {
12332                return Err(Signal::Throw(
12333                    self.make_error("InternalError", "a bare function constant"),
12334                ));
12335            }
12336            // A tagged template's call site: a frozen array of the cooked chunks with a
12337            // frozen `raw` array beside it, which is what `String.raw` reads back.
12338            Some(Constant::Template { cooked, raw }) => {
12339                let cooked_values: Vec<Value> = cooked
12340                    .iter()
12341                    .map(|chunk| match chunk {
12342                        Some(text) => self.string_wtf8(text.clone()),
12343                        None => Value::Undefined,
12344                    })
12345                    .collect();
12346                let raw_values: Vec<Value> =
12347                    raw.iter().map(|text| self.string(text.clone())).collect();
12348                let raw_array = self.new_array(raw_values);
12349                raw_array.set_extensible(false);
12350                let template = self.new_array(cooked_values);
12351                template.define(
12352                    "raw",
12353                    Property::with_attributes(Value::Object(raw_array), false, false),
12354                );
12355                template.set_extensible(false);
12356                Value::Object(template)
12357            }
12358            _ => Value::Undefined,
12359        })
12360    }
12361
12362    /// The reference cell a closure-variable slot names.
12363    ///
12364    /// Two kinds of binding share this addressing: a genuine closure variable
12365    /// (captured from an enclosing function) lives in this frame's environment,
12366    /// while a *declared global* lives in the realm so that a script, a function
12367    /// declaration and their uses all see one binding. A plain `Global` — an
12368    /// undeclared name that may be satisfied by the global object — has no cell at
12369    /// all, which is how `typeof x` still works for a name that does not exist.
12370    /// The reference cell a closure-variable slot names.
12371    ///
12372    /// The environment is resolved once, when the closure is built, and this is
12373    /// just the lookup afterwards. A *declared global* is in there too, pointing at
12374    /// the realm's cell, so a script, a hoisted function declaration and their uses
12375    /// all share one binding. A plain `Global` — a name the script never declared —
12376    /// is read and written through `get_var`/`put_var` by name instead, which is
12377    /// what lets the global object satisfy it.
12378    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12379        self.frame().env.cells.get(slot).cloned()
12380    }
12381
12382    /// Whether `slot` refers to a global binding through the reference table.
12383    ///
12384    /// A global's cell in the closure environment only exists so the slot has
12385    /// something to point at; the binding itself lives on the global object (a `var`)
12386    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12387    /// be routed, not performed on the placeholder.
12388    fn is_global_slot(&self, slot: usize) -> bool {
12389        self.frame()
12390            .code
12391            .code
12392            .closure_vars
12393            .get(slot)
12394            .is_some_and(|c| {
12395                // A module's declarations and imports are *not* globals: their cells are
12396                // the module environment's, filled by the host, so the placeholder routing
12397                // must not apply to them.
12398                matches!(
12399                    c.closure_type,
12400                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12401                )
12402            })
12403    }
12404
12405    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12406        if self.is_global_slot(slot) {
12407            return self.get_global(slot);
12408        }
12409        Ok(self
12410            .var_ref_cell(slot)
12411            .map(|cell| cell.get())
12412            .unwrap_or(Value::Undefined))
12413    }
12414
12415    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12416        // A function declaration is hoisted by storing into a global reference before
12417        // the body runs, so this path is also what puts it on the global object.
12418        if self.is_global_slot(slot) {
12419            return self.put_global(slot, value);
12420        }
12421        if let Some(cell) = self.var_ref_cell(slot) {
12422            cell.set(value);
12423        }
12424        Ok(())
12425    }
12426
12427    // -- closures -----------------------------------------------------------
12428
12429    /// Build the closure for the function constant `index`.
12430    ///
12431    /// Every entry in the child's closure table names where its binding lives in
12432    /// *this* frame: a local or argument slot that was marked captured, or a cell
12433    /// this frame is itself holding. That is how a variable three functions deep
12434    /// stays one binding.
12435    fn closure(&mut self, index: usize) -> JsResult<Value> {
12436        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12437        else {
12438            return Err(Signal::Throw(
12439                self.make_error("InternalError", "fclosure of a non-function"),
12440            ));
12441        };
12442        let mut cells = Vec::with_capacity(function.closure_vars.len());
12443        for closure_var in &function.closure_vars {
12444            let cell = match closure_var.closure_type {
12445                ClosureType::Arg => {
12446                    let slot = closure_var.var_idx as usize;
12447                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12448                }
12449                ClosureType::Local => {
12450                    let slot = closure_var.var_idx as usize;
12451                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12452                }
12453                ClosureType::Ref | ClosureType::GlobalRef => {
12454                    // A `Ref` names a cell in this frame's own closure table; a
12455                    // `GlobalRef` also starts there, then resolves by name below.
12456                    let slot = closure_var.var_idx as usize;
12457                    if let Some(cell) = self.frame().env.cells.get(slot) {
12458                        cells.push(cell.clone());
12459                        continue;
12460                    }
12461                    -1
12462                }
12463                _ => -1,
12464            };
12465            if cell >= 0 {
12466                let cell = self.frame().cells[cell as usize].clone();
12467                cells.push(cell);
12468                continue;
12469            }
12470            // A global: the cell is created on demand and shared through the realm,
12471            // so every function sees one binding.
12472            let name = closure_var.name.clone();
12473            let cell = match self.realm.globals.get(&name) {
12474                Some(cell) => cell.clone(),
12475                None => {
12476                    let cell = self.new_cell(Value::Undefined);
12477                    self.realm.globals.insert(name.clone(), cell.clone());
12478                    cell
12479                }
12480            };
12481            cells.push(cell);
12482        }
12483        let name = function.name.clone();
12484        // `.length` is the arity before any default or rest parameter, not the number
12485        // of slots a pattern parameter needs.
12486        let length = function.defined_args;
12487        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12488        // function and an arrow function do not. A *method* also does not, but that is not
12489        // known here — the method is marked when the `[[HomeObject]]` is attached (see
12490        // `set_home_object`), which is the moment it becomes a method.
12491        let function_kind = function.kind;
12492        let constructible =
12493            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12494        let code = Gc::new(self.heap, CompiledCode::new(*function));
12495        // A closure built inside an `eval` inherits the eval's view of the enclosing
12496        // bindings, so it can still read them once the eval has returned.
12497        let eval_scope = self
12498            .active_eval_scope
12499            .clone()
12500            .or_else(|| self.frame().env.eval_scope.clone());
12501        // A closure sees the variables a direct `eval` declared in the frame it was
12502        // created in — the ones declared before *and after* it, so the same object is
12503        // shared; only the phase bounds which of them are visible.
12504        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12505        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12506        let env = Gc::new(
12507            self.heap,
12508            ClosureEnv {
12509                cells,
12510                eval_scope,
12511                local_vars,
12512                local_phase,
12513            },
12514        );
12515        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12516        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12517        // the only thing that carries `Symbol.toStringTag`, so without it
12518        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12519        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12520        let proto = match function_kind {
12521            js_compile::bytecode::FunctionKind::AsyncGenerator => self
12522                .realm
12523                .async_generator_function_proto
12524                .clone()
12525                .or_else(|| self.realm.function_proto.clone().into()),
12526            js_compile::bytecode::FunctionKind::Generator => self
12527                .realm
12528                .generator_function_proto
12529                .clone()
12530                .or_else(|| self.realm.function_proto.clone().into()),
12531            js_compile::bytecode::FunctionKind::Async => self
12532                .realm
12533                .async_function_proto
12534                .clone()
12535                .or_else(|| self.realm.function_proto.clone().into()),
12536            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12537        };
12538        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12539        object.set_constructible(constructible);
12540        object.define(
12541            "length",
12542            Property::name_or_length(Value::Int(length as i32)),
12543        );
12544        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12545        // that checks the own-property descriptor fails if the property is missing.
12546        object.define("name", Property::name_or_length(self.string(name)));
12547        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12548        // when `[[Construct]]` is created, so an async function and an arrow function have
12549        // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12550        // function) an own `prototype` property, which `builtin.js` checks for absence.
12551        //
12552        // A **generator** function is the exception that is not constructible: it still
12553        // gets a `prototype` field, because that object is what a generator *instance*
12554        // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12555        // made `function* g(){}; g.prototype` `undefined` and every generator share
12556        // `%GeneratorPrototype%` as its direct prototype.
12557        if constructible {
12558            self.install_function_prototype(&object);
12559        } else if matches!(
12560            function_kind,
12561            js_compile::bytecode::FunctionKind::Generator
12562                | js_compile::bytecode::FunctionKind::AsyncGenerator
12563        ) {
12564            let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12565                self.realm.generator_proto.clone()
12566            } else {
12567                self.realm
12568                    .async_generator_proto
12569                    .clone()
12570                    .unwrap_or_else(|| self.realm.generator_proto.clone())
12571            };
12572            self.install_generator_prototype(&object, parent);
12573        }
12574        Ok(Value::Object(object))
12575    }
12576
12577    // -- conversions used by the operators ----------------------------------
12578
12579    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12580        // `+x` is `ToNumber`, which for a string parses it and for an object runs
12581        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12582        // string, which then behaves differently in every later comparison.
12583        match value {
12584            Value::Int(_) | Value::Float(_) => Ok(value),
12585            other => Ok(Value::Float(self.to_js_number(&other)?)),
12586        }
12587    }
12588
12589    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12590    ///
12591    /// Returns the *converted* old value and the new one, because the two callers need
12592    /// different halves: `++x` yields the new value, while `x++` yields the old one and
12593    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12594    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12595    /// boolean.
12596    ///
12597    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12598    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12599    /// a bigint algorithm then ran exactly once.
12600    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12601        if let Value::BigInt(big) = &value {
12602            let one = crate::bigint::BigInt::from_i64(1);
12603            let next = if up { big.add(&one) } else { big.sub(&one) };
12604            return Ok((value, self.bigint(next)));
12605        }
12606        let old = self.numeric(value)?;
12607        let new = if up {
12608            increment(old.clone())
12609        } else {
12610            decrement(old.clone())
12611        };
12612        Ok((old, new))
12613    }
12614
12615    fn numeric(&mut self, value: Value) -> JsResult<Value> {
12616        // `ToNumber` on an object runs `ToPrimitive` first, which is how
12617        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12618        // heard at all. Reading the object's own tag instead (`other.to_number()`)
12619        // turned the whole operand into `NaN` and swallowed the exception.
12620        match value {
12621            Value::Int(_) | Value::Float(_) => Ok(value),
12622            other => Ok(Value::Float(self.to_js_number(&other)?)),
12623        }
12624    }
12625
12626    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12627    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12628        match value {
12629            Value::BigInt(big) => Ok((**big).clone()),
12630            // The reference words this the same way for every operator, so a failing
12631            // script reads identically; the operator itself adds nothing a caller can use.
12632            _ => Err(Signal::Throw(
12633                self.make_error("TypeError", "cannot convert bigint to number"),
12634            )),
12635        }
12636    }
12637
12638    /// Arithmetic where at least one operand is a `BigInt`.
12639    ///
12640    /// The two numeric types never mix, so a bigint paired with anything else is an error
12641    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12642    /// that the relational operators handle it separately.
12643    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12644        use Opcode::*;
12645        let a = self.bigint_operand(&left)?;
12646        let b = self.bigint_operand(&right)?;
12647        let result = match op {
12648            Add => a.add(&b),
12649            Sub => a.sub(&b),
12650            Mul => a.mul(&b),
12651            Div | Mod => {
12652                let Some((quotient, remainder)) = a.div_rem(&b) else {
12653                    return Err(Signal::Throw(
12654                        self.make_error("RangeError", "division by zero"),
12655                    ));
12656                };
12657                if op == Div { quotient } else { remainder }
12658            }
12659            Pow => {
12660                let Some(value) = a.pow(&b) else {
12661                    return Err(Signal::Throw(self.make_error(
12662                        "RangeError",
12663                        "BigInt exponent must be non-negative and not absurdly large",
12664                    )));
12665                };
12666                value
12667            }
12668            And => a.bitand(&b),
12669            Or => a.bitor(&b),
12670            Xor => a.bitxor(&b),
12671            Shl | Sar => {
12672                // A shift count is a `BigInt` here, and both directions are exact; a
12673                // negative count would be the other direction, which the spec forbids.
12674                let Some(count) = b.to_i64() else {
12675                    return Err(Signal::Throw(
12676                        self.make_error("RangeError", "BigInt shift count is too large"),
12677                    ));
12678                };
12679                if count < 0 {
12680                    return Err(Signal::Throw(self.make_error(
12681                        "RangeError",
12682                        "BigInt shift count must be non-negative",
12683                    )));
12684                }
12685                if op == Shl {
12686                    a.shl(count as u64)
12687                } else {
12688                    a.shr(count as u64)
12689                }
12690            }
12691            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12692            _ => {
12693                return Err(Signal::Throw(self.make_error(
12694                    "TypeError",
12695                    "BigInts have no unsigned right shift, use >> instead",
12696                )));
12697            }
12698        };
12699        Ok(self.bigint(result))
12700    }
12701
12702    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12703    ///
12704    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12705    /// is on the mathematical values, and nothing is rounded first.
12706    /// `<`, `<=`, `>`, `>=`.
12707    ///
12708    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12709    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12710    /// It is a `?`-returning function for exactly that reason: an object operand can run
12711    /// script, and script can throw. The old version compared `to_number` of the raw
12712    /// values, which answered `false` for every object instead of calling `valueOf` —
12713    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12714    /// never ran.
12715    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12716        // The hot arm first: `i < n` with both sides already integers. No conversion, no
12717        // call, nothing that can throw.
12718        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12719            let ordering = Some(left.cmp(right));
12720            return Ok(ordering_answer(op, ordering));
12721        }
12722        // Anything that can run script has to be converted first, in this order.
12723        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12724        {
12725            (
12726                self.to_primitive(left, Hint::Number)?,
12727                self.to_primitive(right, Hint::Number)?,
12728            )
12729        } else {
12730            (left, right)
12731        };
12732        let ordering = match (&left, &right) {
12733            // The loop condition `i < n` is integer against integer, and it runs once
12734            // per iteration of every loop in every program. Without this arm it took the
12735            // `to_number` path twice, which is a `match` plus a conversion each.
12736            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12737            (Value::String(a), Value::String(b)) => {
12738                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12739            }
12740            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12741            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12742            // is true even though `2.5` has no bigint form.
12743            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12744                let b = other.to_number();
12745                if b.is_nan() {
12746                    None
12747                } else {
12748                    compare_bigint_and_f64(a, b)
12749                }
12750            }
12751            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12752                let a = other.to_number();
12753                if a.is_nan() {
12754                    None
12755                } else {
12756                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12757                }
12758            }
12759            // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
12760            // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
12761            // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
12762            _ => self
12763                .to_js_number(&left)?
12764                .partial_cmp(&self.to_js_number(&right)?),
12765        };
12766        Ok(ordering_answer(op, ordering))
12767    }
12768
12769    fn binary_add(&mut self) -> JsResult<()> {
12770        let right = self.pop();
12771        let left = self.pop();
12772        // Two integers add without any of the machinery below: no `ToPrimitive` (an
12773        // `Int` is already primitive), no string check, no bigint check, no allocation.
12774        // `x += 1` in a loop is the single most common instruction sequence in real
12775        // script, and it used to walk every one of those checks before reaching the
12776        // same `checked_add`.
12777        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12778            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12779            return Ok(());
12780        }
12781        let left = self.primitive_of(left)?;
12782        let right = self.primitive_of(right)?;
12783        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12784        // that check comes before the bigint one: `"" + 1n` is a string, not a
12785        // mixed-type error.
12786        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12787            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12788            // `TypeError`, the one place a symbol and a string do not mix.
12789            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12790            // between a copy and a rope from their lengths, and a rope is what turns
12791            // `text += "abc"` in a loop from quadratic into linear.
12792            if let (Value::String(left), Value::String(right)) = (&left, &right) {
12793                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12794                // reports as `InternalError: string too long`.
12795                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12796                    return Err(Signal::Throw(
12797                        self.make_error("InternalError", "string too long"),
12798                    ));
12799                };
12800                self.push(Value::String(Gc::new(self.heap, joined)));
12801                return Ok(());
12802            }
12803            // At least one operand was not a string, so `ToString` it. This rejects a
12804            // symbol, which is the one place a symbol and a string do not mix.
12805            let left = self.checked_to_wtf8(&left)?;
12806            let right = self.checked_to_wtf8(&right)?;
12807            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12808            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12809            let text = left.concat(&right);
12810            self.push(self.string_wtf8(text));
12811            return Ok(());
12812        }
12813        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12814        // not a conversion.
12815        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12816            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12817            self.push(value);
12818            return Ok(());
12819        }
12820        let left = self.numeric(left)?;
12821        let right = self.numeric(right)?;
12822        self.push(add_numbers(left, right));
12823        Ok(())
12824    }
12825
12826    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12827        self.to_primitive(value, Hint::Default)
12828    }
12829
12830    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12831    ///
12832    /// The order depends on the hint: the "number" order tries `valueOf` first and
12833    /// `toString` second, the "string" order the other way round, and the default
12834    /// hint uses the number order. A result that is still an object is a `TypeError`,
12835    /// because no built-in `valueOf`/`toString` returns one.
12836    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12837        let Value::Object(object) = &value else {
12838            return Ok(value);
12839        };
12840        // A Date overrides the default hint to mean "string", which is what
12841        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12842        // this, `"" + new Date()` would print the milliseconds, not the date.
12843        let hint = if hint == Hint::Default && is_date_object(self, object) {
12844            Hint::String
12845        } else {
12846            hint
12847        };
12848        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12849        // handed the hint as a string. This is the hook a Date uses for its default hint
12850        // and a script uses to take over conversion entirely.
12851        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12852        // `GetMethod`, not "is it a callable object": the property has to be read and then
12853        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12854        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12855        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12856        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12857        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12858        // callable.
12859        match self.get_property_key(object, &key)? {
12860            None | Some(Value::Undefined) | Some(Value::Null) => {}
12861            Some(Value::Object(function)) if function.is_callable() => {
12862                let hint = match hint {
12863                    Hint::String => "string",
12864                    Hint::Number => "number",
12865                    Hint::Default => "default",
12866                };
12867                let hint = self.string(hint);
12868                let result = self.call_value(
12869                    Value::Object(function),
12870                    Value::Object(object.clone()),
12871                    vec![hint],
12872                )?;
12873                if !matches!(result, Value::Object(_)) {
12874                    return Ok(result);
12875                }
12876                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12877            }
12878            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12879        }
12880        let order: [&str; 2] = match hint {
12881            Hint::String => ["toString", "valueOf"],
12882            Hint::Number | Hint::Default => ["valueOf", "toString"],
12883        };
12884        let receiver = object.clone();
12885        for method in order {
12886            if let Some(function) = self.get_property(&receiver, method)?
12887                && matches!(&function, Value::Object(object) if object.is_callable())
12888            {
12889                let result =
12890                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12891                if !matches!(result, Value::Object(_)) {
12892                    return Ok(result);
12893                }
12894            }
12895        }
12896        Err(self.type_error("cannot convert object to primitive value"))
12897    }
12898
12899    /// `ToString` with the object case going through `ToPrimitive`.
12900    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12901        if matches!(value, Value::Object(_)) {
12902            let primitive = self.to_primitive(value.clone(), Hint::String)?;
12903            return Ok(primitive.to_js_string());
12904        }
12905        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12906        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12907        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12908        // check here broke `String(Symbol())` and 45 cases that print a symbol.
12909        Ok(value.to_js_string())
12910    }
12911
12912    /// `ToString(value)`, with §7.1.19's symbol refusal.
12913    ///
12914    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12915    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12916    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12917    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12918        if matches!(value, Value::Symbol(_)) {
12919            return Err(self.type_error("cannot convert a Symbol to a string"));
12920        }
12921        if matches!(value, Value::Object(_)) {
12922            let primitive = self.to_primitive(value.clone(), Hint::String)?;
12923            if matches!(primitive, Value::Symbol(_)) {
12924                return Err(self.type_error("cannot convert a Symbol to a string"));
12925            }
12926            return Ok(primitive.to_js_string());
12927        }
12928        Ok(value.to_js_string())
12929    }
12930
12931    /// `ToString` that keeps the string's code units instead of flattening them.
12932    ///
12933    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12934    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12935    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12936        if matches!(value, Value::Symbol(_)) {
12937            return Err(Signal::Throw(
12938                self.make_error("TypeError", "cannot convert symbol to string"),
12939            ));
12940        }
12941        // An object runs `ToPrimitive` first, which may itself produce a symbol.
12942        let value = self.to_primitive(value.clone(), Hint::String)?;
12943        match value {
12944            Value::Symbol(_) => Err(Signal::Throw(
12945                self.make_error("TypeError", "cannot convert symbol to string"),
12946            )),
12947            Value::String(text) => Ok(text.wtf8().clone()),
12948            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12949        }
12950    }
12951
12952    /// `ToNumber` with the object case going through `ToPrimitive`.
12953    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12954        let value = if matches!(value, Value::Object(_)) {
12955            self.to_primitive(value.clone(), Hint::Number)?
12956        } else {
12957            value.clone()
12958        };
12959        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12960        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12961        // `NaN` to stay total, and the operators check for the bigint themselves — but
12962        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12963        // refuse, and answering `NaN` made them silently wrong instead.
12964        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12965        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12966        match value {
12967            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12968            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12969            other => Ok(other.to_number()),
12970        }
12971    }
12972
12973    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12974    /// [`ElementType::write`].
12975    ///
12976    /// This is separated from the write because both conversions are observable script —
12977    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12978    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12979    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12980    /// setters, and a plain `a[i] = v`.
12981    pub(crate) fn element_value(
12982        &mut self,
12983        element: crate::builtins::typedarray::ElementType,
12984        value: Value,
12985    ) -> JsResult<Value> {
12986        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12987        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12988        let primitive = match &value {
12989            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12990            _ => value,
12991        };
12992        if element.is_bigint() {
12993            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12994            Ok(Value::BigInt(Gc::new(self.heap, big)))
12995        } else {
12996            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12997            Ok(Value::Float(self.to_js_number(&primitive)?))
12998        }
12999    }
13000
13001    /// `ToPropertyKey`: what a computed member access uses as its key.
13002    ///
13003    /// A symbol is returned as itself, never stringified — that is what keeps
13004    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13005    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13006        match value {
13007            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13008            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13009            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13010            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13011            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13012                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13013                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13014                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13015                    other.to_js_string(),
13016                ))),
13017            },
13018            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13019        }
13020    }
13021
13022    /// `ToPropertyKey` for the callers that can only use a string key.
13023    ///
13024    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13025    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13026    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13027    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13028    /// program continues with a value nobody asked for.
13029    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13030        use crate::value::Wtf8;
13031        Ok(match value {
13032            // A string key keeps its code units. Going through a lossy `String` would make
13033            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13034            Value::String(text) => text.wtf8().clone(),
13035            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13036            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13037            // falling back to its `ToString` would print `[object Object]`.
13038            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13039                Value::String(text) => text.wtf8().clone(),
13040                other => Wtf8::new(other.to_js_string()),
13041            },
13042            other => Wtf8::new(other.to_js_string()),
13043        })
13044    }
13045
13046    // -- object operations used by instructions -----------------------------
13047
13048    /// Read `object[key]`, returning `undefined` when the property is missing.
13049    ///
13050    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13051    /// primitive (looking through its prototype) as well as an object — which is what
13052    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13053    /// argument needs too.
13054    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13055        self.read_field_key(object, &PropertyKey::from(key))
13056    }
13057
13058    /// [`Interp::read_field`] with a key that may be a symbol.
13059    ///
13060    /// A symbol key never reaches the string shortcuts: a string's `length` and its
13061    /// indices are string properties, and a symbol named `length` is a different
13062    /// property that a string primitive cannot have.
13063    /// [`Interp::read_field_key`], with an inline cache in front of it.
13064    ///
13065    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13066    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13067    /// without this the engine walked the chain and compared ~40 property names on each
13068    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13069    ///
13070    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13071    /// missing property. Those answers depend on running code or on state the guard below
13072    /// does not cover, and a wrong answer here is far more expensive than a lookup.
13073    ///
13074    /// A hit is re-validated against the *whole* walked chain, not just the level that
13075    /// answered: the receiver and every prototype down to that level must still be the same
13076    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13077    /// property-table *lengths* — which is what catches a property appearing on an
13078    /// intermediate prototype and shadowing the cached one.
13079    pub fn read_field_cached(
13080        &mut self,
13081        object: &Value,
13082        key: &PropertyKey,
13083        slot: usize,
13084    ) -> JsResult<Value> {
13085        let index = Self::field_cache_slot(object, key, slot);
13086        let Value::Object(target) = object else {
13087            return self.read_field_key(object, key);
13088        };
13089        if target.proxy_state().is_some() {
13090            return self.read_field_key(object, key);
13091        }
13092        if let Some(cached) = &self.field_cache[index]
13093            && cached.key == *key
13094            && let Some(value) = Self::cached_hit(target, cached)
13095        {
13096            return Ok(value);
13097        }
13098        let value = self.read_field_key(object, key)?;
13099        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13100        Ok(value)
13101    }
13102
13103    /// Whether a cache entry still describes this lookup, and if so the value.
13104    ///
13105    /// The guard is the whole point of the entry: identity plus property-table length for
13106    /// every level walked. Re-checked per level rather than once at the receiving end,
13107    /// because a shadowing property can appear anywhere along the chain.
13108    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13109        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13110        // starts with: a clone is a reference-count bump and a drop, and for
13111        // `property:monomorphic` every single hit takes only this arm.
13112        let (weak, len) = cached.chain[0].as_ref()?;
13113        if !target.upgrades_to(weak) {
13114            return None;
13115        }
13116        if cached.level == 0 {
13117            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13118            return target.cached_property_at(cached.index, &cached.key, *len);
13119        }
13120        if target.props_len() != *len {
13121            return None;
13122        }
13123        let mut level = 1;
13124        let mut current = target.proto()?;
13125        loop {
13126            let (weak, len) = cached.chain[level].as_ref()?;
13127            if !current.upgrades_to(weak) || current.props_len() != *len {
13128                return None;
13129            }
13130            if level == cached.level as usize {
13131                // The level that answered: the value is only reusable while the key is
13132                // still there and still a plain data property.
13133                return current.cached_data_property(cached.index, &cached.key);
13134            }
13135            current = current.proto()?;
13136            level += 1;
13137        }
13138    }
13139
13140    /// Build a cache entry for a lookup that just went through the slow path.
13141    ///
13142    /// Records the chain only when the answer came from a plain data property at a level
13143    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13144    /// costs the next lookup the walk it would have cost anyway.
13145    fn record_field_lookup(
13146        target: &Gc<JsObject>,
13147        key: &PropertyKey,
13148        _value: Value,
13149    ) -> Option<FieldCache> {
13150        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13151            [None, None, None];
13152        let mut current = target.clone();
13153        for level in 0..MAX_CACHED_CHAIN {
13154            chain[level] = Some((current.downgrade(), current.props_len()));
13155            if let Some((found, _)) = current.own_property_index(key) {
13156                // `own_property_index` declines an accessor and a hole, which is exactly
13157                // the set that must not be cached.
13158                return Some(FieldCache {
13159                    key: key.clone(),
13160                    index: found,
13161                    level: level as u8,
13162                    chain,
13163                });
13164            }
13165            current = current.proto()?;
13166        }
13167        None
13168    }
13169
13170    /// Which cache slot a lookup uses.
13171    ///
13172    /// Mixes the object's address, the name and the site, so that two properties of one
13173    /// object, and one property of two objects, land in different slots — which is what lets
13174    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13175    /// other iteration.
13176    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13177        let mut hash = match object {
13178            Value::Object(object) => object.address(),
13179            _ => 0,
13180        };
13181        hash = hash
13182            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13183            .rotate_left(17)
13184            .wrapping_add(key.hash_code());
13185        hash = hash.wrapping_add(site.wrapping_mul(31));
13186        // The table is a power of two, so the low bits are the slot.
13187        hash & (FIELD_CACHE_SLOTS - 1)
13188    }
13189
13190    /// Read `key` from `object`, without the inline cache.
13191    ///
13192    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13193    /// prototype chain, while the cached form answers an own data property from memory.
13194    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13195        let text = key.as_str().unwrap_or("");
13196        let Value::Object(object) = object else {
13197            // Reading a property of `undefined`/`null` is the classic TypeError.
13198            if object.is_nullish() {
13199                return Err(Signal::Throw(self.make_error(
13200                    "TypeError",
13201                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
13202                )));
13203            }
13204            // A string has `length` and index access without being boxed.
13205            if let Value::String(value) = object {
13206                if text == "length" {
13207                    return Ok(Value::Int(value.utf16_len() as i32));
13208                }
13209                if let Some(index) = array_index(text) {
13210                    return Ok(match value.wtf8().unit_at(index as usize) {
13211                        Some(unit) => self.string_wtf8(unit),
13212                        None => Value::Undefined,
13213                    });
13214                }
13215            }
13216            // A property of a primitive is looked up on its prototype: this is what
13217            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13218            let prototype = match object {
13219                Value::String(_) => self.realm.string_proto.clone(),
13220                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13221                Value::Bool(_) => self.realm.boolean_proto.clone(),
13222                // A symbol's methods live on `Symbol.prototype`, reached the same way —
13223                // `sym.description` reads through the prototype, not off the symbol.
13224                Value::Symbol(_) => self.realm.symbol_proto.clone(),
13225                // …and a bigint's on `BigInt.prototype`, which is how
13226                // `(255n).toString(16)` reaches its method.
13227                Value::BigInt(_) => self.realm.bigint_proto.clone(),
13228                _ => None,
13229            };
13230            if let Some(prototype) = prototype
13231                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13232            {
13233                return Ok(value);
13234            }
13235            return Ok(Value::Undefined);
13236        };
13237        Ok(self
13238            .get_property_key(object, key)?
13239            .unwrap_or(Value::Undefined))
13240    }
13241
13242    /// The `#name` a private symbol stands for, for error messages.
13243    ///
13244    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13245    /// was made from.
13246    fn private_name(symbol: &Value) -> Option<String> {
13247        match symbol {
13248            Value::Symbol(symbol) if symbol.is_private() => Some(
13249                symbol
13250                    .description()
13251                    .map(|text| text.to_string())
13252                    .unwrap_or_default(),
13253            ),
13254            _ => None,
13255        }
13256    }
13257
13258    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13259    ///
13260    /// Every private-field opcode takes the symbol the class stored in its own scope; a
13261    /// non-symbol here would be a compiler bug, and the reference guards it with
13262    /// `JS_ThrowTypeErrorNotASymbol`.
13263    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13264        match symbol {
13265            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13266            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13267        }
13268    }
13269
13270    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13271    ///
13272    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13273    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13274    /// would hit if the parser did not reject it first.
13275    fn define_private_field(
13276        &mut self,
13277        object: &Value,
13278        symbol: &Value,
13279        value: Value,
13280    ) -> JsResult<()> {
13281        let key = self.private_key(symbol)?;
13282        let Some(target) = object.as_object() else {
13283            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13284        };
13285        if !target.is_extensible() {
13286            return Err(Signal::Throw(
13287                self.make_error("TypeError", "object is not extensible"),
13288            ));
13289        }
13290        if target.own_property_key(&key).is_some() {
13291            let name = Self::private_name(symbol).unwrap_or_default();
13292            return Err(Signal::Throw(self.make_error(
13293                "TypeError",
13294                &format!("private class field '{name}' already exists"),
13295            )));
13296        }
13297        target.define_data_key(&key, value);
13298        Ok(())
13299    }
13300
13301    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13302    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13303        let key = self.private_key(symbol)?;
13304        let Some(target) = object.as_object() else {
13305            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13306        };
13307        match target.own_property_key(&key) {
13308            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13309            None => {
13310                let name = Self::private_name(symbol).unwrap_or_default();
13311                Err(Signal::Throw(self.make_error(
13312                    "TypeError",
13313                    &format!("private class field '{name}' does not exist"),
13314                )))
13315            }
13316        }
13317    }
13318
13319    /// `JS_SetPrivateField`: the store half of the same rule.
13320    fn write_private_field(
13321        &mut self,
13322        object: &Value,
13323        symbol: &Value,
13324        value: Value,
13325    ) -> JsResult<()> {
13326        let key = self.private_key(symbol)?;
13327        let Some(target) = object.as_object() else {
13328            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13329        };
13330        if target.write_value_key(&key, value) {
13331            return Ok(());
13332        }
13333        let name = Self::private_name(symbol).unwrap_or_default();
13334        Err(Signal::Throw(self.make_error(
13335            "TypeError",
13336            &format!("private class field '{name}' does not exist"),
13337        )))
13338    }
13339
13340    /// The `in` half: does `object` have this private field?
13341    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13342    ///
13343    /// The symbol is created once per class — the first `add_brand` on a given home object
13344    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13345    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13346    /// emit for the *instance* brand passes null because all it wants is the symbol.
13347    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13348        let Some(home_object) = home.as_object() else {
13349            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13350        };
13351        let symbol = match home_object.private_brand() {
13352            Some(symbol) => symbol,
13353            None => {
13354                let symbol = Gc::new(
13355                    self.heap,
13356                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13357                );
13358                home_object.set_private_brand(symbol.clone());
13359                symbol
13360            }
13361        };
13362        let Some(target) = object.as_object() else {
13363            // Not an object: nothing to brand. The reference does the same, and `undefined`
13364            // here would otherwise turn a field initialiser into a TypeError.
13365            return Ok(());
13366        };
13367        if !target.is_extensible() {
13368            return Err(Signal::Throw(
13369                self.make_error("TypeError", "object is not extensible"),
13370            ));
13371        }
13372        if target.carries_brand(&symbol) {
13373            return Err(Signal::Throw(
13374                self.make_error("TypeError", "private method is already present"),
13375            ));
13376        }
13377        target.add_brand(symbol);
13378        Ok(())
13379    }
13380
13381    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13382    ///
13383    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13384    /// decides whether to throw.
13385    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13386        let Some(function) = function.as_object() else {
13387            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13388        };
13389        let Some(home) = function.home_object() else {
13390            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13391        };
13392        let Some(brand) = home.private_brand() else {
13393            return Err(Signal::Throw(
13394                self.make_error("TypeError", "expecting <brand> private field"),
13395            ));
13396        };
13397        Ok(object.carries_brand(&brand))
13398    }
13399
13400    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13401        let Value::Object(object) = object else {
13402            // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13403            // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13404            // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13405            // `undefined` still throw, with their own message.
13406            if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13407                return Ok(());
13408            }
13409            return Err(Signal::Throw(self.make_error(
13410                "TypeError",
13411                &format!("cannot set property '{key}' of {}", object.to_js_string()),
13412            )));
13413        };
13414        // The write half of the property inline cache, in effect: an own, writable,
13415        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13416        // decide — no prototype walk (an own property shadows the chain before a setter
13417        // there could matter), no extensibility check (the object already has the key),
13418        // and no `[[DefineOwnProperty]]`.
13419        //
13420        // `this.value = …` inside a method is the whole write side of
13421        // `property:method-call`, and it was reaching `set_property_with_key` with its
13422        // proxy test, its typed-array test, its array-index test and finally a linear
13423        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13424        //
13425        // Every disqualifier is checked here: a proxy traps the set, an array index and
13426        // `length` live outside the property table, and a typed array's element is stored
13427        // through its view's element type.
13428        if object.proxy_state().is_none()
13429            && !object.is_array()
13430            && object.typed_array_element_type().is_none()
13431            && object.write_value_key(key, value.clone())
13432        {
13433            return Ok(());
13434        }
13435        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13436        let on_failure = if self.frame().code.code.strict {
13437            DeleteFailure::Throw
13438        } else {
13439            DeleteFailure::Ignore
13440        };
13441        self.set_property_with_key(object, key, value, on_failure)
13442    }
13443
13444    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13445    ///
13446    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13447    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13448    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13449    /// `Number.parseInt(sym)` — so those callers use this instead.
13450    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13451        if matches!(value, Value::Symbol(_)) {
13452            return Err(Signal::Throw(
13453                self.make_error("TypeError", "cannot convert symbol to string"),
13454            ));
13455        }
13456        // An object runs `ToPrimitive` first, which may itself produce a symbol —
13457        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13458        let value = self.to_primitive(value.clone(), Hint::String)?;
13459        if matches!(value, Value::Symbol(_)) {
13460            return Err(Signal::Throw(
13461                self.make_error("TypeError", "cannot convert symbol to string"),
13462            ));
13463        }
13464        Ok(value.to_js_string())
13465    }
13466
13467    /// `ToPropertyKey` for a builtin that takes a key argument.
13468    ///
13469    /// Fallible: a key whose `toString` throws has to propagate that error, both for
13470    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13471    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13472    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13473    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13474        self.propkey(value)
13475    }
13476
13477    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13478    ///
13479    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13480    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13481    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13482    /// `RangeError` — and why this cannot be a plain `ToNumber`.
13483    /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13484    ///
13485    /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13486    /// then a `RangeError` when they disagree. Two conversions rather than one is
13487    /// observable: a `valueOf` that runs the first time can make `length` non-writable
13488    /// before the second, which turns the store into a refused write
13489    /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13490    pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13491        let first = self.array_length_of(value)?;
13492        let second = self.array_length_of(value)?;
13493        debug_assert_eq!(first, second);
13494        Ok(first)
13495    }
13496
13497    /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13498    ///
13499    /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13500    /// conversion can say so; a caller that needs the spec's two uses that instead.
13501    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13502        let number = match value {
13503            Value::Int(number) => *number as f64,
13504            Value::Float(number) => *number,
13505            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13506            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13507            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13508            // reference answers 0.
13509            Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13510            // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13511            // `"  5  "` is 5, which is exactly what `string_to_number` implements.
13512            Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13513            _ => {
13514                // The primitive comes back through this same conversion, so a wrapper of a
13515                // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13516                // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13517                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13518                return self.array_length_of(&primitive);
13519            }
13520        };
13521        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13522        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13523        // is a `RangeError`, not `0`.
13524        if !number.is_finite()
13525            || number.fract() != 0.0
13526            || !(0.0..=u32::MAX as f64).contains(&number)
13527        {
13528            return Err(self.range_error("invalid array length"));
13529        }
13530        Ok(number as u32)
13531    }
13532
13533    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13534    /// `Object.getOwnPropertySymbols` put in their result array.
13535    pub fn key_value(&self, key: &PropertyKey) -> Value {
13536        match key {
13537            PropertyKey::String(text) => self.string_wtf8(text.clone()),
13538            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13539        }
13540    }
13541
13542    /// Fill in a String exotic object: `_value`, `length` and the index properties.
13543    ///
13544    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13545    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13546    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13547    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13548    /// the two paths had drifted; this is the one both now use.
13549    ///
13550    /// The indices are *code units*, so an astral character occupies two of them — the
13551    /// same rule `s.length` and `s[i]` follow.
13552    /// Give an already-created object the internal slot that makes it a wrapper of
13553    /// `value`, so the primitive's prototype methods work on it.
13554    ///
13555    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13556    /// which are wrappers of their own type holding the empty value.
13557    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13558        self.internal_set(object, "_value", value);
13559    }
13560
13561    pub(crate) fn init_string_wrapper(
13562        &mut self,
13563        object: &Gc<JsObject>,
13564        text: &Gc<crate::value::JsString>,
13565    ) {
13566        object.define(
13567            "length",
13568            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13569        );
13570        for index in 0..text.utf16_len() {
13571            if let Some(unit) = text.wtf8().unit_at(index) {
13572                object.define(
13573                    &index.to_string(),
13574                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13575                    Property::with_attributes(self.string_wtf8(unit), false, true),
13576                );
13577            }
13578        }
13579        object.define_key(
13580            &self.internal_slot("_value"),
13581            Property::with_attributes(Value::String(text.clone()), false, false),
13582        );
13583    }
13584
13585    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13586    ///
13587    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13588    /// throws. The wrapper carries its primitive in `_value` — the same slot
13589    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13590    /// on a boxed value no constructor ever built.
13591    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13592        let (prototype, primitive) = match value {
13593            Value::Object(object) => return Ok(object.clone()),
13594            Value::String(text) => {
13595                let object = self.new_object(self.realm.string_proto.clone());
13596                self.init_string_wrapper(&object, text);
13597                return Ok(object);
13598            }
13599            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13600            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13601            // A symbol and a bigint box into wrappers whose methods live on
13602            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13603            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13604            // branch below instead produced an object with *no* prototype, so those
13605            // methods were unreachable on a box.
13606            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13607            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13608            Value::Undefined | Value::Null => {
13609                return Err(Signal::Throw(self.make_error(
13610                    "TypeError",
13611                    &format!("cannot convert {} to object", value.to_js_string()),
13612                )));
13613            }
13614            _ => (None, value.clone()),
13615        };
13616        let object = self.new_object(prototype);
13617        self.internal_set(&object, "_value", primitive);
13618        Ok(object)
13619    }
13620
13621    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13622    ///
13623    /// Split out for a reader that has to create the object *before* it knows what it wraps:
13624    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13625    /// written before its primitive, so the placeholder has to exist first and be filled in
13626    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13627    /// than a second in the deserialiser.
13628    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13629        let prototype = match value {
13630            Value::String(_) => self.realm.string_proto.clone(),
13631            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13632            Value::Bool(_) => self.realm.boolean_proto.clone(),
13633            Value::Symbol(_) => self.realm.symbol_proto.clone(),
13634            Value::BigInt(_) => self.realm.bigint_proto.clone(),
13635            _ => {
13636                return Err(Signal::Throw(self.make_error(
13637                    "TypeError",
13638                    &format!("cannot box {}", value.to_js_string()),
13639                )));
13640            }
13641        };
13642        object.set_proto(prototype);
13643        if let Value::String(text) = value {
13644            self.init_string_wrapper(object, text);
13645            return Ok(());
13646        }
13647        self.internal_set(object, "_value", value.clone());
13648        Ok(())
13649    }
13650
13651    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13652    ///
13653    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13654    /// through the `Symbol` function object, so the registry is reachable as a method rather
13655    /// than only from `builtins::symbol`.
13656    pub fn symbol_for(&mut self, key: &str) -> Value {
13657        if let Some(existing) = self.realm.symbol_registry.get(key) {
13658            return existing.clone();
13659        }
13660        let symbol = crate::builtins::symbol::symbol_value(
13661            self,
13662            crate::value::JsSymbol::registered(key.to_string()),
13663        );
13664        self.realm
13665            .symbol_registry
13666            .insert(key.to_string(), symbol.clone());
13667        symbol
13668    }
13669
13670    /// `a == b`, the coercing comparison.
13671    ///
13672    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13673    /// which is what makes `[] == ""` true: `[]` becomes `""` via
13674    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13675    /// because the conversion is allowed to call script code, so the two primitive
13676    /// operands are handed back to it.
13677    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13678        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13679            return Ok(left.loose_equals(&right));
13680        }
13681        // `null == undefined` holds even though neither is an object.
13682        if matches!(left, Value::Undefined | Value::Null)
13683            && matches!(right, Value::Undefined | Value::Null)
13684        {
13685            return Ok(true);
13686        }
13687        if matches!(left, Value::Undefined | Value::Null)
13688            || matches!(right, Value::Undefined | Value::Null)
13689        {
13690            return Ok(false);
13691        }
13692        // Two objects compare by identity. Only an object *against a primitive* is
13693        // converted, which is why `{} == {}` is false while `[] == ""` is true.
13694        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13695            return Ok(a.ptr_eq(b));
13696        }
13697        let left = self.to_primitive(left, Hint::Default)?;
13698        let right = self.to_primitive(right, Hint::Default)?;
13699        Ok(left.loose_equals(&right))
13700    }
13701
13702    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13703        let Value::Object(object) = object else {
13704            return Err(Signal::Throw(
13705                self.make_error("TypeError", "cannot use 'in' on a non-object"),
13706            ));
13707        };
13708        let key = self.propkey(key)?;
13709        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13710        // trap. One implementation, so an array's derived `length` and its inherited holes
13711        // cannot be right in one caller and wrong in another.
13712        self.has_own_or_inherited(object, &key)
13713    }
13714
13715    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13716    ///
13717    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13718    /// whole reason the operator is a hook rather than a prototype walk.
13719    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13720        if let Value::Object(function) = constructor {
13721            let key = self.realm.well_known_key(WellKnown::HasInstance);
13722            let method = self.get_property_key(function, &key)?;
13723            if let Some(method) = method
13724                && !matches!(method, Value::Undefined)
13725            {
13726                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13727                return Ok(answer.to_boolean());
13728            }
13729        }
13730        self.instance_of(object, constructor)
13731    }
13732
13733    /// `OrdinaryHasInstance`: the prototype walk on its own.
13734    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13735        self.instance_of(object, constructor)
13736    }
13737
13738    /// `IsArray`: an array, or a proxy whose target is one.
13739    ///
13740    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13741    /// makes `Array.isArray(new Proxy([], {}))` true.
13742    pub fn is_array_value(&self, value: &Value) -> bool {
13743        match value {
13744            Value::Object(object) => {
13745                if let Some(state) = object.proxy_state() {
13746                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13747                }
13748                object.is_array()
13749            }
13750            _ => false,
13751        }
13752    }
13753
13754    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13755    ///
13756    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13757    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13758    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13759    /// see [`Interp::enqueue_job_function`].
13760    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13761        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13762        // the handler is reported rather than lost — the same reason a `then` reaction needs a
13763        // promise to settle.
13764        let promise = self.new_promise();
13765        self.fulfill_promise(&promise, Value::Undefined);
13766        self.jobs.push_back(Job::Reaction {
13767            handler: Some(function),
13768            argument: Value::Undefined,
13769            rejected: false,
13770            promise,
13771        });
13772        Ok(())
13773    }
13774
13775    /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13776    ///
13777    /// Four of its steps were missing or wrong, and each one is a test262 case in
13778    /// `Function/prototype/Symbol.hasInstance/`:
13779    ///
13780    /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13781    /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13782    ///   `[[BoundThis]]` standing in for the object when that is an object), which is why
13783    ///   `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13784    ///   `prototype` of its own, so without this step the walk below gives `false`;
13785    /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13786    /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13787    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13788        let Value::Object(function) = constructor else {
13789            return Ok(false);
13790        };
13791        if !function.is_callable() {
13792            return Ok(false);
13793        }
13794        // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13795        // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13796        // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13797        if let Some((target, this)) = function.bound_target_and_this() {
13798            let object = if this.as_object().is_some() {
13799                this
13800            } else {
13801                object.clone()
13802            };
13803            return self.instance_of(&object, &target);
13804        }
13805        let Value::Object(target) = object else {
13806            return Ok(false);
13807        };
13808        let prototype = self.get_property(function, "prototype")?;
13809        let Some(Value::Object(prototype)) = prototype else {
13810            return Err(Signal::Throw(self.make_error(
13811                "TypeError",
13812                "function has non-object prototype in instanceof check",
13813            )));
13814        };
13815        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13816        // which is also what makes `proxyOfInstance instanceof C` work.
13817        let mut current = Some(target.clone());
13818        while let Some(object) = current {
13819            if object.ptr_eq(&prototype) {
13820                return Ok(true);
13821            }
13822            current = self.object_prototype_of(&object)?;
13823        }
13824        Ok(false)
13825    }
13826
13827    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13828    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13829        if let Some(proto) = self.proxy_get_prototype_of(object)? {
13830            return Ok(proto);
13831        }
13832        if let Some(exotic) = object.exotic()
13833            && let Some(proto) = exotic.get_prototype(self, object)?
13834        {
13835            return Ok(proto);
13836        }
13837        Ok(object.proto())
13838    }
13839
13840    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13841    pub fn object_set_prototype_of(
13842        &mut self,
13843        object: &Gc<JsObject>,
13844        proto: Option<Gc<JsObject>>,
13845    ) -> JsResult<bool> {
13846        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13847            return Ok(answer);
13848        }
13849        if let Some(exotic) = object.exotic()
13850            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13851        {
13852            return Ok(answer);
13853        }
13854        // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
13855        // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
13856        // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
13857        // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
13858        if self
13859            .internal_get(object, "_immutable_proto")
13860            .is_some_and(|flag| flag.to_boolean())
13861            && !same_proto(object.proto().as_ref(), proto.as_ref())
13862        {
13863            return Ok(false);
13864        }
13865        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13866        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13867        // inheriting from itself, which every later prototype walk then had to defend
13868        // against — and `Reflect.setPrototypeOf` reported success for an operation the
13869        // language says is impossible.
13870        if let Some(proto) = &proto {
13871            let mut current = Some(proto.clone());
13872            let mut guard = 0;
13873            while let Some(node) = current {
13874                if node.ptr_eq(object) {
13875                    // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
13876                    // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
13877                    // while `Reflect.setPrototypeOf` reports it
13878                    // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
13879                    return Ok(false);
13880                }
13881                guard += 1;
13882                if guard > 1000 {
13883                    break;
13884                }
13885                current = node.proto();
13886            }
13887        }
13888        // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13889        // re-setting it to the *same* one is a no-op `true`. Missing this made
13890        // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13891        // actually reparent the object — and it is what
13892        // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13893        // forwarding path has nothing else left to refuse it.
13894        if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13895            return Ok(false);
13896        }
13897        object.set_proto(proto);
13898        Ok(true)
13899    }
13900
13901    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13902    ///
13903    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13904    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13905    /// already one.
13906    /// `HasProperty(O, P)`.
13907    ///
13908    /// One implementation, shared with the `in` operator. It used to be a second copy that
13909    /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
13910    /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
13911    /// proxy ran the wrong hook and could even disagree with `in`. The
13912    /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
13913    /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
13914    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13915        self.has_own_or_inherited(object, key)
13916    }
13917
13918    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13919    ///
13920    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13921    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13922    /// boolean as well, and it needs the receiver to be the one the caller named.
13923    pub fn set_property_with_key_receiver(
13924        &mut self,
13925        object: &Gc<JsObject>,
13926        key: &PropertyKey,
13927        value: Value,
13928        receiver: Option<&Value>,
13929        on_failure: DeleteFailure,
13930    ) -> JsResult<bool> {
13931        let receiver = receiver
13932            .cloned()
13933            .unwrap_or_else(|| Value::Object(object.clone()));
13934        if object.proxy_state().is_some() {
13935            return match self.proxy_set(object, key, value, &receiver)? {
13936                Some(accepted) => Ok(accepted),
13937                None => Ok(true),
13938            };
13939        }
13940        // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
13941        // receiver. This has to be answered here as well as in the storing path below,
13942        // because `Reflect.set` reports the refusal as a `bool` instead of raising.
13943        if object.module_namespace_marker() {
13944            return Ok(false);
13945        }
13946        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13947        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13948        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13949        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13950        //
13951        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13952        //
13953        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13954        // * an *invalid* index with a different receiver answers `true` and does nothing,
13955        //   not even converting `V` (`valueOfCalls` stays 0);
13956        // * a valid index with a different receiver falls through to
13957        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13958        //   value lands on the **receiver**, unconverted, and can be refused by a
13959        //   non-extensible receiver, an accessor, or a read-only index there.
13960        //
13961        // The last one used to write into the view itself, which left `target[0]` changed
13962        // and `receiver[0]` untouched — backwards.
13963        if object.typed_array_element_type().is_some()
13964            && let Some(numeric) = canonical_numeric_index(key)
13965        {
13966            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13967            if same {
13968                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13969                return Ok(true);
13970            }
13971            if !typed_array_index_is_valid(object, numeric) {
13972                return Ok(true);
13973            }
13974            let Some(receiver) = receiver.as_object().cloned() else {
13975                return Ok(false);
13976            };
13977            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13978                if existing.is_accessor() || !existing.writable {
13979                    return Ok(false);
13980                }
13981                let property = Property {
13982                    value: Some(value),
13983                    ..existing
13984                };
13985                return self.object_define_own_property(&receiver, key, property);
13986            }
13987            return self.object_define_own_property(&receiver, key, Property::data(value));
13988        }
13989        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13990        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13991        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13992        // `Reflect.set` to *report* the refusal instead of raising.
13993        //
13994        // A receiver that is not the object turns the whole operation into
13995        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13996        // `[[Set]]` rather than a lookup — that is what makes
13997        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13998        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13999        // writes to `object`, so it cannot express that and is only used when the two are
14000        // the same.
14001        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14002        if !same {
14003            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14004        }
14005        // Same receiver: the plain path below writes into `object`, which is right, but it
14006        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14007        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14008        if let Some(existing) = self.object_get_own_property(object, key)? {
14009            if existing.is_accessor() {
14010                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14011                    Some(setter) => {
14012                        self.call_value(setter, receiver, vec![value])?;
14013                        Ok(true)
14014                    }
14015                    None => Ok(false),
14016                };
14017            }
14018            if !existing.writable {
14019                return Ok(false);
14020            }
14021        }
14022        // Otherwise it is an ordinary create-or-write into `object` itself.
14023        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14024        Ok(true)
14025    }
14026
14027    /// `[[IsExtensible]]`, with the proxy trap when there is one.
14028    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14029        if let Some(answer) = self.proxy_is_extensible(object)? {
14030            return Ok(answer);
14031        }
14032        if let Some(exotic) = object.exotic()
14033            && let Some(answer) = exotic.is_extensible(self, object)?
14034        {
14035            return Ok(answer);
14036        }
14037        Ok(object.is_extensible())
14038    }
14039
14040    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14041    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14042        if let Some(answer) = self.proxy_prevent_extensions(object)? {
14043            return Ok(answer);
14044        }
14045        // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14046        //
14047        // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14048        //
14049        // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14050        // created with an explicit length, because the buffer can still move it. That is
14051        // what makes `Object.freeze` refuse every such view, including a zero-length one
14052        // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14053        // plain buffer is allowed.
14054        if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14055            && buffer
14056                .array_buffer_storage()
14057                .is_some_and(|storage| storage.borrow().is_resizable())
14058        {
14059            return Err(
14060                self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14061            );
14062        }
14063        if let Some(exotic) = object.exotic()
14064            && let Some(answer) = exotic.prevent_extensions(self, object)?
14065        {
14066            return Ok(answer);
14067        }
14068        object.set_extensible(false);
14069        Ok(true)
14070    }
14071
14072    fn copy_properties(
14073        &mut self,
14074        target: &Value,
14075        source: &Value,
14076        exclusion: &Value,
14077    ) -> JsResult<()> {
14078        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14079        // does contribute: its index properties are own, enumerable and writable, which
14080        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14081        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14082        // is a no-op.
14083        let Some(target) = target.as_object() else {
14084            return Ok(());
14085        };
14086        let source_object = match source {
14087            Value::Object(object) => object.clone(),
14088            Value::String(text) => {
14089                // Untaken keys are the string's indices, which are code units.
14090                for index in 0..text.utf16_len() {
14091                    if let Some(unit) = text.wtf8().unit_at(index) {
14092                        target.define_data(&index.to_string(), self.string_wtf8(unit));
14093                    }
14094                }
14095                return Ok(());
14096            }
14097            _ => return Ok(()),
14098        };
14099        // An object *rest* element passes the keys already taken by the literal part as
14100        // an array of strings; a spread passes `null`, which excludes nothing. Only the
14101        // string keys of the exclusion array are meaningful, so an array is read by its
14102        // elements rather than by its own property names.
14103        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
14104        if let Value::Object(list) = exclusion
14105            && let Some(length) = list.array_length()
14106        {
14107            for index in 0..length {
14108                if let Some(value) = list.array_get(index) {
14109                    excluded.push(self.propkey_of(&value)?);
14110                }
14111            }
14112        }
14113        let source = &source_object;
14114        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14115        // Reading the property table directly made every spread of a proxy empty.
14116        let keys = self.object_own_property_keys(source)?;
14117        for as_key in keys {
14118            if as_key.is_symbol() {
14119                // A spread copies string-keyed properties only.
14120                continue;
14121            }
14122            if excluded.contains(&crate::value::Wtf8::new(
14123                as_key.as_str().unwrap_or_default(),
14124            )) {
14125                continue;
14126            }
14127            let enumerable = self
14128                .object_get_own_property(source, &as_key)?
14129                .is_some_and(|property| property.enumerable);
14130            if !enumerable {
14131                continue;
14132            }
14133            let value = self
14134                .get_property_key(source, &as_key)?
14135                .unwrap_or(Value::Undefined);
14136            target.define_data_key(&as_key, value);
14137        }
14138        Ok(())
14139    }
14140
14141    // -- iteration ---------------------------------------------------------
14142
14143    /// One object's own keys in enumeration order: array indices ascending, then the
14144    /// rest in insertion order.
14145    ///
14146    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14147    /// whether the key is enumerable, which the caller resolves per key because an
14148    /// array's elements are not in the same store as its named properties.
14149    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14150        // An index can arrive twice, once from the array's element store and once from
14151        // its property map, so the numeric keys go through a map that keeps the
14152        // enumerable answer if either source gave one.
14153        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14154        for (key, enumerable) in &own {
14155            if let Some(index) = key.as_str().and_then(array_index) {
14156                let entry = numeric.entry(index).or_insert(false);
14157                *entry = *entry || *enumerable;
14158            }
14159        }
14160        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14161            .into_iter()
14162            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14163            .collect();
14164        ordered.extend(
14165            own.into_iter()
14166                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14167        );
14168        ordered
14169    }
14170
14171    /// Build the key list a `for-in` loop walks.
14172    ///
14173    /// The order is the specification's: own properties before inherited ones, and
14174    /// within one object the integer-like keys in ascending numeric order ahead of the
14175    /// string keys in insertion order. A shadowed key only appears once, and a key that
14176    /// is a non-enumerable own property anywhere nearer is skipped entirely.
14177    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14178        let record = self.new_object(None);
14179        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14180        // A proxy supplies its own key list, and — the reason this is not just another
14181        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14182        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14183        // descriptor there.
14184        if let Value::Object(object) = value
14185            && object.proxy_state().is_some()
14186        {
14187            let own = self
14188                .proxy_own_keys(object)?
14189                .unwrap_or_else(|| object.own_property_keys());
14190            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14191            let mut numeric: Vec<u32> = Vec::new();
14192            let mut rest: Vec<PropertyKey> = Vec::new();
14193            for key in own {
14194                match key.as_str().and_then(array_index) {
14195                    Some(index) => numeric.push(index),
14196                    None => rest.push(key),
14197                }
14198            }
14199            numeric.sort_unstable();
14200            ordered.extend(
14201                numeric
14202                    .into_iter()
14203                    .map(|index| PropertyKey::from(index.to_string())),
14204            );
14205            ordered.extend(rest);
14206            for (index, key) in ordered.into_iter().enumerate() {
14207                record.define_data(&index.to_string(), self.key_value(&key));
14208            }
14209            record.define_data("__index", Value::Int(0));
14210            // The mark that makes `for_in_advance` re-ask the proxy per key.
14211            record.define_data("__proxy", Value::Object(object.clone()));
14212            return Ok(record);
14213        }
14214        if let Value::Object(object) = value {
14215            let mut chain = vec![object.clone()];
14216            chain.extend(object.chain());
14217            // Every own string key the walk has seen, enumerable or not. A
14218            // non-enumerable own property still hides a same-named enumerable one
14219            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14220            // keeps `x` out of the loop even when the prototype has one.
14221            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14222            for object in chain {
14223                let mut own: Vec<(crate::value::Wtf8, bool)> = object
14224                    .own_property_keys()
14225                    .iter()
14226                    .filter_map(|key| key.as_wtf8().cloned())
14227                    .map(|key| {
14228                        let enumerable = object
14229                            .own_property(&key.to_string_lossy())
14230                            .map(|property| property.enumerable)
14231                            .unwrap_or(false);
14232                        (key, enumerable)
14233                    })
14234                    .collect();
14235                if let Some(length) = object.array_length() {
14236                    own.retain(|(key, _)| key.as_str() != Some("length"));
14237                    for index in 0..length {
14238                        // A dense element is enumerable; a **hole** is not there at all —
14239                        // and a hole is also what an index with a recorded descriptor
14240                        // leaves behind, in which case the table entry above already
14241                        // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14242                        // defines index 0 non-enumerable and `for…in` must skip it).
14243                        if let Some(value) = object.array_get(index)
14244                            && !matches!(value, Value::Hole)
14245                        {
14246                            own.push((crate::value::Wtf8::new(index.to_string()), true));
14247                        }
14248                    }
14249                }
14250                // Integer-like keys come first in ascending order, then the rest in
14251                // insertion order — and the ordering is *per object*, not for the chain
14252                // as a whole: one pass over every collected key lifted a prototype's
14253                // `"4"` above the target's own `x`/`y`, which is not the order
14254                // `for…in` reports.
14255                for (key, enumerable) in Self::order_own_keys(own) {
14256                    if visited.contains(&key) {
14257                        continue;
14258                    }
14259                    visited.push(key.clone());
14260                    if enumerable {
14261                        keys.push(key);
14262                    }
14263                }
14264            }
14265        }
14266        for (index, key) in keys.into_iter().enumerate() {
14267            record.define_data(&index.to_string(), self.string_wtf8(key));
14268        }
14269        record.define_data("__index", Value::Int(0));
14270        Ok(record)
14271    }
14272
14273    /// The next key of a `for…in` record, `None` when the loop is done.
14274    ///
14275    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14276    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14277    /// the loop reaches it, so a handler that stops reporting a key partway through drops
14278    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14279    /// key the handler had already withdrawn.
14280    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14281        let Value::Object(record) = record else {
14282            return Ok(None);
14283        };
14284        let proxy = record
14285            .own_property("__proxy")
14286            .and_then(|property| property.value);
14287        loop {
14288            let index = record
14289                .own_property("__index")
14290                .and_then(|property| property.value)
14291                .map(|value| value.to_int32())
14292                .unwrap_or(0);
14293            let Some(candidate) = record
14294                .own_property(&index.to_string())
14295                .and_then(|property| property.value)
14296            else {
14297                return Ok(None);
14298            };
14299            record.define_data("__index", Value::Int(index + 1));
14300            let text = candidate.to_js_string();
14301            let Some(Value::Object(proxy)) = &proxy else {
14302                return Ok(Some(text));
14303            };
14304            // The candidate is already a key string here, so the lookup does not need a
14305            // second `ToPropertyKey` conversion.
14306            let key = PropertyKey::from(text.as_str());
14307            let live = match self.proxy_get_own_property(proxy, &key)? {
14308                Some(descriptor) => descriptor,
14309                // Not a proxy after all, or it lost its state: fall back to the target.
14310                None => proxy.own_property_key(&key),
14311            };
14312            if live.is_some_and(|property| property.enumerable) {
14313                return Ok(Some(text));
14314            }
14315            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14316            // next one.
14317        }
14318    }
14319
14320    /// The iterator for `for-of`: the object and its `next` method.
14321    ///
14322    /// An object that already carries a `next` method is used as it is — that is what
14323    /// `arr.values()` returns — and only arrays and strings get the built-in
14324    /// sequence iterator.
14325    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14326    ///
14327    /// Callers that must choose between the iterable and the array-like protocol — the
14328    /// typed-array constructor is the main one — need to ask *before* committing to one.
14329    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14330        let key = self.realm.well_known_key(WellKnown::Iterator);
14331        let method = self.read_field_key(value, &key)?;
14332        if matches!(method, Value::Undefined | Value::Null) {
14333            return Ok(false);
14334        }
14335        if !matches!(&method, Value::Object(object) if object.is_callable()) {
14336            return Err(Signal::Throw(
14337                self.make_error("TypeError", "Symbol.iterator is not callable"),
14338            ));
14339        }
14340        Ok(true)
14341    }
14342
14343    /// Collect everything an iterable yields.
14344    ///
14345    /// The cap is a guard against a generator that never ends: an unbounded collect would
14346    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14347    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14348    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14349    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14350        const MAX_ITEMS: usize = 1 << 24;
14351        let iterator = self.get_iterator(value)?;
14352        let mut out = Vec::new();
14353        loop {
14354            let (element, done) = self.iterator_step(&iterator)?;
14355            if done {
14356                return Ok(out);
14357            }
14358            out.push(element);
14359            if out.len() > MAX_ITEMS {
14360                // Close before refusing: the walk is being abandoned, so the iterator's
14361                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14362                // unrun and a locked resource unreleased.
14363                self.close_iterator_after_throw(&iterator)?;
14364                return Err(self.range_error("iterable is too long to collect"));
14365            }
14366        }
14367    }
14368
14369    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14370    ///
14371    /// A native constructor calls this once it has validated its arguments, which is the
14372    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14373    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14374    /// never reached. The prototype comes from `new.target` when it is an object, and from
14375    /// `default_proto` otherwise.
14376    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14377        let proto = self.ctor_prototype(default_proto)?;
14378        Ok(self.new_object(Some(proto)))
14379    }
14380
14381    /// An **array** whose prototype comes from `new.target`.
14382    ///
14383    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14384    /// instance from `new.target.prototype`, and building a plain array instead made every
14385    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14386    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14387        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14388        Ok(JsObject::array(self.heap, Some(proto), 0))
14389    }
14390
14391    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14392    ///
14393    /// The `Option` form is for the constructors that build their instance in a helper which
14394    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14395    /// from `await`'s internal promise, and only the first has a `new.target`.
14396    fn ctor_prototype_opt(
14397        &mut self,
14398        default_proto: Option<Gc<JsObject>>,
14399    ) -> JsResult<Option<Gc<JsObject>>> {
14400        // `active_new_target`: by the time a native constructor runs, `call_value` has
14401        // already consumed the parked value.
14402        let Some(target) = self
14403            .active_new_target
14404            .as_object()
14405            .cloned()
14406            .map(Value::Object)
14407        else {
14408            return Ok(default_proto);
14409        };
14410        let Some(target) = target.as_object().cloned() else {
14411            return Ok(default_proto);
14412        };
14413        match self.get_property(&target, "prototype")? {
14414            Some(Value::Object(proto)) => Ok(Some(proto)),
14415            _ => Ok(default_proto),
14416        }
14417    }
14418
14419    /// `new.target.prototype`, or `default_proto` when this is a plain call.
14420    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14421        let Some(target) = self.active_new_target.as_object().cloned() else {
14422            return Ok(default_proto);
14423        };
14424        match self.get_property(&target, "prototype")? {
14425            Some(Value::Object(proto)) => Ok(proto),
14426            _ => Ok(default_proto),
14427        }
14428    }
14429
14430    /// `CreateDataPropertyOrThrow(O, key, value)`.
14431    ///
14432    /// A *definition*, not an assignment. The difference is visible the moment the target
14433    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14434    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14435    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14436    /// refused (`configurable: false`).
14437    ///
14438    /// The fast path exists because this is called once per element by `map`, `filter`,
14439    /// `slice` and friends: a plain array with no custom element descriptors and a writable
14440    /// `length` can store straight into its element vector.
14441    pub fn create_data_property_or_throw(
14442        &mut self,
14443        object: &Gc<JsObject>,
14444        index: usize,
14445        value: Value,
14446    ) -> JsResult<()> {
14447        // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
14448        // an array (that is what `Array.isArray` must say), so the element fast path would
14449        // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
14450        // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
14451        // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
14452        // records the exact trap sequence.
14453        if object.proxy_state().is_none()
14454            && object.is_array()
14455            && object.elements_writable()
14456            && !object.has_element_descriptors()
14457            && object.is_extensible()
14458            && object.array_set(self.heap, index, value.clone())
14459        {
14460            return Ok(());
14461        }
14462        let key = PropertyKey::from(index.to_string());
14463        let property = Property {
14464            value: Some(value),
14465            writable: true,
14466            enumerable: true,
14467            configurable: true,
14468            ..Property::default()
14469        };
14470        // `CreateDataProperty` always asks for the default attributes, so it can only ever
14471        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
14472        // the rest. Checking here rather than inside `object_define_own_property` is
14473        // deliberate: that function receives a fully-populated `Property` and cannot tell
14474        // an omitted attribute from an explicit `false`, so the generic check it would need
14475        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
14476        // writable property (that cost eight `Object/defineProperty` tests).
14477        if object.proxy_state().is_none()
14478            && let Some(existing) = self.object_get_own_property(object, &key)?
14479            && !existing.configurable
14480        {
14481            return Err(self.type_error("cannot create the property"));
14482        }
14483        if self.object_define_own_property(object, &key, property)? {
14484            return Ok(());
14485        }
14486        Err(self.type_error("cannot create the property"))
14487    }
14488
14489    /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
14490    ///
14491    /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
14492    /// its callers have; this is the same operation for the named properties a built-in
14493    /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
14494    /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
14495    /// `Array.prototype` cannot see it — while `Set` would run that accessor.
14496    pub fn create_named_data_property_or_throw(
14497        &mut self,
14498        object: &Gc<JsObject>,
14499        key: &str,
14500        value: Value,
14501    ) -> JsResult<()> {
14502        let key = PropertyKey::from(key);
14503        let property = Property {
14504            value: Some(value),
14505            writable: true,
14506            enumerable: true,
14507            configurable: true,
14508            ..Property::default()
14509        };
14510        if object.proxy_state().is_none()
14511            && let Some(existing) = self.object_get_own_property(object, &key)?
14512            && !existing.configurable
14513        {
14514            return Err(self.type_error("cannot create the property"));
14515        }
14516        if self.object_define_own_property(object, &key, property)? {
14517            return Ok(());
14518        }
14519        Err(self.type_error("cannot create the property"))
14520    }
14521
14522    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14523    ///
14524    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14525    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14526    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14527    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14528    /// run user code and both can throw.
14529    pub fn species_constructor(
14530        &mut self,
14531        object: &Gc<JsObject>,
14532        default: Value,
14533    ) -> JsResult<Value> {
14534        let Some(constructor) = self.get_property(object, "constructor")? else {
14535            return Ok(default);
14536        };
14537        let constructor = match constructor {
14538            Value::Undefined => return Ok(default),
14539            Value::Object(constructor) => constructor,
14540            _ => return Err(self.type_error("constructor is not an object")),
14541        };
14542        let key = self.realm.well_known_key(WellKnown::Species);
14543        let species = self.get_property_key(&constructor, &key)?;
14544        match species {
14545            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
14546            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
14547            Some(_) => Err(self.type_error("species is not a constructor")),
14548        }
14549    }
14550
14551    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
14552    ///
14553    /// The result is an array of `length` holes whose prototype comes from
14554    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
14555    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
14556    /// is why the `IsArray` check is the first step and not an optimisation.
14557    pub fn array_species_create(
14558        &mut self,
14559        original: &Value,
14560        length: usize,
14561    ) -> JsResult<Gc<JsObject>> {
14562        // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
14563        // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
14564        // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
14565        // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
14566        // `new_array_of_length` (`slice/create-non-array-invalid-len`).
14567        // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14568        // realm** — the species may be a user function that ignores the length entirely, and
14569        // then `2**53 - 1` is not its problem
14570        // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14571        // a short proxy and expects the copy loop to run).
14572        let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14573            if length > ARRAY_CREATE_LIMIT {
14574                return Err(interp.range_error("invalid array length"));
14575            }
14576            Ok(interp.new_array_of_length(length))
14577        };
14578        let Some(object) = original.as_object().cloned() else {
14579            return default(self);
14580        };
14581        if !object.is_array() {
14582            return default(self);
14583        }
14584        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14585        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14586        let Some(constructor) = self.get_property(&object, "constructor")? else {
14587            return default(self);
14588        };
14589        let species = match constructor {
14590            Value::Undefined => return Ok(self.new_array_of_length(length)),
14591            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14592                return default(self);
14593            }
14594            Value::Object(constructor) => {
14595                let key = self.realm.well_known_key(WellKnown::Species);
14596                match self.get_property_key(&constructor, &key)? {
14597                    None | Some(Value::Undefined) | Some(Value::Null) => {
14598                        return default(self);
14599                    }
14600                    Some(species) => species,
14601                }
14602            }
14603            // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14604            // is a `TypeError`, not "the default". Treating it as the default made
14605            // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14606            // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14607            // `concat/create-ctor-non-object` are the same rule three times.
14608            _ => return Err(self.type_error("constructor is not an object")),
14609        };
14610        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14611        // that is merely callable is the `create-species-non-ctor` case.
14612        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14613            return Err(self.type_error("species is not a constructor"));
14614        }
14615        // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14616        // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14617        // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14618        let created = self.construct(
14619            species.clone(),
14620            species,
14621            vec![crate::object::length_value(length)],
14622        )?;
14623        let Some(created) = created.as_object().cloned() else {
14624            return Err(self.type_error("species constructor did not answer an object"));
14625        };
14626        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14627        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14628        // object, and `create-species-with-non-writable-property` asserts exactly that.
14629        // The length is set for the array case; the generic case is the caller's
14630        // `Set(A, "length", …)`.
14631        if created.is_array() {
14632            created.array_set_length(self.heap, length);
14633        }
14634        Ok(created)
14635    }
14636
14637    /// Whether `object` is this realm's `%Array%`.
14638    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14639        self.realm
14640            .array_constructor
14641            .as_ref()
14642            .is_some_and(|array| array.ptr_eq(object))
14643    }
14644
14645    /// A fresh `length`-hole array with the intrinsic prototype.
14646    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14647        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14648        array.array_set_length(self.heap, length);
14649        array
14650    }
14651
14652    /// Whether this call is a construction, i.e. `new.target` is defined.
14653    ///
14654    /// A native constructor receives `this = undefined` (it builds its own instance), so it
14655    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14656    /// The native function currently executing, if any.
14657    pub fn current_native(&self) -> Option<Gc<JsObject>> {
14658        self.current_native.clone()
14659    }
14660
14661    /// Whether this call is a construction, i.e. `new.target` is defined.
14662    pub fn is_constructing(&self) -> bool {
14663        // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14664        // `call_value` before a native runs, so by the time a constructor body asks, the
14665        // answer is only in the active slot.
14666        matches!(self.active_new_target, Value::Object(_))
14667    }
14668
14669    /// The `TypeError` a constructor too primitive to have a wrapper raises.
14670    ///
14671    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
14672    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
14673    /// happens inside the native function, which is why the trace carries an
14674    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
14675    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
14676    /// constructor`, and an unnamed one reports the leading space of `" is not a
14677    /// constructor"` because the reference formats the empty name as it is.
14678    ///
14679    /// It is also the answer for a `new.target` that cannot be named at all — not a
14680    /// function, or a throwing `name` getter — where the reference falls back to the bare
14681    /// `not a constructor`.
14682    pub fn not_a_constructor_error(&mut self) -> Signal {
14683        let target = self.active_new_target.clone();
14684        self.not_a_constructor_error_for(target)
14685    }
14686
14687    /// The same `TypeError` for an explicit target, for the callers that check
14688    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
14689    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
14690        let target = match target {
14691            Value::Object(target) if target.is_callable() => target,
14692            _ => return self.type_error("not a constructor"),
14693        };
14694        let name = match self.get_property(&target, "name") {
14695            Ok(Some(value)) => value.to_js_string(),
14696            _ => return self.type_error("not a constructor"),
14697        };
14698        self.type_error(format!("{name} is not a constructor"))
14699    }
14700
14701    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
14702    ///
14703    /// True whenever `new.target` is not the callee itself, or when it has no usable
14704    /// `prototype` — the cases where reading the property is observable at all.
14705    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
14706        match &self.active_new_target {
14707            Value::Object(target) => !target.ptr_eq(callee),
14708            Value::Undefined => false,
14709            _ => true,
14710        }
14711    }
14712
14713    /// The symbol key for one of the engine's own hidden slots.
14714    ///
14715    /// Cached on the realm, so every object of a kind shares one key and a slot can be
14716    /// read back by name.
14717    /// Whether any object on `object`'s **prototype chain** owns an array index.
14718    ///
14719    /// The one question the array methods' dense fast paths have to ask before touching the
14720    /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
14721    /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
14722    /// vector an unreliable answer. Walking the chain once per call is cheap because a
14723    /// prototype almost never holds an index.
14724    pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
14725        let mut current = object.proto();
14726        // Bounded, like every other prototype walk here: a proxy can answer a cycle.
14727        for _ in 0..10_000 {
14728            let Some(proto) = current else {
14729                return false;
14730            };
14731            if proto.has_indexed_own_property() {
14732                return true;
14733            }
14734            current = proto.proto();
14735        }
14736        false
14737    }
14738
14739    /// The hidden symbol a named internal slot is keyed by, created on first use.
14740    ///
14741    /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
14742    /// either keeping a table of its own.
14743    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
14744        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
14745            return PropertyKey::Symbol(symbol.clone());
14746        }
14747        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
14748        self.realm
14749            .internal_slots
14750            .borrow_mut()
14751            .insert(name, Value::Symbol(symbol.clone()));
14752        PropertyKey::Symbol(symbol)
14753    }
14754
14755    /// Read a hidden slot, or `None` when the object has none of that name.
14756    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
14757        let slots = self.realm.internal_slots.borrow();
14758        let Value::Symbol(symbol) = slots.get(name)? else {
14759            return None;
14760        };
14761        object
14762            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
14763            .and_then(|property| property.value)
14764    }
14765
14766    /// Define a hidden slot.
14767    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
14768        let key = self.internal_slot(name);
14769        object.define_key(&key, Property::with_attributes(value, false, false));
14770    }
14771
14772    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14773    ///
14774    /// The method is looked up on the value (through its prototype), called with no
14775    /// arguments, and its result becomes the iterator. A generator gets here through
14776    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14777    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14778    ///
14779    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14780    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14781    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14782    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14783    /// does, and a user-defined iterable works without a special case.
14784    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14785    /// `Symbol.iterator`.
14786    ///
14787    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14788    /// iterable is legal there, and each value it produces is simply already settled by
14789    /// the time the `await` around it runs.
14790    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14791        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14792        let method = self.read_field_key(value, &async_key)?;
14793        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14794        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14795        // is *present but not callable* is a TypeError — it does not mean "try the other
14796        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14797        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14798        // guard is there to catch.
14799        let absent = matches!(method, Value::Undefined | Value::Null);
14800        if !absent {
14801            let Value::Object(object) = &method else {
14802                return Err(Signal::Throw(
14803                    self.make_error("TypeError", "value is not iterable"),
14804                ));
14805            };
14806            if !object.is_callable() {
14807                return Err(Signal::Throw(
14808                    self.make_error("TypeError", "value is not iterable"),
14809                ));
14810            }
14811        }
14812        if absent {
14813            // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
14814            // generator's `yield*` both reach here, and the wrapper is what puts
14815            // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
14816            // caller — a poisoned `constructor` on that value rejects instead of being
14817            // yielded, and a rejection closes the synchronous iterator first.
14818            let sync = self.get_iterator(value)?;
14819            return self.async_from_sync_iterator(sync);
14820        }
14821        let iterator = self.call_value(method, value.clone(), Vec::new())?;
14822        if !matches!(iterator, Value::Object(_)) {
14823            return Err(Signal::Throw(
14824                self.make_error("TypeError", "iterator is not an object"),
14825            ));
14826        }
14827        // §7.4.2 `GetIteratorFromMethod` step 3.b: `GetIteratorDirect` reads `next` and
14828        // §7.4.1 requires it to be **callable** straight away — a throwing `return` must
14829        // not be reached, because the `TypeError` comes before any stepping
14830        // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14831        let next = self.read_field(&iterator, "next")?;
14832        if !matches!(&next, Value::Object(function) if function.is_callable()) {
14833            return Err(Signal::Throw(
14834                self.make_error("TypeError", "iterator's next method is not callable"),
14835            ));
14836        }
14837        Ok(Iterator {
14838            object: iterator,
14839            next,
14840        })
14841    }
14842
14843    /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
14844    ///
14845    /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
14846    /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
14847    /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
14848    fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
14849        let Some(factory) = self.realm.async_from_sync.clone() else {
14850            // No wrapper installed (a realm whose heap refused to hold it): fall back to the
14851            // raw synchronous iterator rather than refusing to iterate at all.
14852            return Ok(sync);
14853        };
14854        let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
14855        let next = self.read_field(&wrapper, "next")?;
14856        Ok(Iterator {
14857            object: wrapper,
14858            next,
14859        })
14860    }
14861
14862    /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14863    /// read — `@@iterator` is **not** consulted.
14864    ///
14865    /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14866    /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14867    /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14868    /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14869    /// refused it with "[object Object] is not iterable".
14870    pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14871        if !matches!(value, Value::Object(_)) {
14872            return Err(self.type_error("iterator is not an object"));
14873        }
14874        let next = self.read_field(&value, "next")?;
14875        Ok(Iterator {
14876            object: value,
14877            next,
14878        })
14879    }
14880
14881    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14882        let key = self.realm.well_known_key(WellKnown::Iterator);
14883        let method = self.read_field_key(value, &key)?;
14884        let Value::Object(function) = &method else {
14885            return Err(Signal::Throw(self.make_error(
14886                "TypeError",
14887                &format!("{} is not iterable", value.to_js_string()),
14888            )));
14889        };
14890        if !function.is_callable() {
14891            return Err(Signal::Throw(self.make_error(
14892                "TypeError",
14893                &format!("{} is not iterable", value.to_js_string()),
14894            )));
14895        }
14896        let iterator = self.call_value(method, value.clone(), Vec::new())?;
14897        // The spec requires an object here; a primitive iterator has no `next` to call
14898        // and would fail one step later with a confusing message.
14899        if !matches!(iterator, Value::Object(_)) {
14900            return Err(Signal::Throw(
14901                self.make_error("TypeError", "iterator is not an object"),
14902            ));
14903        }
14904        // `GetIteratorDirect` requires `next` to be **callable** right away, before any
14905        // stepping and therefore before any `return` can be reached
14906        // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14907        let next = self.read_field(&iterator, "next")?;
14908        if !matches!(&next, Value::Object(function) if function.is_callable()) {
14909            return Err(Signal::Throw(
14910                self.make_error("TypeError", "iterator's next method is not callable"),
14911            ));
14912        }
14913        Ok(Iterator {
14914            object: iterator,
14915            next,
14916        })
14917    }
14918
14919    /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14920    /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14921    /// exception from `return` propagates normally instead of being swallowed. That is the
14922    /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14923    /// because confusing them is exactly the bug both exist to avoid.
14924    pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14925        let method = self.read_field(&iterator.object, "return")?;
14926        if matches!(method, Value::Undefined | Value::Null) {
14927            return Ok(());
14928        }
14929        if !matches!(&method, Value::Object(object) if object.is_callable()) {
14930            return Err(self.type_error("iterator return is not a function"));
14931        }
14932        self.call_value(method, iterator.object.clone(), Vec::new())?;
14933        Ok(())
14934    }
14935
14936    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14937    /// cannot replace it.
14938    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14939        let method = self.read_field(&iterator.object, "return")?;
14940        if matches!(method, Value::Undefined | Value::Null) {
14941            return Ok(());
14942        }
14943        if !matches!(&method, Value::Object(object) if object.is_callable()) {
14944            return Err(self.type_error("iterator return is not a function"));
14945        }
14946        self.call_value(method, iterator.object.clone(), Vec::new())?;
14947        Ok(())
14948    }
14949
14950    /// One step of an internal iterator: the value and whether it is exhausted.
14951    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14952        // A real iterator (`next` is a function) answers with a result object.
14953        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14954            let result =
14955                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14956            let Some(result) = result.as_object().cloned() else {
14957                return Err(self.type_error("iterator result is not an object"));
14958            };
14959            let done = self
14960                .get_property(&result, "done")?
14961                .is_some_and(|value| value.to_boolean());
14962            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14963            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14964            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14965            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14966            // made an unrelated `value` getter observable after the loop was over.
14967            if done {
14968                return Ok((Value::Undefined, true));
14969            }
14970            let value = self
14971                .get_property(&result, "value")?
14972                .unwrap_or(Value::Undefined);
14973            return Ok((value, false));
14974        }
14975        // An iterator whose `next` is not callable is treated as exhausted, which is
14976        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14977        // that are not iterable at all.
14978        Ok((Value::Undefined, true))
14979    }
14980
14981    /// `[...iterable]`: append everything the iterator yields, and answer the next
14982    /// index.
14983    ///
14984    /// This goes through the same iterator machinery `for-of` uses rather than copying
14985    /// an array's elements, because a spread source is any iterable: a string spreads
14986    /// into its characters and an array iterator spreads into its results. Handling
14987    /// only arrays made `[..."ab"]` come out empty with no error at all.
14988    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14989        let Some(target) = array.as_object().cloned() else {
14990            return Ok(0);
14991        };
14992        let start = target.array_length().unwrap_or(0);
14993        let mut added = 0;
14994        let iterator = self.get_iterator(iterable)?;
14995        loop {
14996            let (value, done) = self.iterator_step(&iterator)?;
14997            if done {
14998                break;
14999            }
15000            target.array_set(self.heap, start + added, value);
15001            added += 1;
15002        }
15003        Ok((start + added) as i32)
15004    }
15005
15006    /// How an uncaught exception is reported.
15007    ///
15008    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15009    /// with `ToString` — `js_std_dump_error` is three lines that end in
15010    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15011    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15012    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15013    ///
15014    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15015    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15016    /// `toString`"; it does call it, but only for objects of a class it does not know how
15017    /// to walk, and never for errors, arrays or plain objects.
15018    ///
15019    /// A printer that fails must not take the reporter down with it, so that case falls
15020    /// back to the `ToString` rendering.
15021    pub fn describe_exception(&mut self, value: &Value) -> String {
15022        match crate::print::sprint(self, value) {
15023            Ok(text) => text,
15024            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15025        }
15026    }
15027
15028    /// The file name of whatever is running, innermost frame first.
15029    ///
15030    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15031    /// innermost frame's file name, without distinguishing a module body from a plain
15032    /// script. `import()` uses it as the base for a relative specifier, which is why
15033    /// `import('./x.js')` inside a script resolves next to the script and not next to the
15034    /// process's working directory.
15035    pub fn script_or_module_name(&self) -> Option<String> {
15036        self.script_or_module_name_at(0)
15037    }
15038
15039    /// [`Interp::script_or_module_name`] `level` frames further out.
15040    ///
15041    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15042    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15043    /// frame without a file name is skipped rather than counted, because a native call
15044    /// pushes no frame of its own and so cannot be a level.
15045    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15046        self.frames
15047            .iter()
15048            .rev()
15049            .filter_map(|frame| frame.code.code.filename.clone())
15050            .nth(level)
15051    }
15052
15053    /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15054    ///
15055    /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15056    /// because that is what a stack trace should print, but §19.2.1.1's
15057    /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15058    /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15059    /// produced the bare specifier `x.js`, which the loader then looked for in the working
15060    /// directory instead of beside the file that called `eval`.
15061    pub fn script_or_module_file_name(&self) -> Option<String> {
15062        self.frames.iter().rev().find_map(|frame| {
15063            let name = frame.code.code.filename.as_deref()?;
15064            (!name.starts_with('<')).then(|| name.to_string())
15065        })
15066    }
15067
15068    /// The current call stack, formatted the way `qjs` prints `error.stack`.
15069    ///
15070    /// One `    at name (file:line:col)` line per active frame, innermost first. The
15071    /// position is the one recorded for the instruction each frame is stopped on, which
15072    /// is why the compiler builds a pc-to-position table per function: without it a
15073    /// trace could only name the function, not the line inside it.
15074    ///
15075    /// A frame whose code has no positions prints just `(file)`, matching the
15076    /// reference's output for stripped bytecode.
15077    pub fn stack_trace(&self) -> String {
15078        self.stack_trace_skipping(0)
15079    }
15080
15081    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15082    fn stack_trace_skipping(&self, skip: usize) -> String {
15083        // One ordered list, innermost first, so `skip` counts the same thing whether the
15084        // frames it leaves out are native or bytecode. Indices rather than references: a
15085        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15086        let depth = self.frames.len();
15087        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15088        // A native entered while `at` bytecode frames were live was called *from* the
15089        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15090        // entered at the current depth are therefore innermost of all.
15091        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15092            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15093                if *at == wanted {
15094                    order.push((true, index));
15095                }
15096            }
15097        };
15098        push_natives(&mut order, depth);
15099        for index in (0..depth).rev() {
15100            order.push((false, index));
15101            push_natives(&mut order, index);
15102        }
15103        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15104        // barrier. Natives entered at exactly the barrier depth are the eval entry point
15105        // itself (`evalScript (native)`), and the reference leaves those out too.
15106        if let Some(barrier) = self.trace_barriers.last().copied() {
15107            order.retain(|(is_native, index)| match is_native {
15108                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15109                false => *index >= barrier,
15110            });
15111        }
15112
15113        let mut out = String::new();
15114        for (is_native, index) in order.into_iter().skip(skip) {
15115            match is_native {
15116                true => {
15117                    out.push_str("    at ");
15118                    let (native, _) = &self.native_frames[index];
15119                    let name = native
15120                        .own_property("name")
15121                        .and_then(|property| property.value)
15122                        .map(|value| value.to_js_string())
15123                        .unwrap_or_default();
15124                    out.push_str(&name);
15125                    out.push_str(" (native)\n");
15126                }
15127                false => {
15128                    let frame = &self.frames[index];
15129                    let code = &frame.code.code;
15130                    let file = code.filename.as_deref().unwrap_or("<input>");
15131                    // The name comes from the function *object*, not from the compiled code:
15132                    // an anonymous function expression is named by the property it is stored
15133                    // in (`{valueOf: function(){}}`), which only the object knows.
15134                    let bound_name = match &frame.callee {
15135                        Value::Object(object) => {
15136                            object
15137                                .own_property("name")
15138                                .and_then(|property| match property.value {
15139                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
15140                                        Some(text.to_string_lossy().into_owned())
15141                                    }
15142                                    _ => None,
15143                                })
15144                        }
15145                        _ => None,
15146                    };
15147                    // No callee object means the body was entered by the host, so the
15148                    // name has to come from the compiled code. Two cases differ:
15149                    //
15150                    // * an *unnamed* function of any kind — the reference reads the
15151                    //   `name` property, finds it empty, and prints `<anonymous>`;
15152                    // * a *module* body, which has no `name` property at all: the
15153                    //   reference builds that function object with `js_closure2` and
15154                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15155                    //   so a trace reaching it also prints `<anonymous>` — while a
15156                    //   *script* body prints `<eval>`, its `name`.
15157                    let unnamed = code.name.is_empty() || code.module.is_some();
15158                    out.push_str("    at ");
15159                    match bound_name.as_deref() {
15160                        Some(name) => out.push_str(name),
15161                        None if unnamed => out.push_str("<anonymous>"),
15162                        None => out.push_str(&code.name),
15163                    }
15164                    match code.position_at(frame.at as u32) {
15165                        Some((line, column)) => {
15166                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
15167                        }
15168                        None => out.push_str(&format!(" ({file})\n")),
15169                    }
15170                }
15171            }
15172        }
15173        out
15174    }
15175
15176    /// Give an anonymous function the name of the property it is stored in.
15177    ///
15178    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15179    /// enumerable and not configurable, and a function that already has a real name
15180    /// keeps it.
15181    ///
15182    /// "Already named" means a *non-empty* name: every function object is created with
15183    /// a `name` of `""` so the property exists on all of them, and treating that empty
15184    /// string as a name left every anonymous function nameless — which is how a stack
15185    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
15186    /// `SetFunctionName`, for a name that came from source text.
15187    fn set_function_name(&mut self, function: &Value, name: &str) {
15188        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15189    }
15190
15191    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15192    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15193    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15194        let Value::Object(object) = function else {
15195            return;
15196        };
15197        // `SetFunctionName` applies to *functions* and classes only, and only when they are
15198        // anonymous. Without the callability guard, `{value: someObject}` renamed
15199        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15200        // on the right-hand side of a property. That is how a `zipKeyed` result object
15201        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15202        // has no `NamedEvaluation` at all.
15203        if !object.is_callable() {
15204            return;
15205        }
15206        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15207            && !existing.wtf8().is_empty()
15208        {
15209            return;
15210        }
15211        let text = self.string_wtf8(name.clone());
15212        object.define("name", Property::name_or_length(text));
15213    }
15214
15215    // -- global declarations -----------------------------------------------
15216
15217    /// Declare a global binding, creating its reference cell.
15218    /// Declare a `var` or function global, whose home is the global object.
15219    ///
15220    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15221    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15222    /// such as `print`, or a redeclaration — is left alone.
15223    pub fn declare_var_global(&mut self, name: &str) {
15224        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15225        // global object is exactly the leak `typeof my_var === "undefined"` after
15226        // `eval("var my_var=2")` rules out.
15227        if let Some(scope) = self.eval_scope.as_mut() {
15228            scope.entry(name.to_string()).or_insert(Value::Undefined);
15229            return;
15230        }
15231        // A sloppy direct eval declares into its *caller's* variable environment. Doing
15232        // this on the global object instead made `eval("var c = 1")` inside a parameter
15233        // list overwrite a global `c`, and made two calls to the same function share one
15234        // binding.
15235        if let Some(cell) = self.declare_eval_local(name) {
15236            cell.set(Value::Undefined);
15237            return;
15238        }
15239        let global = self.realm.global.clone();
15240        if global.own_property(name).is_some() {
15241            return;
15242        }
15243        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15244        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15245        // whole point of that trick and what lets `Object.defineProperty` reshape it
15246        // afterwards. `eval_scope` is `Some` while an eval is running.
15247        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15248        global.define(
15249            name,
15250            Property {
15251                value: Some(Value::Undefined),
15252                writable: true,
15253                enumerable: true,
15254                configurable: from_eval,
15255                ..Property::default()
15256            },
15257        );
15258    }
15259
15260    /// Declare a *lexical* global binding, which starts in its dead zone.
15261    ///
15262    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15263    /// global object and is created when its initialiser runs.
15264    pub fn declare_global(&mut self, name: &str, is_const: bool) {
15265        if is_const {
15266            self.realm.lexical_consts.insert(name.to_string());
15267        }
15268        if !self.realm.globals.contains_key(name) {
15269            // `Uninitialized` rather than `Undefined`: the binding exists but is not
15270            // readable until its initialiser runs, and that is what `let x` before
15271            // `x = 1` has to observe.
15272            let cell = self.new_cell(Value::Uninitialized);
15273            self.realm.globals.insert(name.to_string(), cell);
15274            self.realm.declared.push(name.to_string());
15275        }
15276    }
15277}
15278
15279/// The bytecode and environment of a function object, if it is a bytecode function.
15280///
15281/// Extracted before a call so no borrow of the object is held across it.
15282fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15283    function.with(|data| match &data.kind {
15284        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15285        _ => None,
15286    })
15287}
15288
15289/// A native call target, extracted before the call so no borrow is held.
15290enum NativeCall {
15291    Native(NativeFn),
15292    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15293    /// not hold that object's `RefCell` borrow.
15294    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15295    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15296    Bound {
15297        target: Value,
15298        this: Value,
15299        leading: Vec<Value>,
15300    },
15301    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15302    Revoker(crate::object::ProxyRef),
15303    /// A promise's `resolve`.
15304    PromiseResolve(Gc<JsObject>),
15305    /// A promise's `reject`.
15306    PromiseReject(Gc<JsObject>),
15307    /// The executor `NewPromiseCapability(C)` hands a user constructor.
15308    CapabilityExecutor {
15309        state: Gc<JsObject>,
15310    },
15311    /// One leg of a `then` that settles through a user capability.
15312    ThenShim {
15313        handler: Option<Value>,
15314        resolve: Value,
15315        reject: Value,
15316        fulfilled: bool,
15317    },
15318    /// One continuation of an `await`.
15319    AwaitResume {
15320        coroutine: Gc<JsObject>,
15321        promise: Gc<JsObject>,
15322        kind: ResumeKind,
15323    },
15324    /// One element of a `Promise` combinator settling.
15325    CombinatorSettle {
15326        state: Gc<JsObject>,
15327        index: usize,
15328        fulfilled: bool,
15329    },
15330    /// One of `Promise.prototype.finally`'s two shims.
15331    FinallyShim {
15332        callback: Option<Value>,
15333        fulfilled: bool,
15334        constructor: Value,
15335    },
15336    /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15337    ReturnValue(Value),
15338    /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15339    ThrowValue(Value),
15340    /// Settle a promise with a fixed outcome.
15341    SettlePromise {
15342        promise: Gc<JsObject>,
15343        value: Value,
15344        rejected: bool,
15345    },
15346    /// Continue an async generator after its `await` settled.
15347    GeneratorResume {
15348        generator: Gc<JsObject>,
15349        promise: Gc<JsObject>,
15350        kind: ResumeKind,
15351    },
15352    /// Read a module namespace's binding out of its cell.
15353    ModuleBinding(Gc<Cell>),
15354    /// Finish a completed async generator's `return(v)` once `v` has settled.
15355    CompletedReturn {
15356        generator: Gc<JsObject>,
15357        promise: Gc<JsObject>,
15358        rejected: bool,
15359    },
15360    /// Answer a pending async-generator method with `{value, done}`.
15361    YieldResult {
15362        generator: Gc<JsObject>,
15363        promise: Gc<JsObject>,
15364        done: bool,
15365    },
15366    /// One step of `AsyncDisposableStack.disposeAsync`.
15367    DisposeStep {
15368        remaining: Gc<JsObject>,
15369        promise: Gc<JsObject>,
15370        error: Value,
15371        rejected: bool,
15372        awaited: bool,
15373        needs_await: bool,
15374    },
15375}
15376
15377/// What a store does when the object refuses the write.
15378#[derive(Clone, Copy, PartialEq, Eq)]
15379pub enum DeleteFailure {
15380    /// Raise a `TypeError`, which is what strict mode and every built-in does.
15381    Throw,
15382    /// Ignore the write, which is what a sloppy-mode assignment does.
15383    Ignore,
15384}
15385
15386/// Whether `object` is a `Date` instance, by the class tag it carries.
15387///
15388/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15389/// builtins module depending on the interpreter's conversion order.
15390fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15391    interp
15392        .internal_get(object, "_class")
15393        .is_some_and(|value| value.to_js_string() == "Date")
15394}
15395
15396/// Which type `ToPrimitive` prefers when it converts an object.
15397#[derive(Clone, Copy, PartialEq, Eq)]
15398pub enum Hint {
15399    /// The default hint, which behaves like [`Hint::Number`].
15400    Default,
15401    /// `Number(obj)` and the arithmetic operators.
15402    Number,
15403    /// `String(obj)` and `ToPropertyKey`.
15404    String,
15405}
15406
15407/// Which table a binding slot indexes, for the messages that name it.
15408#[derive(Clone, Copy)]
15409enum VarSlot {
15410    Loc,
15411    Closure,
15412}
15413
15414/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15415fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15416    Ok(this)
15417}
15418
15419/// An internal iterator: the sequence plus a cursor.
15420pub(crate) struct Iterator {
15421    pub(crate) object: Value,
15422    pub(crate) next: Value,
15423}
15424
15425/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15426/// and plain `a` for a method.
15427///
15428/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
15429/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
15430/// reads `at get a (file:1:2)`.
15431/// The same prefixing, for a name that may hold an unpaired surrogate.
15432fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
15433    let prefix = match flags & 3 {
15434        1 => "get ",
15435        2 => "set ",
15436        _ => return key.clone(),
15437    };
15438    let mut units: Vec<u16> = prefix.encode_utf16().collect();
15439    units.extend_from_slice(&key.to_units());
15440    crate::value::Wtf8::from_units(&units)
15441}
15442
15443fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
15444    match flags & 3 {
15445        1 => format!("get {key}"),
15446        2 => format!("set {key}"),
15447        _ => key.to_string(),
15448    }
15449}
15450
15451/// Define a method or accessor property, per the `define_method` flag byte.
15452///
15453/// The low two bits pick value/getter/setter and bit 2 marks the property
15454/// enumerable.
15455///
15456/// A getter and a setter arrive as two separate `define_method` instructions, and the
15457/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
15458/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
15459/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
15460/// `JS_DefineProperty`, which leaves the other half alone.
15461fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
15462    let enumerable = flags & 4 != 0;
15463    let kind = flags & 3;
15464    let existing = object.own_property_key(key);
15465    let property = match kind {
15466        1 => Property {
15467            getter: Some(function),
15468            // The setter half, if this literal already defined one.
15469            setter: existing
15470                .filter(Property::is_accessor)
15471                .and_then(|p| p.setter),
15472            enumerable,
15473            configurable: true,
15474            ..Property::default()
15475        },
15476        2 => Property {
15477            getter: existing
15478                .filter(Property::is_accessor)
15479                .and_then(|p| p.getter),
15480            setter: Some(function),
15481            enumerable,
15482            configurable: true,
15483            ..Property::default()
15484        },
15485        _ => Property {
15486            value: Some(function),
15487            writable: true,
15488            enumerable,
15489            configurable: true,
15490            ..Property::default()
15491        },
15492    };
15493    object.define_key(key, property);
15494}
15495
15496// ---------------------------------------------------------------------------
15497// Operand decoding
15498// ---------------------------------------------------------------------------
15499
15500/// How `print` renders a value: the reference's `JS_PrintValue`.
15501///
15502/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
15503/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
15504/// The format is reproduced closely because the test suite compares output text:
15505///
15506/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
15507/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
15508/// * a cycle prints `[circular N]` with `N` the stack index of the object;
15509/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
15510///   end print as `<N empty item(s)>`;
15511/// * a string is quoted inside a container but raw at the top level, which is why
15512///   `print("x")` and `print(["x"])` differ.
15513pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
15514    // A string argument is printed raw: `js_print` converts it with `ToString`
15515    // instead of dumping it, and the quoting only appears inside a container.
15516    if let Value::String(text) = value {
15517        return text.to_string_lossy().into_owned();
15518    }
15519    let mut printer = Printer {
15520        interp,
15521        out: String::new(),
15522        stack: Vec::new(),
15523    };
15524    printer.value(value, 0);
15525    printer.out
15526}
15527
15528/// The internal class name an object carries, when it has one.
15529fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
15530    interp
15531        .internal_get(object, "_class")
15532        .map(|value| value.to_js_string())
15533}
15534
15535/// A string property, looked up the way `GetProperty` does: own first, then the
15536/// prototype chain. Needed because the print formatter holds the interpreter
15537/// immutably and so cannot run getters.
15538fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
15539    let mut current = Some(object.clone());
15540    // Bounded, because a prototype cycle would otherwise loop forever.
15541    for _ in 0..100 {
15542        let node = current?;
15543        if let Some(property) = node.own_property(name)
15544            && let Some(value) = property.value
15545        {
15546            return Some(value.to_js_string());
15547        }
15548        current = node.with(|data| data.proto.clone());
15549    }
15550    None
15551}
15552
15553/// The `JS_PrintValue` state: output, and the objects currently being printed.
15554struct Printer<'a, 'rt> {
15555    /// Kept for the class-name lookups that typed arrays and `Date` will need.
15556    #[allow(dead_code)]
15557    interp: &'a Interp<'rt>,
15558    out: String,
15559    stack: Vec<Gc<JsObject>>,
15560}
15561
15562impl Printer<'_, '_> {
15563    /// Depth past which a container is summarised by its class name.
15564    const MAX_DEPTH: usize = 2;
15565
15566    fn value(&mut self, value: &Value, level: usize) {
15567        match value {
15568            Value::Undefined
15569            | Value::Uninitialized
15570            | Value::Hole
15571            | Value::CatchOffset(_)
15572            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
15573            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
15574            // The printer writes a bigint the way the language spells one, so a dump is
15575            // unambiguous about which kind of number it is showing.
15576            Value::BigInt(big) => {
15577                self.out.push_str(&big.to_decimal_string());
15578                self.out.push('n');
15579            }
15580            Value::Null => self.out.push_str("null"),
15581            Value::Bool(true) => self.out.push_str("true"),
15582            Value::Bool(false) => self.out.push_str("false"),
15583            Value::Int(number) => self.out.push_str(&number.to_string()),
15584            Value::Float(number) => {
15585                self.out
15586                    .push_str(&crate::value::number_to_string_for_print(*number));
15587            }
15588            Value::String(text) => self.print_string(&text.to_string_lossy()),
15589            Value::Object(object) => self.object(object, level),
15590        }
15591    }
15592
15593    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
15594        // A cycle is reported rather than followed; the index is where the object
15595        // already sits in the print stack, which is what the reference shows.
15596        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
15597            self.out.push_str(&format!("[circular {index}]"));
15598            return;
15599        }
15600        if object.is_callable() {
15601            let name = object
15602                .own_property("name")
15603                .and_then(|property| property.value)
15604                .map(|value| value.to_js_string())
15605                .unwrap_or_default();
15606            if name.is_empty() {
15607                self.out.push_str("[Function (anonymous)]");
15608            } else {
15609                self.out.push_str(&format!("[Function {name}]"));
15610            }
15611            return;
15612        }
15613        if level >= Self::MAX_DEPTH {
15614            let class = if object.is_array() { "Array" } else { "Object" };
15615            self.out.push_str(&format!("[{class}]"));
15616            return;
15617        }
15618        // `Date` and `Error` print as themselves rather than as bags of properties:
15619        // the ISO string, and `Name: message` followed by the trace.
15620        if let Some(class) = class_of(self.interp, object) {
15621            if class == "Date" {
15622                self.date(object);
15623                return;
15624            }
15625            if class == "Error" {
15626                self.error(object);
15627                return;
15628            }
15629        }
15630        self.stack.push(object.clone());
15631        if object.is_array() {
15632            self.array(object, level);
15633        } else {
15634            self.plain_object(object, level);
15635        }
15636        self.stack.pop();
15637    }
15638
15639    /// A Date prints as its ISO string; an invalid one falls through to the plain
15640    /// object form, the way the reference falls back when `toISOString` throws.
15641    fn date(&mut self, object: &Gc<JsObject>) {
15642        let value = self
15643            .interp
15644            .internal_get(object, "_date_value")
15645            .map(|value| value.to_number());
15646        match value.and_then(crate::builtins::date::iso_string) {
15647            Some(text) => self.out.push_str(&text),
15648            None => self.plain_object(object, 0),
15649        }
15650    }
15651
15652    /// `Name: message`, then the trace with its trailing newline removed.
15653    fn error(&mut self, object: &Gc<JsObject>) {
15654        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
15655        self.out.push_str(&name);
15656        if let Some(message) = inherited(object, "message")
15657            && !message.is_empty()
15658        {
15659            self.out.push_str(": ");
15660            self.out.push_str(&message);
15661        }
15662        if let Some(stack) = inherited(object, "stack") {
15663            self.out.push('\n');
15664            self.out.push_str(stack.trim_end_matches('\n'));
15665        }
15666    }
15667
15668    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
15669        let elements = object.array_elements().unwrap_or_default();
15670        self.out.push_str("[ ");
15671        // An interior hole means the array is "sparse": the reference prints those
15672        // as `index: value` pairs and says nothing about the holes themselves, while
15673        // a hole run at the end becomes a single `<N empty items>` note.
15674        let last_present = elements
15675            .iter()
15676            .rposition(|value| !matches!(value, Value::Hole));
15677        let has_interior_hole = match last_present {
15678            Some(last) => elements[..last]
15679                .iter()
15680                .any(|value| matches!(value, Value::Hole)),
15681            None => false,
15682        };
15683        let mut first = true;
15684        if has_interior_hole {
15685            let mut index = 0;
15686            while index < elements.len() {
15687                let value = &elements[index];
15688                if matches!(value, Value::Hole) {
15689                    index += 1;
15690                    continue;
15691                }
15692                if !first {
15693                    self.out.push_str(", ");
15694                }
15695                first = false;
15696                self.out.push_str(&format!("{index}: "));
15697                self.value(value, level + 1);
15698                index += 1;
15699            }
15700        } else {
15701            for (index, value) in elements.iter().enumerate() {
15702                if matches!(value, Value::Hole) {
15703                    continue;
15704                }
15705                if !first {
15706                    self.out.push_str(", ");
15707                }
15708                first = false;
15709                let _ = index;
15710                self.value(value, level + 1);
15711            }
15712            if let Some(last) = last_present {
15713                let trailing = elements.len() - last - 1;
15714                if trailing > 0 {
15715                    if !first {
15716                        self.out.push_str(", ");
15717                    }
15718                    self.out.push_str(&format!(
15719                        "<{trailing} empty item{}>",
15720                        if trailing > 1 { "s" } else { "" }
15721                    ));
15722                }
15723            } else if !elements.is_empty() {
15724                let count = elements.len();
15725                self.out.push_str(&format!(
15726                    "<{count} empty item{}>",
15727                    if count > 1 { "s" } else { "" }
15728                ));
15729            }
15730        }
15731        self.out.push_str(" ]");
15732    }
15733
15734    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
15735        self.out.push_str("{ ");
15736        let mut first = true;
15737        for key in object.own_keys() {
15738            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
15739                continue;
15740            };
15741            if !property.enumerable {
15742                continue;
15743            }
15744            if !first {
15745                self.out.push_str(", ");
15746            }
15747            first = false;
15748            self.out
15749                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
15750                    &key.to_string_lossy(),
15751                )));
15752            self.out.push_str(": ");
15753            // An accessor has no value to dump; the reference names the half that
15754            // exists instead of calling it.
15755            if property.is_accessor() {
15756                let text = match (property.getter.is_some(), property.setter.is_some()) {
15757                    (true, true) => "[Getter/Setter]",
15758                    (false, true) => "[Setter]",
15759                    _ => "[Getter]",
15760                };
15761                self.out.push_str(text);
15762            } else {
15763                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
15764            }
15765        }
15766        self.out.push_str(" }");
15767    }
15768
15769    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
15770    fn print_string(&mut self, text: &str) {
15771        self.out.push('"');
15772        for character in text.chars() {
15773            match character {
15774                '"' => self.out.push_str("\\\""),
15775                '\\' => self.out.push_str("\\\\"),
15776                '\n' => self.out.push_str("\\n"),
15777                '\r' => self.out.push_str("\\r"),
15778                '\t' => self.out.push_str("\\t"),
15779                c if (c as u32) < 0x20 => {
15780                    self.out.push_str(&format!("\\u{:04x}", c as u32));
15781                }
15782                c => self.out.push(c),
15783            }
15784        }
15785        self.out.push('"');
15786    }
15787}
15788
15789/// How `print` renders a value.
15790///
15791/// `ToString`, except that negative zero keeps its sign — the reference's host
15792/// printer does that while `String(-0)` is `"0"`.
15793pub fn display(value: &Value) -> String {
15794    match value {
15795        Value::Float(number) => crate::value::number_to_string_for_print(*number),
15796        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
15797            "undefined".to_string()
15798        }
15799        other => other.to_js_string(),
15800    }
15801}
15802
15803// ---------------------------------------------------------------------------
15804// Numeric operators
15805// ---------------------------------------------------------------------------
15806
15807/// `a + b` keeping the `Int` representation when it fits.
15808fn add_numbers(left: Value, right: Value) -> Value {
15809    match (&left, &right) {
15810        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
15811            Some(sum) => Value::Int(sum),
15812            None => Value::Float(*a as f64 + *b as f64),
15813        },
15814        _ => Value::Float(left.to_number() + right.to_number()),
15815    }
15816}
15817
15818/// The arithmetic operators other than `+`, which needs string concatenation.
15819fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15820    use Opcode::*;
15821    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
15822    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
15823    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
15824    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
15825        return Ok(match op {
15826            And => Value::Int(x & y),
15827            Or => Value::Int(x | y),
15828            Xor => Value::Int(x ^ y),
15829            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
15830            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
15831            Shr => match (*x as u32) >> ((*y as u32) & 31) {
15832                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
15833                shifted => Value::Float(shifted as f64),
15834            },
15835            Sub => match x.checked_sub(*y) {
15836                Some(value) => Value::Int(value),
15837                None => Value::Float(*x as f64 - *y as f64),
15838            },
15839            _ => return arithmetic_slow(op, left, right),
15840        });
15841    }
15842    arithmetic_slow(op, left, right)
15843}
15844
15845/// [`arithmetic`] for everything the integer fast path above does not take.
15846fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15847    use Opcode::*;
15848    let (a, b) = (left.to_number(), right.to_number());
15849    Ok(match op {
15850        Sub => match (&left, &right) {
15851            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15852                Some(value) => Value::Int(value),
15853                None => Value::Float(a - b),
15854            },
15855            _ => Value::Float(a - b),
15856        },
15857        Mul => Value::Float(a * b),
15858        Div => Value::Float(a / b),
15859        Mod => Value::Float(js_mod(a, b)),
15860        Pow => Value::Float(a.powf(b)),
15861        And => Value::Int(left.to_int32() & right.to_int32()),
15862        Or => Value::Int(left.to_int32() | right.to_int32()),
15863        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15864        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15865        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15866        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15867        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15868        // fits the small-integer representation stays an `Int`; the rest become a
15869        // float, which is how the reference keeps `n >>> 0` non-negative.
15870        Shr => {
15871            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15872            match i32::try_from(shifted) {
15873                Ok(value) => Value::Int(value),
15874                Err(_) => Value::Float(shifted as f64),
15875            }
15876        }
15877        _ => Value::Float(a),
15878    })
15879}
15880
15881/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15882///
15883/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15884/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15885/// slow path where the rules live.
15886fn is_number(value: &Value) -> bool {
15887    matches!(value, Value::Int(_) | Value::Float(_))
15888}
15889
15890/// The `Value::Bool` a comparison operator answers for `ordering`.
15891///
15892/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15893/// false for it, including `<=` and `>=`.
15894fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15895    use Opcode::*;
15896    let answer = match (op, ordering) {
15897        (_, None) => false,
15898        (Lt, Some(ordering)) => ordering.is_lt(),
15899        (Lte, Some(ordering)) => ordering.is_le(),
15900        (Gt, Some(ordering)) => ordering.is_gt(),
15901        (Gte, Some(ordering)) => ordering.is_ge(),
15902        _ => false,
15903    };
15904    Value::Bool(answer)
15905}
15906
15907/// `%`, which follows the sign of the dividend rather than Rust's.
15908fn js_mod(left: f64, right: f64) -> f64 {
15909    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15910        return f64::NAN;
15911    }
15912    if right.is_infinite() {
15913        return left;
15914    }
15915    let remainder = left % right;
15916    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15917    // the spec makes the sign match the dividend.
15918    if remainder == 0.0 {
15919        0.0f64.copysign(left)
15920    } else {
15921        remainder
15922    }
15923}
15924
15925fn negate(value: Value) -> Value {
15926    match value {
15927        Value::Int(0) => Value::Float(-0.0),
15928        Value::Int(i) => Value::Int(-i),
15929        other => Value::Float(-other.to_number()),
15930    }
15931}
15932
15933fn increment(value: Value) -> Value {
15934    match value {
15935        Value::Int(i) => match i.checked_add(1) {
15936            Some(next) => Value::Int(next),
15937            None => Value::Float(i as f64 + 1.0),
15938        },
15939        other => Value::Float(other.to_number() + 1.0),
15940    }
15941}
15942
15943fn decrement(value: Value) -> Value {
15944    match value {
15945        Value::Int(i) => match i.checked_sub(1) {
15946            Some(next) => Value::Int(next),
15947            None => Value::Float(i as f64 - 1.0),
15948        },
15949        other => Value::Float(other.to_number() - 1.0),
15950    }
15951}
15952
15953/// Compare a `BigInt` with an `f64` on their mathematical values.
15954///
15955/// Neither side is rounded to the other's precision: the number is split into its integer
15956/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15957/// when the integer parts are equal. An infinite value is larger than every bigint.
15958fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15959    use std::cmp::Ordering;
15960    if number.is_nan() {
15961        return None;
15962    }
15963    if number.is_infinite() {
15964        return Some(if number > 0.0 {
15965            Ordering::Less
15966        } else {
15967            Ordering::Greater
15968        });
15969    }
15970    let truncated = number.trunc();
15971    // A number wider than `i128` still has an exact integer part, but no bigint form we can
15972    // build cheaply; the sign of the difference is all that is needed, so compare against
15973    // the bigint's own magnitude instead.
15974    if truncated.abs() >= 1.7e38 {
15975        let big_as_f64 = big.to_f64();
15976        return big_as_f64.partial_cmp(&number);
15977    }
15978    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15979    match big.cmp(&integer) {
15980        Ordering::Equal => {
15981            // Same integer part: the fraction decides, and a negative number's fraction is
15982            // below the integer (`-1.5` truncates to `-1`).
15983            if number > truncated {
15984                Some(Ordering::Less)
15985            } else if number < truncated {
15986                Some(Ordering::Greater)
15987            } else {
15988                Some(Ordering::Equal)
15989            }
15990        }
15991        other => Some(other),
15992    }
15993}
15994
15995/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15996///
15997/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15998/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15999/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
16000/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
16001/// rather than treating it as `0`.
16002fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
16003    let PropertyKey::String(text) = key else {
16004        // A symbol is never an index.
16005        return None;
16006    };
16007    let text = text.to_string_lossy();
16008    if text == "-0" {
16009        return Some(-0.0);
16010    }
16011    let number: f64 = text.parse().ok()?;
16012    // The round-trip test *is* the definition: only the canonical spelling qualifies.
16013    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
16014    // `"0.10"` does not.
16015    let rendered = Value::Float(number).to_js_string();
16016    (rendered == text).then_some(number)
16017}
16018
16019/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
16020///
16021/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
16022/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
16023/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
16024/// numeric and invalid, which is why they stop the prototype chain instead of falling
16025/// through it.
16026///
16027/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
16028/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
16029/// `in`, `delete` and `defineProperty` separately to make sure it does not.
16030fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
16031    numeric.is_finite()
16032        && numeric.fract() == 0.0
16033        && !(numeric == 0.0 && numeric.is_sign_negative())
16034        && numeric >= 0.0
16035        && object
16036            .typed_array_length()
16037            .is_some_and(|length| (numeric as usize) < length)
16038}
16039
16040/// `ArrayCreate`'s length bound, `2**32 - 1`.
16041///
16042/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
16043/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
16044/// through — can enforce it without depending on a builtin module.
16045const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;