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(), Value::Undefined)?;
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, function)
2839    }
2840
2841    /// Build a coroutine over an already-resolved body.
2842    ///
2843    /// `callee` is the function object the body belongs to, or `undefined` when there is
2844    /// none — a module with top-level `await`. It has to be handed over rather than
2845    /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2846    /// function's body uses that to initialise its own-name binding. Passing `undefined`
2847    /// made `var f = async function Binding(){ return typeof Binding }` answer
2848    /// `"undefined"`, so a named async function expression could not see its own name and
2849    /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2850    fn new_coroutine_from(
2851        &mut self,
2852        code: Gc<CompiledCode>,
2853        env: Gc<ClosureEnv>,
2854        this: Value,
2855        args: Vec<Value>,
2856        callee: Value,
2857    ) -> JsResult<Gc<JsObject>> {
2858        self.push_frame(code, env, this, args, callee)?;
2859        let frame = self.frames.pop().expect("push_frame just pushed it");
2860        let state = GeneratorState {
2861            frame: Some(frame),
2862            phase: GeneratorPhase::SuspendedStart,
2863            parked_on_await: false,
2864            parked_on_yield_star: false,
2865            requests: std::collections::VecDeque::new(),
2866            async_busy: false,
2867            // An `async function` body is driven by `drive_async`, never by the generator
2868            // protocol, and the object is not reachable from script.
2869            is_async: false,
2870        };
2871        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2872        coroutine.with_mut(|data| {
2873            data.kind = ObjectKind::Generator(Box::new(state));
2874        });
2875        Ok(coroutine)
2876    }
2877
2878    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2879    /// `await` and `value` is what it awaited.
2880    fn resume_coroutine(
2881        &mut self,
2882        coroutine: &Gc<JsObject>,
2883        kind: ResumeKind,
2884        value: Value,
2885    ) -> JsResult<(Value, bool)> {
2886        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2887            ObjectKind::Generator(state) => {
2888                let is_async = state.is_async;
2889                Some(std::mem::replace(
2890                    state.as_mut(),
2891                    GeneratorState {
2892                        frame: None,
2893                        phase: GeneratorPhase::Executing,
2894                        parked_on_await: false,
2895                        parked_on_yield_star: false,
2896                        requests: std::collections::VecDeque::new(),
2897                        async_busy: false,
2898                        is_async,
2899                    },
2900                ))
2901            }
2902            _ => None,
2903        }) else {
2904            return Err(self.type_error("not a coroutine"));
2905        };
2906        let result = self.step_generator(&mut state, kind, value);
2907        coroutine.with_mut(|data| {
2908            data.kind = ObjectKind::Generator(Box::new(state));
2909        });
2910        let (value, done, _ready, _reason) = result?;
2911        Ok((value, done))
2912    }
2913
2914    /// Advance an async body and settle its promise with the outcome.
2915    fn drive_async(
2916        &mut self,
2917        coroutine: &Gc<JsObject>,
2918        promise: &Gc<JsObject>,
2919        kind: ResumeKind,
2920        value: Value,
2921    ) -> JsResult<()> {
2922        match self.resume_coroutine(coroutine, kind, value) {
2923            Ok((value, true)) => {
2924                // `Ok` with `done` means the body finished *normally*, even when it was
2925                // resumed by a `throw` — `try { await p } catch {}` completes by
2926                // returning. Only the `Err` arm below is a rejection.
2927                //
2928                // Resolving rather than fulfilling matters: `return promise` in an async
2929                // body adopts the inner promise, so `async function f(){ return
2930                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2931                // promise.
2932                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2933                    self.reject_promise(promise, reason);
2934                }
2935                Ok(())
2936            }
2937            Ok((value, false)) => {
2938                // Parked on `await`: follow what it awaited and resume with the outcome.
2939                let awaited = match self.promise_resolve_value(value) {
2940                    Ok(awaited) => awaited,
2941                    Err(Signal::Throw(error)) => {
2942                        self.reject_promise(promise, error);
2943                        return Ok(());
2944                    }
2945                    Err(other) => return Err(other),
2946                };
2947                self.hook_await(awaited, coroutine, promise)
2948            }
2949            Err(Signal::Throw(reason)) => {
2950                self.reject_promise(promise, reason);
2951                Ok(())
2952            }
2953            Err(other) => Err(other),
2954        }
2955    }
2956
2957    /// Arrange for `coroutine` to resume when `awaited` settles.
2958    fn hook_await(
2959        &mut self,
2960        awaited: Value,
2961        coroutine: &Gc<JsObject>,
2962        promise: &Gc<JsObject>,
2963    ) -> JsResult<()> {
2964        let resumed = JsObject::function(
2965            self.heap,
2966            Some(self.realm.function_proto.clone()),
2967            Callable::AwaitResume {
2968                coroutine: coroutine.clone(),
2969                promise: promise.clone(),
2970                kind: ResumeKind::Next,
2971            },
2972        );
2973        let raised = JsObject::function(
2974            self.heap,
2975            Some(self.realm.function_proto.clone()),
2976            Callable::AwaitResume {
2977                coroutine: coroutine.clone(),
2978                promise: promise.clone(),
2979                kind: ResumeKind::Throw,
2980            },
2981        );
2982        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2983        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2984        let Value::Object(awaited) = &awaited else {
2985            self.jobs.push_back(Job::Resume {
2986                coroutine: coroutine.clone(),
2987                promise: promise.clone(),
2988                kind: ResumeKind::Next,
2989                value: awaited,
2990            });
2991            return Ok(());
2992        };
2993        self.perform_then(
2994            awaited,
2995            Some(Value::Object(resumed)),
2996            Some(Value::Object(raised)),
2997        )?;
2998        Ok(())
2999    }
3000
3001    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3002    /// things an engine keeps outside it — array elements and an array's `length`.
3003    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3004        if let Some(property) = object.own_property_key(key) {
3005            return Some(property);
3006        }
3007        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3008        // be synthesized too — and every one of them is a plain writable, enumerable,
3009        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3010        // `undefined` before this, which made `key-is-numericindex` fail on its own
3011        // side effect check.
3012        //
3013        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3014        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3015        // likewise not elements however numeric they look.
3016        if object.typed_array_element_type().is_some()
3017            && let Some(numeric) = canonical_numeric_index(key)
3018            && numeric.is_finite()
3019            && numeric.fract() == 0.0
3020            && !(numeric == 0.0 && numeric.is_sign_negative())
3021            && numeric >= 0.0
3022            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3023        {
3024            let value = object.typed_array_element(numeric as usize)?;
3025            return Some(Property::data(value));
3026        }
3027        // An array's elements live in their own vector rather than the property table, so
3028        // a descriptor for one has to be synthesized — with the attributes an element has.
3029        if let Some(index) = key.as_str().and_then(array_index)
3030            && let Some(value) = object.array_get(index as usize)
3031            && !matches!(value, Value::Hole)
3032        {
3033            return Some(Property::data(value));
3034        }
3035        // `length` is an own property of an array that is not in its property table
3036        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3037        // and non-enumerable.
3038        if key.as_str() == Some("length")
3039            && let Some(length) = object.array_length()
3040        {
3041            return Some(Property {
3042                value: Some(crate::object::length_value(length)),
3043                writable: object.length_writable(),
3044                enumerable: false,
3045                configurable: false,
3046                getter: None,
3047                setter: None,
3048                descriptor_fields: None,
3049            });
3050        }
3051        None
3052    }
3053
3054    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3055    pub fn object_get_own_property(
3056        &mut self,
3057        object: &Gc<JsObject>,
3058        key: &PropertyKey,
3059    ) -> JsResult<Option<Property>> {
3060        if let Some(answer) = self.proxy_get_own_property(object, key)? {
3061            return Ok(answer);
3062        }
3063        if let Some(exotic) = object.exotic()
3064            && let Some(answer) = exotic.get_own_property(self, object, key)?
3065        {
3066            return Ok(answer);
3067        }
3068        // A module namespace's bindings are accessors internally and data properties to
3069        // script; see `namespace_own_property`.
3070        if object.module_namespace_marker() {
3071            return self.namespace_own_property(object, key);
3072        }
3073        // A mapped `arguments` index is a data property as far as script can see: the
3074        // accessor pair that aliases the parameter is plumbing, and exposing it would
3075        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3076        // report a `get` where the spec has a `[[Value]]`.
3077        if let Some(index) = key.as_str().and_then(crate::object::array_index)
3078            && let Some(cell) = object.mapped_argument_cell(index as usize)
3079        {
3080            // Non-configurable is *not* the default: an ordinary mapped index is
3081            // configurable, and only becomes non-configurable once something
3082            // redefines it. Preserve whatever the property table currently says.
3083            // The attributes come from whatever the property table holds, because they
3084            // can be changed independently of the mapping; only the *value* and the
3085            // data-property *kind* are the accessor's secret.
3086            let flags = Self::ordinary_own_property(object, key);
3087            if let Some(existing) = &flags
3088                && !existing.is_accessor()
3089            {
3090                // Already demapped: the table entry is the answer, not the cell.
3091                return Ok(flags);
3092            }
3093            return Ok(Some(Property {
3094                value: Some(cell.get()),
3095                writable: true,
3096                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3097                configurable: flags.as_ref().is_some_and(|p| p.configurable),
3098                ..Property::default()
3099            }));
3100        }
3101        Ok(Self::ordinary_own_property(object, key))
3102    }
3103
3104    /// Whether `object` is a module namespace exotic object (§10.4.6).
3105    ///
3106    /// Recognised by shape rather than by a flag: a namespace is the only object whose
3107    /// properties are all accessors over a `ModuleBinding` cell. That is the same
3108    /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3109    /// distinction in one place instead of adding a boolean every constructor has to
3110    /// remember to set.
3111    pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3112        object.module_namespace_marker()
3113    }
3114
3115    /// `[[GetOwnProperty]]` for a module namespace exotic object.
3116    ///
3117    /// The bindings are stored as getters — that is the only way a live binding can be read
3118    /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3119    /// descriptor:
3120    ///
3121    /// ```text
3122    /// { [[Value]]: current value, [[Writable]]: true,
3123    ///   [[Enumerable]]: true, [[Configurable]]: false }
3124    /// ```
3125    ///
3126    /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3127    /// `undefined`. Reporting the accessor instead — which is what the property table holds
3128    /// — made every one of test262's namespace descriptor assertions fail, in both the
3129    /// `await-ns-*` and `promise-then-ns-*` families.
3130    ///
3131    /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3132    /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3133    /// property`); the ordinary descriptor machinery derives that from these attributes.
3134    pub fn namespace_own_property(
3135        &mut self,
3136        object: &Gc<JsObject>,
3137        key: &PropertyKey,
3138    ) -> JsResult<Option<Property>> {
3139        let Some(stored) = Self::ordinary_own_property(object, key) else {
3140            return Ok(None);
3141        };
3142        let Some(Property {
3143            getter: Some(getter),
3144            ..
3145        }) = Some(&stored)
3146        else {
3147            return Ok(Some(stored));
3148        };
3149        // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3150        // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3151        // rather than stored.
3152        let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3153        Ok(Some(Property {
3154            value: Some(value),
3155            writable: true,
3156            enumerable: true,
3157            configurable: false,
3158            ..Property::default()
3159        }))
3160    }
3161
3162    /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3163    ///
3164    /// Modelled as "does this descriptor describe the property that is already there?",
3165    /// because a namespace property's attributes are fixed and its value cannot be changed
3166    /// through the namespace. The three ways to succeed:
3167    ///
3168    /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3169    /// * one whose `[[Value]]` is `SameValue` the current binding value;
3170    /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3171    ///   configurable: false}`.
3172    ///
3173    /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3174    /// false), so it goes through the same check against its stored value — which is what
3175    /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3176    /// answer `true` while `{value: "Other"}` answers `false`.
3177    fn namespace_define_own_property(
3178        &mut self,
3179        object: &Gc<JsObject>,
3180        key: &PropertyKey,
3181        property: &Property,
3182    ) -> JsResult<bool> {
3183        let Some(current) = self.namespace_own_property(object, key)? else {
3184            // A name the namespace does not export cannot be added to it.
3185            return Ok(false);
3186        };
3187        if let Some(value) = &property.value {
3188            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3189            if !self.same_value(value, current_value)? {
3190                return Ok(false);
3191            }
3192        }
3193        Ok(true)
3194    }
3195
3196    /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3197    ///
3198    /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3199    /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3200    /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3201    /// descriptor with no fields at all therefore succeeds, which is what
3202    /// `Reflect.defineProperty(ns, k, {})` checks.
3203    ///
3204    /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3205    /// stored property, and a namespace stores its bindings as accessors, so every
3206    /// definition looked like "accessor → data kind changed" or carried `writable: false`
3207    /// from the accessor's own entry. Presence is only available here, before the merge.
3208    pub fn namespace_define_from_descriptor(
3209        &mut self,
3210        object: &Gc<JsObject>,
3211        key: &PropertyKey,
3212        descriptor: &Gc<JsObject>,
3213    ) -> JsResult<bool> {
3214        let Some(current) = self.namespace_own_property(object, key)? else {
3215            return Ok(false);
3216        };
3217        // An accessor descriptor can never describe a namespace binding.
3218        if self.get_property(descriptor, "get")?.is_some()
3219            || self.get_property(descriptor, "set")?.is_some()
3220        {
3221            return Ok(false);
3222        }
3223        if let Some(value) = self.get_property(descriptor, "value")? {
3224            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3225            if !self.same_value(&value, current_value)? {
3226                return Ok(false);
3227            }
3228        }
3229        // The three attribute fields, when named, must restate what the property already
3230        // has. Not a fixed shape: an exported binding reports
3231        // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3232        // is a real own data property with `{false, false, false}`, and both are namespace
3233        // properties. Comparing against `current` is what makes one rule cover both.
3234        for (name, have) in [
3235            ("writable", current.writable),
3236            ("enumerable", current.enumerable),
3237            ("configurable", current.configurable),
3238        ] {
3239            if let Some(named) = self.get_property(descriptor, name)?
3240                && named.to_boolean() != have
3241            {
3242                return Ok(false);
3243            }
3244        }
3245        Ok(true)
3246    }
3247
3248    /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3249    /// compare a requested value against a live binding.
3250    pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3251        Ok(a.same_value(b))
3252    }
3253
3254    ///
3255    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3256    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3257    /// abstract operation here rather than a private helper in `error.rs`.
3258    ///
3259    /// The name is the whole point: the setter must behave as if the prototype were not
3260    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3261    /// the accessor for every error object in the realm. Everything below follows from that:
3262    ///
3263    /// 1. `thisValue` must be an object — otherwise `TypeError`.
3264    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3265    ///    accessor's own home an error rather than a self-shadow.
3266    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3267    ///    either has a string or has made a mistake.
3268    /// 4. An existing *own* property decides the path — an own setter is called, an own
3269    ///    non-writable data property is a `TypeError` — and only a missing own property
3270    ///    falls through to defining one.
3271    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3272    ///    traps and a non-extensible receiver is a `TypeError`.
3273    ///
3274    /// The installed shape is writable + configurable, not enumerable.
3275    pub fn setter_that_ignores_prototype_properties(
3276        &mut self,
3277        this_value: Value,
3278        home: &Gc<JsObject>,
3279        property_key: &str,
3280        args: &[Value],
3281    ) -> JsResult<Value> {
3282        self.setter_that_ignores_prototype_properties_key(
3283            this_value,
3284            home,
3285            &PropertyKey::from(property_key),
3286            args,
3287        )
3288    }
3289
3290    /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3291    ///
3292    /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3293    pub fn setter_that_ignores_prototype_properties_key(
3294        &mut self,
3295        this_value: Value,
3296        home: &Gc<JsObject>,
3297        key: &PropertyKey,
3298        args: &[Value],
3299    ) -> JsResult<Value> {
3300        let Some(receiver) = this_value.as_object().cloned() else {
3301            return Err(self.type_error("setter called on a non-object"));
3302        };
3303        if Gc::ptr_eq(&receiver, home) {
3304            return Err(self.type_error("cannot assign to the accessor's own home object"));
3305        }
3306        // No type check here: §7.3.40 takes an arbitrary `v`, and
3307        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3308        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3309        // before calling this.
3310        let value = args.first().cloned().unwrap_or(Value::Undefined);
3311        // Step 4: an own property on the receiver changes what happens, and there are three
3312        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3313        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3314        // `Set` with `throw = true`, and a test exists for each.
3315        if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3316            if existing.is_accessor() && existing.setter.is_none() {
3317                // A getter-only own accessor cannot be written through.
3318                return Err(self.type_error("no setter for the own property"));
3319            }
3320            // Everything else — an own data property, or an own accessor *with* a setter —
3321            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3322            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3323            // an own user setter receives the value (`setter-own-accessor`), because
3324            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3325            // setter directly is the difference between one code path and two that can
3326            // disagree.
3327            self.set_property_with_key(
3328                &receiver,
3329                key,
3330                value.clone(),
3331                crate::interp::DeleteFailure::Throw,
3332            )?;
3333            return Ok(Value::Undefined);
3334        }
3335        let property = Property {
3336            value: Some(value.clone()),
3337            writable: true,
3338            // Enumerable, despite the accessor it shadows not being. The reference installs
3339            // it that way and six cases check it (`setter-creates-own-property` and friends).
3340            enumerable: true,
3341            configurable: true,
3342            ..Property::default()
3343        };
3344        if !self.object_define_own_property(&receiver, key, property)? {
3345            return Err(self.type_error("the receiver refused the definition"));
3346        }
3347        Ok(Value::Undefined)
3348    }
3349
3350    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3351    ///
3352    /// The indices of a typed array are not properties at all — they are bytes in the
3353    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3354    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3355    /// enumerable and configurable, so a definition can only ever change the *value*, and
3356    /// every other descriptor is refused rather than applied.
3357    ///
3358    /// The order of the checks is the spec's, and two of them are load-bearing:
3359    ///
3360    /// * the index is validated **before** the value is converted, because the conversion
3361    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3362    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3363    ///   happens when the index was valid on the way in;
3364    /// * the store is attempted even when the index has gone out of bounds by the time the
3365    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3366    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3367    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3368    ///
3369    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3370    /// the existing element, which is harmless here: every valid index is already
3371    /// writable, enumerable and configurable, so a `false` in the merged property can only
3372    /// have come from the descriptor having named `false`.
3373    fn integer_indexed_define_own_property(
3374        &mut self,
3375        object: &Gc<JsObject>,
3376        numeric: f64,
3377        property: &Property,
3378    ) -> JsResult<bool> {
3379        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3380        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3381        if !typed_array_index_is_valid(object, numeric) {
3382            return Ok(false);
3383        }
3384        // Step 6: the indices are data properties, so an accessor descriptor is refused
3385        // rather than converted. `Object.defineProperty` turns the `false` into a
3386        // `TypeError`; `Reflect.defineProperty` reports it.
3387        if property.is_accessor() {
3388            return Ok(false);
3389        }
3390        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3391        // definition that asks for anything else cannot be honoured.
3392        if !property.writable || !property.enumerable || !property.configurable {
3393            return Ok(false);
3394        }
3395        // Step 10: only a descriptor that names a value stores anything.
3396        let Some(value) = property.value.clone() else {
3397            return Ok(true);
3398        };
3399        let Some(element) = object.typed_array_element_type() else {
3400            return Ok(false);
3401        };
3402        let stored = self.element_value(element, value)?;
3403        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3404            return Err(self.type_error(reason));
3405        }
3406        Ok(true)
3407    }
3408
3409    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3410    pub fn object_define_own_property(
3411        &mut self,
3412        object: &Gc<JsObject>,
3413        key: &PropertyKey,
3414        property: Property,
3415    ) -> JsResult<bool> {
3416        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3417            return Ok(accepted);
3418        }
3419        // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3420        //
3421        // The only definitions that can succeed are ones describing the property the
3422        // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3423        // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3424        // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3425        // `writable: false`, `configurable: true`, or any name the namespace does not
3426        // export is `false`.
3427        //
3428        // The ordinary path gets the no-change case right by accident — it compares against
3429        // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3430        // is an accessor internally while the definition script writes is a data descriptor.
3431        // Answering here is what makes that attribute-only definition a no-op rather than a
3432        // refusal (`namespace/await-ns-define-own-property`).
3433        if object.module_namespace_marker() {
3434            return self.namespace_define_own_property(object, key, &property);
3435        }
3436        // A proxy always answers above — with `Some` from its trap, or with `None` when
3437        // the trap is absent, and then the definition belongs to the **target**
3438        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3439        // when there is no trap). Falling through to the ordinary path here defined the
3440        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3441        // property the target never saw.
3442        if object.proxy_state().is_some() {
3443            let Some((target, _handler)) = self.proxy_parts(object)? else {
3444                return Err(self.type_error("cannot use a proxy that has been revoked"));
3445            };
3446            return self.object_define_own_property(&target, key, property);
3447        }
3448        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3449        // they accept exactly one descriptor shape. This has to happen before the
3450        // ordinary path, which would happily store a data property next to the buffer —
3451        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3452        // and `TypedArray/prototype/set` are about this section.
3453        if object.typed_array_element_type().is_some()
3454            && let Some(index) = canonical_numeric_index(key)
3455        {
3456            return self.integer_indexed_define_own_property(object, index, &property);
3457        }
3458        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3459        // non-extensible object. The check lives here rather than in the callers because
3460        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3461        // `Array.prototype.filter` uses to store its result, and a species object made
3462        // non-extensible by its own constructor must make that a `TypeError`
3463        // (`target-array-non-extensible`).
3464        // Note the `is_none()`: an already-present property may still be **redefined** on a
3465        // non-extensible object, and only *adding* one is refused (as Distinct from
3466        // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3467        // properties — testing extensibility before looking for the property made every
3468        // `Object.freeze` of an ordinary object refuse its own second step).
3469        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3470            return Ok(false);
3471        }
3472        // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3473        // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3474        // an omitted field is left alone). Merging here rather than at each call site is
3475        // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3476        // the value and `enumerable` in place.
3477        //
3478        // The merge is a no-op when the property is absent: there is nothing to keep.
3479        let was_partial = property.descriptor_fields.is_some();
3480        let property = match property.descriptor_fields {
3481            None => property,
3482            Some(fields) => {
3483                let base = self.object_get_own_property(object, key)?;
3484                let mut merged = base.clone().unwrap_or_default();
3485                // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3486                // descriptor names, and switching kind discards the other half —
3487                // `{set: f}` on a data property is an accessor with no getter, not a data
3488                // property whose `get` happens to be absent.
3489                let wants_accessor = fields.get || fields.set;
3490                let wants_data = fields.value || fields.writable;
3491                if wants_accessor {
3492                    merged.value = None;
3493                    merged.writable = false;
3494                    merged.getter = property.getter.clone();
3495                    merged.setter = property.setter.clone();
3496                } else if wants_data {
3497                    merged.getter = None;
3498                    merged.setter = None;
3499                    if fields.value {
3500                        merged.value = property.value.clone();
3501                    }
3502                    if fields.writable {
3503                        merged.writable = property.writable;
3504                    }
3505                }
3506                if fields.enumerable {
3507                    merged.enumerable = property.enumerable;
3508                }
3509                if fields.configurable {
3510                    merged.configurable = property.configurable;
3511                }
3512                merged.descriptor_fields = None;
3513                merged
3514            }
3515        };
3516        // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3517        // descriptor. `define_property_on` runs the same check before it calls here, so an
3518        // ordinary object is already covered; what is *not* is the forwarding a proxy does
3519        // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3520        // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3521        // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3522        // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3523        // own define would have refused.
3524        //
3525        // Only partial descriptors are validated here. A whole `Property` passed by an
3526        // internal caller (`Property::data(…)`) carries attributes that say nothing about
3527        // what the descriptor "named", and those callers rely on the write landing.
3528        if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3529            // Every branch below is gated on `!existing.configurable`: a *configurable*
3530            // property may be reshaped however the descriptor likes, which is why an
3531            // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3532            // must succeed. Testing only `writable` refused that and broke
3533            // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3534            let same_kind = existing.is_accessor() == property.is_accessor();
3535            if !same_kind {
3536                // Step 4: a non-configurable property may not change kind.
3537                if !existing.configurable {
3538                    return Ok(false);
3539                }
3540            } else if existing.is_accessor() {
3541                // Step 6: an accessor's halves are its value.
3542                if !existing.configurable
3543                    && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3544                        || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3545                {
3546                    return Ok(false);
3547                }
3548            } else if !existing.configurable && !existing.writable {
3549                // Step 7: a non-configurable *and* non-writable data property's value is
3550                // fixed, and it may not become writable again.
3551                if property.writable {
3552                    return Ok(false);
3553                }
3554                let current = existing.value.clone().unwrap_or(Value::Undefined);
3555                let requested = property.value.clone().unwrap_or(Value::Undefined);
3556                if !current.same_value(&requested) {
3557                    return Ok(false);
3558                }
3559            }
3560            // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3561            // is frozen with it.
3562            if !existing.configurable
3563                && (property.configurable || property.enumerable != existing.enumerable)
3564            {
3565                return Ok(false);
3566            }
3567        }
3568        // A host class that intercepts definitions owns the attributes of the properties it
3569        // defines: `_class`-style storage on the native side is the usual reason.
3570        if let Some(exotic) = object.exotic()
3571            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3572        {
3573            return Ok(accepted);
3574        }
3575        // An array index is stored in the element vector, which can hold a plain value and
3576        // nothing else. An accessor — or a data property with non-default attributes —
3577        // therefore has to live in the property table, and the element slot is blanked so
3578        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3579        // {get})` stored the accessor where no read ever looked, and the array kept
3580        // answering its old value.
3581        // An array's `length` is not stored in the property table, so defining it has to
3582        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3583        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3584        // {value: 1})` reported success and changed nothing.
3585        if key.as_str() == Some("length") && object.is_array() {
3586            // `{writable: false}` on `length` does not change the length, but it does make
3587            // it read-only — after which neither a later `{writable: true}` nor a store
3588            // past the end may succeed.
3589            if property.value.is_none() {
3590                if !object.length_writable() && property.writable {
3591                    return Ok(false);
3592                }
3593                object.set_length_writable(property.writable);
3594                return Ok(true);
3595            }
3596            if !object.length_writable() {
3597                return Ok(false);
3598            }
3599        }
3600        if key.as_str() == Some("length")
3601            && object.is_array()
3602            && let Some(value) = property.value.clone()
3603        {
3604            let requested = value.to_number();
3605            let valid = requested.is_finite()
3606                && requested >= 0.0
3607                && requested.fract() == 0.0
3608                && requested <= u32::MAX as f64;
3609            if !valid {
3610                return Err(self.range_error("invalid array length"));
3611            }
3612            // Truncating deletes the elements above the new length, and a non-configurable
3613            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3614            // makes `a.length = 2` fail rather than quietly drop it.
3615            let current = object.array_length().unwrap_or(0);
3616            let requested = requested as usize;
3617            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3618                // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3619                // `[[Writable]]: false` when the descriptor asked for it — the length is
3620                // left at its old value but locked. Returning `false` alone left it
3621                // writable, which `verifyProperty` catches
3622                // (`defineProperties/15.2.3.7-6-a-164`).
3623                if property
3624                    .descriptor_fields
3625                    .is_some_and(|fields| fields.writable)
3626                    && !property.writable
3627                    && object.length_writable()
3628                {
3629                    object.set_length_writable(false);
3630                }
3631                return Ok(false);
3632            }
3633            object.array_set_length(self.heap, requested);
3634            return Ok(true);
3635        }
3636        let plain = property.writable
3637            && property.enumerable
3638            && property.configurable
3639            && !property.is_accessor();
3640        if let Some(index) = key.as_str().and_then(array_index)
3641            && object.is_array()
3642        {
3643            // Growing the array needs a writable `length`: after
3644            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3645            // be added.
3646            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3647                return Ok(false);
3648            }
3649            if plain && property.value.is_some() {
3650                // An ordinary element: the vector is where a read looks first, so it has
3651                // to be the vector that changes — unless the index is too far out to be
3652                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3653                // one property, because past its own limit it stores the index as an
3654                // ordinary key. Falling through to `define_key` below is the same choice,
3655                // and the alternative was worse: the store used to be *dropped* and the
3656                // length left at 0, which is a silent wrong answer.
3657                let value = property.value.clone().unwrap_or(Value::Undefined);
3658                object.delete_key(key);
3659                if object.array_set(self.heap, index as usize, value) {
3660                    return Ok(true);
3661                }
3662                // Past the dense limit the element lives in the table like any property.
3663                object.note_element_descriptor();
3664                object.define_key(key, property);
3665                // A sparse store past the dense limit still extends `length`, which is what
3666                // `a[a.length] = v` relies on — but only extends: shortening would delete
3667                // the sparse properties above the index, including this one.
3668                if index as usize + 1 > object.array_length().unwrap_or(0) {
3669                    object.array_set_length(self.heap, index as usize + 1);
3670                }
3671                return Ok(true);
3672            }
3673            // A non-plain element — an accessor, or an attribute that is not the default —
3674            // lives in the table while the slot becomes a hole. Recording it keeps every
3675            // later `a[i] = v` off the dense path, where the write would have shadowed the
3676            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3677            // replace the accessor with a plain data property.
3678            object.note_element_descriptor();
3679            object.define_key(key, property);
3680            // The slot stays, so `length` does not shrink; a hole is not an element, so
3681            // the table entry is now what a read finds.
3682            object.array_set(self.heap, index as usize, Value::Hole);
3683            // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3684            // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3685            // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3686            // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3687            if index as usize + 1 > object.array_length().unwrap_or(0) {
3688                object.array_set_length(self.heap, index as usize + 1);
3689            }
3690            return Ok(true);
3691        }
3692        object.define_key(key, property);
3693        Ok(true)
3694    }
3695
3696    /// Build a proxy object over `target`, with its traps read from `handler`.
3697    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3698        JsObject::proxy(self.heap, target, handler)
3699    }
3700
3701    /// The `revoke` function for a proxy's slots.
3702    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3703        let revoke = JsObject::function(
3704            self.heap,
3705            Some(self.realm.function_proto.clone()),
3706            Callable::Revoker(slots),
3707        );
3708        // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3709        // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3710        // inherited from `Function.prototype` reads the same but fails the three cases that
3711        // check the own-property list (`revocation-function-{length,name,property-order}`).
3712        revoke.define("length", Property::name_or_length(Value::Int(0)));
3713        revoke.define("name", Property::name_or_length(self.string("")));
3714        revoke
3715    }
3716
3717    /// A new array.
3718    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3719        let array = JsObject::array(
3720            self.heap,
3721            Some(self.realm.array_proto.clone()),
3722            elements.len(),
3723        );
3724        for (index, element) in elements.into_iter().enumerate() {
3725            array.array_set(self.heap, index, element);
3726        }
3727        array
3728    }
3729
3730    /// A new native function object.
3731    ///
3732    /// The observable `name` and `length` are installed as properties here, which is
3733    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3734    /// so `f.name = "x"` behaves like the writable property it is.
3735    /// A native constructor that builds its own instance after validating its arguments.
3736    ///
3737    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3738    /// check runs before `new.target.prototype` is read.
3739    pub fn new_native_ctor(
3740        &self,
3741        name: impl Into<String>,
3742        length: u32,
3743        func: NativeFn,
3744    ) -> Gc<JsObject> {
3745        let function = JsObject::function(
3746            self.heap,
3747            Some(self.realm.function_proto.clone()),
3748            Callable::Native {
3749                func,
3750                own_instance: true,
3751            },
3752        );
3753        function.set_constructible(true);
3754        function.define(
3755            "length",
3756            Property::name_or_length(Value::Int(length as i32)),
3757        );
3758        function.define("name", Property::name_or_length(self.string(name)));
3759        function
3760    }
3761
3762    /// A native constructor that lets `new` build the instance first.
3763    ///
3764    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3765    /// validation that must precede reading `new.target.prototype`, so the object can be
3766    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3767    /// which makes a *method* and therefore not a constructor at all.
3768    pub fn new_native_constructor(
3769        &self,
3770        name: impl Into<String>,
3771        length: u32,
3772        func: NativeFn,
3773    ) -> Gc<JsObject> {
3774        let function = self.new_native(name, length, func);
3775        function.set_constructible(true);
3776        function
3777    }
3778
3779    /// A new host function object: a native closure that carries its own state.
3780    ///
3781    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3782    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3783    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3784    /// this safe: the closure must not capture a `Gc`.
3785    pub fn new_host_function(
3786        &self,
3787        name: impl Into<String>,
3788        length: u32,
3789        func: crate::object::HostFn,
3790    ) -> Gc<JsObject> {
3791        self.new_host_inner(name.into(), length, func, false)
3792    }
3793
3794    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3795    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3796    pub fn new_host_ctor(
3797        &self,
3798        name: impl Into<String>,
3799        length: u32,
3800        func: crate::object::HostFn,
3801    ) -> Gc<JsObject> {
3802        let function = self.new_host_inner(name.into(), length, func, true);
3803        function.set_constructible(true);
3804        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3805        // installs its own methods on it, so it starts as a plain object.
3806        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3807        function.define(
3808            "prototype",
3809            Property {
3810                value: Some(Value::Object(proto)),
3811                writable: true,
3812                enumerable: false,
3813                configurable: false,
3814                ..Property::default()
3815            },
3816        );
3817        function
3818    }
3819
3820    fn new_host_inner(
3821        &self,
3822        name: String,
3823        length: u32,
3824        func: crate::object::HostFn,
3825        own_instance: bool,
3826    ) -> Gc<JsObject> {
3827        let function = JsObject::function(
3828            self.heap,
3829            Some(self.realm.function_proto.clone()),
3830            Callable::Host {
3831                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3832                own_instance,
3833            },
3834        );
3835        function.define(
3836            "length",
3837            Property::name_or_length(Value::Int(length as i32)),
3838        );
3839        function.define("name", Property::name_or_length(self.string(name)));
3840        function
3841    }
3842
3843    /// A callable object with the `length`/`name` a built-in function has, in that order.
3844    ///
3845    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3846    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3847    /// [`JsObject::function`] defines neither, which is why every capability helper built
3848    /// with it reported no own `length` and no own `name` at all.
3849    ///
3850    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3851    /// configurable.
3852    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3853        let function =
3854            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3855        function.define(
3856            "length",
3857            Property::name_or_length(Value::Int(length as i32)),
3858        );
3859        function.define("name", Property::name_or_length(self.string(name)));
3860        function
3861    }
3862
3863    /// A new native function object.
3864    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3865        let function = JsObject::function(
3866            self.heap,
3867            Some(self.realm.function_proto.clone()),
3868            Callable::Native {
3869                func,
3870                own_instance: false,
3871            },
3872        );
3873        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3874        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3875        // `length,name` and this listed `name,length`. A bytecode function already gets it
3876        // the right way round; only native ones were built backwards.
3877        function.define(
3878            "length",
3879            Property::name_or_length(Value::Int(length as i32)),
3880        );
3881        function.define("name", Property::name_or_length(self.string(name)));
3882        function
3883    }
3884
3885    /// A new bound function.
3886    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3887        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3888        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3889        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3890        let constructible = target
3891            .as_object()
3892            .is_some_and(|target| target.is_constructor());
3893        let bound = JsObject::function(
3894            self.heap,
3895            Some(self.realm.function_proto.clone()),
3896            Callable::Bound { target, this, args },
3897        );
3898        bound.set_constructible(constructible);
3899        bound
3900    }
3901
3902    /// A new reference cell.
3903    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3904        Gc::new(self.heap, Cell::new(value))
3905    }
3906
3907    // -- running ------------------------------------------------------------
3908
3909    /// Evaluate `code` as a script body and return its completion value.
3910    /// Compile and run `source` for the engine's own use, returning its completion value.
3911    ///
3912    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3913    /// needs to be a real async function, and the engine already runs those as coroutines,
3914    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3915    ///
3916    /// Differences from [`Self::eval_in_global`], both deliberate:
3917    ///
3918    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3919    ///   being built, and the source is an IIFE that only constructs a closure, so there
3920    ///   is nothing to drain — and draining here would run script-queued jobs in the
3921    ///   middle of `install`.
3922    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3923    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3924    ///   and it should not look like the user wrote something wrong.
3925    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3926        let program = match js_parse::parse_script(source) {
3927            Ok(program) => program,
3928            Err(error) => {
3929                let message = format!("builtin source does not parse: {error}");
3930                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3931            }
3932        };
3933        let mut code = match js_compile::compile_script_with_source(&program, source) {
3934            Ok(code) => code,
3935            Err(error) => {
3936                let message = format!("builtin source does not compile: {}", error.message);
3937                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3938            }
3939        };
3940        // The frame has to name something, and `<builtin>` is what a stack trace through
3941        // this code should say.
3942        code.set_filename("<builtin>");
3943        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3944        let closure_vars = compiled.code.closure_vars.clone();
3945        let env = self.global_env(&closure_vars);
3946        let this = Value::Object(self.realm.global.clone());
3947        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3948    }
3949
3950    /// Run an already-parsed script and drain the microtasks it queued.
3951    ///
3952    /// The drain is what lets an `async` function's body advance past its first `await`
3953    /// before the host sees the result: nothing else pumps the job queue.
3954    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3955        let this = Value::Object(self.realm.global.clone());
3956        self.run_script_with_this(code, this)
3957    }
3958
3959    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3960    ///
3961    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3962    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3963    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3964    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3965    /// state the next script evaluation tripped over.
3966    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3967        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3968        let closure_vars = compiled.code.closure_vars.clone();
3969        let env = self.global_env(&closure_vars);
3970        let callee = Value::Undefined;
3971        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3972        // The script is done, so the microtasks it queued run before the host sees the
3973        // result. Without this an `async` function's body would never advance past its
3974        // first `await`, because nothing else drains the queue.
3975        self.drain_jobs()?;
3976        Ok(result)
3977    }
3978
3979    /// Compile and run `source` in global scope, returning its completion value.
3980    ///
3981    /// This is what `eval` and `new Function` use. Running it as a script means it
3982    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3983    /// for a `Function` body; a *direct* eval that reads a local variable would need
3984    /// the compiler to hand its variable environment over, which is not implemented.
3985    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3986        self.eval_in_global_named(source, EVAL_FILE, false)
3987    }
3988
3989    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3990    ///
3991    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3992    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3993    /// through the code, so they cannot share one constant.
3994    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3995        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3996    }
3997
3998    /// Evaluate `source` as a global script, reported under `file`.
3999    ///
4000    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4001    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4002    /// from inside a C callback, where the interpreter is the running one rather than a
4003    /// context's own.
4004    pub fn eval_in_global_named(
4005        &mut self,
4006        source: &str,
4007        file: &str,
4008        barrier: bool,
4009    ) -> JsResult<Value> {
4010        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4011        // eval-created global binding — configurable, unlike a script's own `var`.
4012        self.eval_depth += 1;
4013        if barrier {
4014            let depth = self.frames.len();
4015            self.trace_barriers.push(depth);
4016        }
4017        let result = self.eval_in_global_inner(source, file);
4018        if barrier {
4019            self.trace_barriers.pop();
4020        }
4021        self.eval_depth -= 1;
4022        result
4023    }
4024
4025    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
4026        let compiled = self.compile_global_script(source, file, false)?;
4027        let strict = compiled.strict;
4028        self.run_eval_script(compiled, strict)
4029    }
4030
4031    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4032    ///
4033    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4034    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4035    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4036    /// direct eval's is.
4037    pub fn eval_script_with_this(
4038        &mut self,
4039        source: &str,
4040        file: &str,
4041        this: Value,
4042    ) -> JsResult<Value> {
4043        let program = match js_parse::parse_script(source) {
4044            Ok(program) => program,
4045            Err(error) => {
4046                return Err(Signal::Throw(self.syntax_error_at(
4047                    file,
4048                    error.span.start.line,
4049                    error.span.start.column,
4050                    &error.message,
4051                )));
4052            }
4053        };
4054        let mut compiled = match js_compile::compile_script(&program) {
4055            Ok(compiled) => compiled,
4056            Err(error) => {
4057                return Err(Signal::Throw(self.syntax_error_at(
4058                    file,
4059                    error.span.start.line,
4060                    error.span.start.column,
4061                    &error.message,
4062                )));
4063            }
4064        };
4065        compiled.set_filename(file);
4066        self.run_script_with_this(compiled, this)
4067    }
4068
4069    /// Parse and compile `source` as a global script, without running it.
4070    ///
4071    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4072    /// before a promise exists to reject — while still evaluating in the same eval context
4073    /// (direct-eval strictness, `new.target`, `super`).
4074    fn compile_global_script(
4075        &mut self,
4076        source: &str,
4077        file: &str,
4078        async_body: bool,
4079    ) -> JsResult<CompiledFunction> {
4080        // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4081        // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4082        // context at all. The site is what tells the two apart — an indirect call leaves no
4083        // site behind, since only a bare `eval(...)` is recorded.
4084        let site = self.eval_site_at_cursor();
4085        // Strictness follows the same rule, and it is *not* a detail: §19.2.1.1 step 4
4086        // makes the eval code strict when the caller is strict **and the call is direct**.
4087        // So `var s = eval; s("var eval;")` called from strict code is sloppy — legal —
4088        // while `eval("var eval;")` there is a `SyntaxError`
4089        // (`statements/variable/12.2.1-*-s`). Inheriting unconditionally rejected the
4090        // indirect form. A `"use strict"` prologue in the source still works either way:
4091        // the parser reads the directive itself, which is how a script becomes strict.
4092        let strict = site.is_some() && self.current_strict();
4093        // `eval` runs in the caller's function context, so `new.target` is legal here
4094        // even though the source is a bare script — and so is `super.x` when the caller
4095        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4096        // caller's, which is what `special_object 4` already does.
4097        let private = site
4098            .map(|site| site.private_names.clone())
4099            .unwrap_or_default();
4100        let context = js_parse::EvalContext {
4101            in_method: site.is_some() && self.enclosing_home_object().is_some(),
4102            // `super()` belongs to a derived constructor, and an eval'd body is not a
4103            // constructor at all: the caller frame's `this` is already built.
4104            in_derived_constructor: false,
4105            // Private names are lexically scoped, so a direct `eval` inside a class body
4106            // can see them; see `Interp::eval_private_names`.
4107            private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4108            arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4109            new_target_allowed: site.is_some(),
4110        };
4111        // A *global* eval is not a function body: `new.target` and `super` are out of
4112        // reach there. Its `{async: true}` form differs in the other direction — the body
4113        // may `await` — so the two flags are independent and the reference sets both from
4114        // the eval type rather than from the caller.
4115        let parsed = if async_body {
4116            js_parse::parse_suspensible_global_eval(source, strict)
4117        } else {
4118            js_parse::parse_eval_script_in(source, strict, context)
4119        };
4120        let program = match parsed {
4121            Ok(program) => program,
4122            Err(error) => {
4123                // The message is bare: the position lives in `fileName`,
4124                // `lineNumber`, `columnNumber` and the stack frame above, which is where
4125                // the reference puts it. An `invalid source: L:C: ` prefix made
4126                // `e.message` differ from the reference while the stack already agreed.
4127                return Err(Signal::Throw(self.syntax_error_at(
4128                    file,
4129                    error.span.start.line,
4130                    error.span.start.column,
4131                    &error.message,
4132                )));
4133            }
4134        };
4135        let mut compiled = match if async_body {
4136            js_compile::compile_eval_with_private(&program, &private, true)
4137        } else {
4138            js_compile::compile_eval_with_private(&program, &private, false)
4139        } {
4140            Ok(compiled) => compiled,
4141            // A construct the compiler does not handle yet is reported the same way a
4142            // parse error is: it happens before anything runs, so the trace is the
4143            // position in the source followed by the caller.
4144            Err(error) => {
4145                return Err(Signal::Throw(self.syntax_error_at(
4146                    file,
4147                    error.span.start.line,
4148                    error.span.start.column,
4149                    &error.message,
4150                )));
4151            }
4152        };
4153        compiled.set_filename(file);
4154        Ok(compiled)
4155    }
4156
4157    /// The private names the code at the current position can see, innermost first.
4158    ///
4159    /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4160    /// direct `eval` runs inside its caller's scope, so
4161    /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4162    /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4163    /// here rather than being derivable from the eval'd source.
4164    ///
4165    /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4166    /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4167    /// [`Interp::run_eval_script`] uses for "direct".
4168    fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4169        let frame = self.frames.last()?;
4170        let (line, column) = frame
4171            .code
4172            .code
4173            .position_at(frame.at as u32)
4174            .unwrap_or_default();
4175        // The nearest site at or before the current position: the recorded position of the
4176        // `call` instruction is the callee's, which sits a few columns inside the call
4177        // expression the compiler recorded, so an exact match would never be found.
4178        frame
4179            .code
4180            .code
4181            .eval_sites
4182            .iter()
4183            .filter(|site| (site.line, site.column) <= (line, column))
4184            .max_by_key(|site| (site.line, site.column))
4185    }
4186
4187    /// Run an `eval`'d script in the caller's scope.
4188    ///
4189    /// Three things have to come from the calling frame, because the eval'd code is a
4190    /// script and would otherwise see only the global object:
4191    ///
4192    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4193    /// * `arguments`, exposed as a binding of the eval's own scope, so
4194    ///   `f("arguments.length", 1)` sees the caller's arguments;
4195    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4196    ///   `eval("var v = 1")` into the global object.
4197    ///
4198    /// Locals of the calling function are *not* reachable: that needs the compiler to
4199    /// hand its variable environment over, which this milestone does not do.
4200    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4201        // `this` and `arguments` come from the innermost frame only — those are not
4202        // lexical — while the name bindings come from the whole chain of frames, part
4203        // of it being ordinary scope resolution.
4204        // An arrow has no `this` of its own, so an `eval` inside one inherits the
4205        // enclosing function's receiver — the lexical `this` the arrow was compiled to
4206        // read from its closure.
4207        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4208        // variable environment is the innermost frame of all: an arrow's own body is where
4209        // `var`s declared by an `eval` inside it belong.
4210        let caller_index = self
4211            .frames
4212            .iter()
4213            .rposition(|frame| !frame.code.code.is_arrow)
4214            .or_else(|| self.frames.len().checked_sub(1));
4215        let env_index = self.frames.len().checked_sub(1);
4216        let caller = caller_index.and_then(|index| self.frames.get(index));
4217        let (this, passed) = match caller {
4218            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4219            // No frame at all: the eval is running at the top level, so there is
4220            // nothing to inherit and the global receiver is right.
4221            None => (Value::Object(self.realm.global.clone()), Vec::new()),
4222        };
4223        // Innermost frame first, so the first binding found for a name is the one that
4224        // shadows the rest. A script frame (`<eval>`) contributes nothing.
4225        let mut bindings: Vec<EvalBinding> = Vec::new();
4226        // The calling function's own bindings, resolved by the compiler at the call
4227        // site. That table is the only reliable answer when a name is declared twice in
4228        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4229        // body means, and guessing by declaration order picks the wrong one as soon as
4230        // two loops in a row use the same name.
4231        // Only a *direct* eval sees the caller's scope. The compiler records a site for
4232        // every direct call — a bare `eval(...)` callee — so finding one at the current
4233        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4234        // callee to a value first and leave no site behind.
4235        let mut direct = false;
4236        let mut resolved_here = false;
4237        if let Some(frame) = self.frames.last() {
4238            let (line, column) = frame
4239                .code
4240                .code
4241                .position_at(frame.at as u32)
4242                .unwrap_or_default();
4243            // The nearest site at or before the current position, not an exact match:
4244            // the recorded position of the `call` instruction is the callee's, which
4245            // sits a few columns inside the call expression the compiler recorded. A
4246            // site is unique per call, so "the closest one behind us" identifies it.
4247            if let Some(site) = frame
4248                .code
4249                .code
4250                .eval_sites
4251                .iter()
4252                .filter(|site| (site.line, site.column) <= (line, column))
4253                .max_by_key(|site| (site.line, site.column))
4254            {
4255                direct = true;
4256                resolved_here = true;
4257                for binding in &site.bindings {
4258                    // An enclosing function's frame sits `owner` levels below the one
4259                    // running the call.
4260                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4261                    else {
4262                        continue;
4263                    };
4264                    bindings.push(EvalBinding {
4265                        name: binding.name.clone(),
4266                        frame,
4267                        slot: if binding.is_arg {
4268                            EvalSlot::Arg
4269                        } else {
4270                            EvalSlot::Local
4271                        },
4272                        index: binding.index as usize,
4273                    });
4274                }
4275            }
4276        }
4277        for frame_index in (0..self.frames.len()).rev() {
4278            // Skip the innermost frame's flat scan when the compiler already answered
4279            // for it; an enclosing frame still needs one, because the eval resolves
4280            // those names dynamically.
4281            if resolved_here && frame_index == self.frames.len() - 1 {
4282                continue;
4283            }
4284            let frame = &self.frames[frame_index];
4285            for (index, arg) in frame.code.code.args.iter().enumerate() {
4286                bindings.push(EvalBinding {
4287                    name: arg.name.clone(),
4288                    frame: frame_index,
4289                    slot: EvalSlot::Arg,
4290                    index,
4291                });
4292            }
4293            for (index, local) in frame.code.code.vars.iter().enumerate() {
4294                bindings.push(EvalBinding {
4295                    name: local.name.clone(),
4296                    frame: frame_index,
4297                    slot: EvalSlot::Local,
4298                    index,
4299                });
4300            }
4301        }
4302        let mut seen = BTreeSet::new();
4303        bindings.retain(|binding| seen.insert(binding.name.clone()));
4304
4305        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4306        // elements is all the spec's ordinary uses need.
4307        //
4308        // Known divergence: this is bound for a *global* eval too, where there is no
4309        // caller and the reference throws `'arguments' is not defined`. Deciding properly
4310        // needs "does the calling frame have an `arguments` of its own", which is not
4311        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4312        // script or eval body does not, and `eval(b)` passes the callee as a value so even
4313        // the call-site detection does not answer it. Modelled as a binding in the caller's
4314        // variable environment, this would fall out; that is a larger change than the one
4315        // this comment is attached to.
4316        let arguments = Value::Object(self.new_array(passed));
4317
4318        // Only a *strict* eval gets a variable environment of its own. A sloppy one
4319        // declares its `var`s in the caller's — which for a top-level eval is the global
4320        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4321        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4322        // vanish into a scope nobody reads back from.
4323        let previous_scope = if code_strict {
4324            self.eval_scope.replace(BTreeMap::new())
4325        } else {
4326            None
4327        };
4328        // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4329        // in global scope, where `arguments` means whatever the global object says — which
4330        // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4331        // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4332        // answer the array instead.
4333        let previous_arguments = if direct {
4334            self.eval_arguments.replace(arguments)
4335        } else {
4336            None
4337        };
4338        let previous_with = self.eval_with.replace(self.with_objects());
4339        let inherited_new_target = self
4340            .frames
4341            .iter()
4342            .rev()
4343            .find(|frame| !frame.code.code.is_arrow)
4344            .map(|frame| frame.new_target.clone());
4345        let previous_new_target = self
4346            .eval_new_target
4347            .replace(inherited_new_target.unwrap_or(Value::Undefined));
4348        let eval_cells = self.eval_cells_for(&bindings);
4349        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4350        // A sloppy direct eval declares its `var`s in the caller's variable environment;
4351        // `declare_eval_local` needs to know which frame that is.
4352        // An indirect eval gets the global environment, so nothing of the caller's is
4353        // recorded as the place its `var`s belong.
4354        let previous_caller = self
4355            .eval_caller
4356            .replace(if direct { env_index } else { None });
4357        // The cell-based view of the same bindings, which is what a closure created
4358        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4359        // whose compiler did not put a binding in a cell simply does not appear here —
4360        // reads and writes still work through `eval_bindings`, they just cannot outlive
4361        // the eval.
4362        let previous_eval_scope = self
4363            .active_eval_scope
4364            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4365        let compiled = Gc::new(self.heap, CompiledCode::new(code));
4366        let closure_vars = compiled.code.closure_vars.clone();
4367        // Declaration instantiation is where this belongs: the check needs the caller frame
4368        // (recorded just above) and the eval's own var names, and it raises before any of
4369        // the eval's code runs.
4370        self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4371        let env = self.global_env(&closure_vars);
4372        let callee = Value::Undefined;
4373        // An async body does not run here: it becomes a coroutine and answers a promise,
4374        // which is what makes `await` legal in it. `this` still has to be the caller's
4375        // (for a global eval, the global object), because `this` is not part of `await`.
4376        let result = if compiled.code.kind.is_async() {
4377            self.run_async_body(compiled, env, this)
4378        } else {
4379            self.execute(compiled, env, this, Vec::new(), callee)
4380        };
4381        self.eval_scope = previous_scope;
4382        self.eval_arguments = previous_arguments;
4383        self.eval_with = previous_with;
4384        self.eval_new_target = previous_new_target;
4385        self.eval_bindings = previous_bindings;
4386        self.eval_caller = previous_caller;
4387        self.active_eval_scope = previous_eval_scope;
4388        result
4389    }
4390
4391    /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4392    /// rather than bindings.
4393    ///
4394    /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4395    /// declaration that cannot exist:
4396    ///
4397    /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4398    ///   parameter expressions a separate parameter environment, and `arguments` is bound
4399    ///   implicitly there, so a `var` of that name collides. An arrow that binds no
4400    ///   `arguments` of its own has nothing to collide with and is allowed — see the table in
4401    ///   [`Interp::check_eval_var_named_arguments`].
4402    /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4403    ///   false; the operation is a `TypeError`, and `eval("var x")` with
4404    ///   `Object.preventExtensions(this)` must raise rather than quietly do nothing
4405    ///   (`non-definable-global-var` and its four siblings).
4406    fn check_eval_var_named_arguments(
4407        &self,
4408        closure_vars: &[js_compile::bytecode::ClosureVar],
4409        strict: bool,
4410    ) -> JsResult<()> {
4411        if strict {
4412            return Ok(());
4413        }
4414        // A `var` this eval would declare on the global object, where there is no room for it.
4415        let global = &self.realm.global;
4416        if !global.is_extensible() {
4417            for var in closure_vars {
4418                if var.is_lexical || var.name == "*default*" {
4419                    continue;
4420                }
4421                let declare = matches!(
4422                    var.closure_type,
4423                    js_compile::bytecode::ClosureType::GlobalDecl
4424                );
4425                if declare && global.own_property(&var.name).is_none() {
4426                    return Err(Signal::Throw(self.make_error(
4427                        "TypeError",
4428                        "cannot declare a global in a non-extensible global object",
4429                    )));
4430                }
4431            }
4432        }
4433        // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4434        // global environment, where `var arguments` is an ordinary global.
4435        let Some(caller) = self.eval_caller.flatten() else {
4436            return Ok(());
4437        };
4438        // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4439        // environment* already binds is a `SyntaxError`. While a default expression is being
4440        // evaluated that environment is the **parameter** scope, so
4441        // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4442        // the eval would otherwise declare into an environment that is about to be copied
4443        // into the body. A *different* name is fine, and so is the same name in a function
4444        // with a simple parameter list, where there is no separate parameter environment and
4445        // the `var` belongs to the function's own.
4446        //
4447        // The names come from `args`, which is exactly the plain-identifier parameters. A
4448        // pattern parameter's bindings are also in that scope but are not recoverable from
4449        // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4450        // narrower than the one this closes and needs the parameter scope published in the
4451        // compiled function to fix.
4452        if self.in_parameter_list_at(caller) {
4453            let parameter_names: Vec<String> = self
4454                .frames
4455                .get(caller)
4456                .map(|frame| {
4457                    frame
4458                        .code
4459                        .code
4460                        .args
4461                        .iter()
4462                        .map(|arg| arg.name.clone())
4463                        .collect()
4464                })
4465                .unwrap_or_default();
4466            let collides = closure_vars.iter().any(|var| {
4467                !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4468            });
4469            if collides {
4470                return Err(Signal::Throw(self.make_error(
4471                    "SyntaxError",
4472                    "eval declares a var that the parameter scope already binds",
4473                )));
4474            }
4475        }
4476        if !closure_vars
4477            .iter()
4478            .any(|var| var.name == "arguments" && !var.is_lexical)
4479        {
4480            return Ok(());
4481        }
4482        // The body of a function is a different environment from its parameter list, and only
4483        // the parameter list is separate from `arguments`.
4484        if !self.in_parameter_list_at(caller) {
4485            return Ok(());
4486        }
4487        let caller_is_arrow = self
4488            .frames
4489            .get(caller)
4490            .is_some_and(|frame| frame.code.code.is_arrow);
4491        // A *parameter* named `arguments`, not merely a binding of that name: a body
4492        // `let arguments` is in the body's environment, which is the one that is separate and
4493        // therefore cannot collide. The slot tells them apart — an argument lives in
4494        // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4495        let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4496            binding.frame == caller
4497                && binding.name == "arguments"
4498                && matches!(binding.slot, EvalSlot::Arg)
4499        });
4500        if caller_is_arrow && !parameter_scope_binds_arguments {
4501            return Ok(());
4502        }
4503        Err(Signal::Throw(self.make_error(
4504            "SyntaxError",
4505            "eval declares 'arguments' in a function's parameter scope",
4506        )))
4507    }
4508
4509    /// The cell-backed subset of `bindings`, in the same priority order.
4510    ///
4511    /// Both lookup routes have to agree — the eval's own reads go through
4512    /// [`Interp::eval_binding_value`] and the closures it builds go through
4513    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4514    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4515    /// is not in a cell simply does not appear: reads and writes still work, they just
4516    /// cannot be handed to a closure that outlives the eval.
4517    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4518        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4519        for binding in bindings {
4520            let Some(frame) = self.frames.get(binding.frame) else {
4521                continue;
4522            };
4523            let cell = match binding.slot {
4524                EvalSlot::Arg => frame
4525                    .code
4526                    .arg_cell
4527                    .get(binding.index)
4528                    .copied()
4529                    .unwrap_or(-1),
4530                EvalSlot::Local => frame
4531                    .code
4532                    .loc_cell
4533                    .get(binding.index)
4534                    .copied()
4535                    .unwrap_or(-1),
4536            };
4537            if cell < 0 {
4538                continue;
4539            }
4540            if let Some(cell) = frame.cells.get(cell as usize) {
4541                names.push((binding.name.clone(), cell.clone()));
4542            }
4543        }
4544        names
4545    }
4546
4547    /// A `SyntaxError` that reports where in the source it happened.
4548    ///
4549    /// Compile-time failures never run, so they have no frame of their own; the
4550    /// reference still puts the position first in the trace, with no function name and
4551    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4552    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4553    /// reference borrows), which is how a script reads the position without parsing
4554    /// the trace.
4555    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4556    ///
4557    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4558    /// `columnNumber`, which is how the reference prints one. A positionless error
4559    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4560    /// the reference raises it from `js_resolve_module`, where there is no position.
4561    pub(crate) fn syntax_error_plain(
4562        &mut self,
4563        error: &js_parse::SyntaxError,
4564        file: &str,
4565    ) -> Value {
4566        if error.positionless {
4567            return self.make_error("SyntaxError", &error.message);
4568        }
4569        self.syntax_error_at(
4570            file,
4571            error.span.start.line,
4572            error.span.start.column,
4573            &error.message,
4574        )
4575    }
4576
4577    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4578        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
4579        let value = self.make_error("SyntaxError", message);
4580        if let Value::Object(object) = &value {
4581            let text = self.string(blamed);
4582            // `stack` is an own data property, and the reference keeps it
4583            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4584            object.define("stack", Property::with_attributes(text, true, false));
4585            let name = self.string(file);
4586            object.define("fileName", Property::with_attributes(name, true, true));
4587            object.define(
4588                "lineNumber",
4589                Property::with_attributes(Value::Int(line as i32), true, true),
4590            );
4591            object.define(
4592                "columnNumber",
4593                Property::with_attributes(Value::Int(column as i32), true, true),
4594            );
4595        }
4596        value
4597    }
4598
4599    /// Run a compiled script whose completion value is a function, returning it.
4600    ///
4601    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4602    /// get the closure out, which keeps the constant-pool plumbing in one place.
4603    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4604        self.run_script(code)
4605    }
4606
4607    /// The environment of a script or of any function compiled at global scope:
4608    /// every entry is a global binding, so each one resolves to the realm's cell.
4609    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4610        let mut cells = Vec::with_capacity(closure_vars.len());
4611        for closure_var in closure_vars {
4612            let cell = match closure_var.closure_type {
4613                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4614                    if closure_var.is_lexical =>
4615                {
4616                    // A lexical declaration: the cell is created here holding the
4617                    // dead-zone marker, which is what makes the binding exist and
4618                    // unreadable before its initialiser runs.
4619                    self.declare_global(&closure_var.name, closure_var.is_const);
4620                    self.realm.globals[&closure_var.name].clone()
4621                }
4622                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4623                    // A `var` or function declaration becomes a property of the global
4624                    // object, and it exists from here on — which is why
4625                    // `print(v); var v = 1` prints `undefined` instead of raising.
4626                    // Declaring it at instantiation time (rather than at the
4627                    // initialiser) is also what makes it non-configurable: the store
4628                    // then lands on an existing property instead of creating one.
4629                    self.declare_var_global(&closure_var.name);
4630                    // The cell is a placeholder that nothing indexes; it cannot be
4631                    // omitted because the slot has to hold something.
4632                    self.new_cell(Value::Undefined)
4633                }
4634                _ => {
4635                    // An undeclared global is read by name; the cell is a
4636                    // placeholder that nothing indexes.
4637                    self.new_cell(Value::Undefined)
4638                }
4639            };
4640            cells.push(cell);
4641        }
4642        Gc::new(
4643            self.heap,
4644            ClosureEnv {
4645                cells,
4646                eval_scope: None,
4647                local_vars: None,
4648                local_phase: 1,
4649            },
4650        )
4651    }
4652
4653    /// Push a frame and run until it returns.
4654    pub(crate) fn execute(
4655        &mut self,
4656        code: Gc<CompiledCode>,
4657        env: Gc<ClosureEnv>,
4658        this: Value,
4659        args: Vec<Value>,
4660        callee: Value,
4661    ) -> JsResult<Value> {
4662        let depth = self.frames.len();
4663        if depth == 0 {
4664            // A throw that reached the host ends the *active* mode: the next one is catchable
4665            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4666            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4667            // for the throw that evaluation will raise.
4668            self.uncatchable = false;
4669        }
4670        self.push_frame(code, env, this, args, callee)?;
4671        loop {
4672            // The fast loop first: it runs whole runs of records with `pc` in a register.
4673            //
4674            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4675            // reads it again — a store, a load and two bounds checks that a loop body does
4676            // not need, because nothing outside the loop can run in between. This is the
4677            // classic split: advance a register, and only spill it when leaving.
4678            //
4679            // `Some(value)` means the function ended by running off the end of its
4680            // instruction array, which is a normal return.
4681            let step = match self.run_fast() {
4682                Ok(Some(value)) => Ok(Step::Return(value)),
4683                Ok(None) => self.step(),
4684                Err(signal) => Err(signal),
4685            };
4686            match step {
4687                Ok(Step::Continue) => {}
4688                Ok(Step::Return(value)) => {
4689                    self.pop_frame();
4690                    // A frame that ended in a `tail_call` hands its value straight to
4691                    // its caller: nothing after the call can run, so every frame above
4692                    // the callee unwinds with the same value. See [`Frame::tail`] —
4693                    // the reference does not reuse frames either, so recursion depth
4694                    // and the stack-overflow limit behave the same way.
4695                    while self.frames.len() > depth && self.frame().tail {
4696                        self.pop_frame();
4697                    }
4698                    if self.frames.len() == depth {
4699                        return Ok(value);
4700                    }
4701                    // The caller resumes with the value on its stack.
4702                    self.frames
4703                        .last_mut()
4704                        .expect("a caller is live")
4705                        .stack
4706                        .push(value);
4707                }
4708                Err(Signal::Throw(value)) => {
4709                    // The host's standing request becomes the active mode for this unwind,
4710                    // and is consumed here so it does not leak into the next throw.
4711                    if self.uncatchable_next {
4712                        self.uncatchable_next = false;
4713                        self.uncatchable = true;
4714                    }
4715                    // An uncatchable throw walks past every `catch` on the way out. The
4716                    // frames are still popped, because the values they hold have to be
4717                    // dropped — only the search for a handler is skipped.
4718                    if self.uncatchable {
4719                        while self.frames.len() > depth {
4720                            self.frames.pop();
4721                        }
4722                        return Err(Signal::Throw(value));
4723                    }
4724                    // A handler lives on the stack of the frame that is throwing —
4725                    // `catch` pushed it there — so this frame gets the first chance
4726                    // to catch before it is popped.
4727                    let mut value = value;
4728                    loop {
4729                        if self.frames.len() <= depth {
4730                            return Err(Signal::Throw(value));
4731                        }
4732                        if self.catch_here(&mut value).is_some() {
4733                            break;
4734                        }
4735                        self.frames.pop();
4736                    }
4737                }
4738                // A `yield` in a frame that `execute` is running directly means a
4739                // generator body was entered as an ordinary call, which only happens if
4740                // the generator check in `call_or_push` was bypassed.
4741                Ok(Step::Suspend(_)) => {
4742                    return Err(Signal::Throw(self.make_error(
4743                        "InternalError",
4744                        "a generator body ran as an ordinary call",
4745                    )));
4746                }
4747                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4748            }
4749        }
4750    }
4751
4752    /// Install a handler for `value` if this frame has one, resuming at it.
4753    ///
4754    /// The scan is the reference's: walk the frame's stack downwards looking for the
4755    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4756    /// enumerator marker rather than a handler — `for of` keeps one under its record so
4757    /// that `break` and `return` can find the iterator — and an exception reaching one
4758    /// **closes that iterator** before the unwinding continues.
4759    ///
4760    /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4761    /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4762    /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4763    /// close the iterator while the reference to store into is being worked out.
4764    ///
4765    /// `value` is `&mut` because closing the iterator may replace it: see
4766    /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4767    fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4768        loop {
4769            // Popped one at a time so no frame borrow is held across the close below.
4770            let top = self.frames.last_mut()?.stack.pop()?;
4771            let Value::CatchOffset(offset) = top else {
4772                continue;
4773            };
4774            if offset != 0 {
4775                let frame = self.frames.last_mut().expect("the frame was just read");
4776                frame.stack.push(value.clone());
4777                frame.pc = offset as usize;
4778                return Some(());
4779            }
4780            // The record's `iter` and `next` sit directly below the marker.
4781            let close = {
4782                let frame = self.frames.last_mut().expect("the frame was just read");
4783                let next = frame.stack.pop();
4784                let iterator = frame.stack.pop();
4785                match (iterator, next) {
4786                    (Some(iterator), Some(_next)) => Some(iterator),
4787                    // A malformed record cannot be closed, but unwinding still has to go
4788                    // on: this is not a handler, so there is nothing to resume at.
4789                    _ => None,
4790                }
4791            };
4792            if let Some(iterator) = close {
4793                self.close_iterator_on_throw(iterator);
4794            }
4795        }
4796    }
4797
4798    /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4799    ///
4800    /// Two things differ from the ordinary close, both from the spec's step ordering:
4801    ///
4802    /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4803    ///   return ? completion`) comes before step 5, so an exception raised by `return()`
4804    ///   itself — or by reading it — is discarded;
4805    /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4806    ///
4807    /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4808    /// it saves the pending exception, clears the slot, and re-throws the saved one from
4809    /// `done:` no matter what happened in between.
4810    fn close_iterator_on_throw(&mut self, iterator: Value) {
4811        if matches!(iterator, Value::Undefined) {
4812            return;
4813        }
4814        let Ok(method) = self.read_field(&iterator, "return") else {
4815            return;
4816        };
4817        if matches!(method, Value::Undefined | Value::Null) {
4818            return;
4819        }
4820        // A throw from `return()` replaces nothing: the exception already being unwound is
4821        // the one that propagates.
4822        let _ = self.call_value(method, iterator, Vec::new());
4823    }
4824
4825    fn push_frame(
4826        &mut self,
4827        code: Gc<CompiledCode>,
4828        env: Gc<ClosureEnv>,
4829        this: Value,
4830        mut args: Vec<Value>,
4831        callee: Value,
4832    ) -> JsResult<()> {
4833        // Two bounds, and the byte budget is the one that decides in practice. The
4834        // reference's message is `stack overflow` on an `InternalError`, not V8's
4835        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4836        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4837        let frame_cost = Self::frame_cost(&code);
4838        let stack_base = self.stack_used();
4839        if self.frames.len() >= self.max_frames
4840            || stack_base.saturating_add(frame_cost) > self.stack_limit
4841        {
4842            return Err(Signal::Throw(
4843                self.make_error("InternalError", "stack overflow"),
4844            ));
4845        }
4846        let arg_count = code.code.args.len();
4847        // How many were actually passed, which `arguments.length` reports and
4848        // `assert(x)` depends on: a call with one argument must not look like a call
4849        // with one argument and an explicit `undefined`.
4850        let passed = args.len();
4851        // Missing arguments are `undefined` in their slots; extra ones are dropped
4852        // from the slots but still reachable through `arguments`.
4853        //
4854        // A call that passes no more than the declared parameters needs **no** copy:
4855        // after the resize below, `args[..passed]` *is* the passed values. Only the
4856        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4857        // the rare case. This used to copy every call: one `Value` clone per argument
4858        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4859        let passed_overflow = (passed > arg_count).then(|| {
4860            let mut values = self.take_values(passed, Value::Undefined);
4861            values[..passed].clone_from_slice(&args[..passed]);
4862            values
4863        });
4864        // Only when the counts differ, which for the overwhelmingly common call — as many
4865        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4866        // lengths is two length compares and nothing else, but this is the hottest few
4867        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4868        if passed != arg_count {
4869            args.resize(arg_count, Value::Undefined);
4870            args.truncate(arg_count);
4871        }
4872        let cell_count = code.code.var_ref_count as usize;
4873        let mut cells = Vec::with_capacity(cell_count);
4874        for _ in 0..cell_count {
4875            cells.push(self.new_cell(Value::Undefined));
4876        }
4877        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4878        // A captured argument lives in its cell, not in the argument slot, so the
4879        // incoming value has to be moved there before the body runs.
4880        for (slot, cell) in code.arg_cell.iter().enumerate() {
4881            if *cell >= 0
4882                && let Some(value) = args.get(slot).cloned()
4883            {
4884                cells[*cell as usize].set(value);
4885            }
4886        }
4887        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4888        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4889        // reports `object`. Strict mode passes the value through untouched.
4890        let this = if code.code.strict {
4891            this
4892        } else if this.is_nullish() {
4893            Value::Object(self.realm.global.clone())
4894        } else if matches!(this, Value::Object(_)) {
4895            this
4896        } else {
4897            match crate::builtins::this_object(self, &this) {
4898                Ok(boxed) => Value::Object(boxed),
4899                Err(_) => this,
4900            }
4901        };
4902        let stack_depth = code.code.stack_size as usize + 1;
4903        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4904        // out of the same recycle pool the locals did.
4905        let stack = self.take_values(stack_depth, Value::Undefined);
4906        self.frames.push(Frame {
4907            code,
4908            env,
4909            this,
4910            args,
4911            passed_count: passed,
4912            passed_overflow: passed_overflow.map(Box::new),
4913            locals,
4914            cells,
4915            local_vars: None,
4916            // Exactly the depth the compiler computed, so the operand stack never
4917            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4918            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4919            // the buffer between calls, so "exactly" costs nothing after the first one.
4920            stack,
4921            pc: 0,
4922            at: 0,
4923            callee,
4924            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4925            cost: frame_cost,
4926            stack_base,
4927            tail: false,
4928        });
4929        Ok(())
4930    }
4931
4932    /// A value buffer of `len` slots, from the recycle pool when there is one.
4933    ///
4934    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4935    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4936        // A frame with no locals asks for nothing, and that is most frames: taking a
4937        // buffer out of the pool, clearing it and resizing it to zero is four operations
4938        // and a pool pop for an empty `Vec`, which is free to construct.
4939        if len == 0 {
4940            return Vec::new();
4941        }
4942        let mut buffer = self.free_values.pop().unwrap_or_default();
4943        buffer.clear();
4944        buffer.resize(len, fill);
4945        buffer
4946    }
4947
4948    /// Return a finished frame's value buffers for the next call to reuse.
4949    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4950        for mut buffer in [
4951            std::mem::take(&mut frame.locals),
4952            frame
4953                .passed_overflow
4954                .take()
4955                .map(|buffer| *buffer)
4956                .unwrap_or_default(),
4957            std::mem::take(&mut frame.stack),
4958        ] {
4959            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4960            // GC root: it kept every value the frame held reachable, which is invisible
4961            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4962            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4963            // exactly that within one run — the target `{}` of a finished IIFE was still
4964            // in its operand stack, in the pool.
4965            buffer.clear();
4966            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4967            // fill the pool with nothing to offer.
4968            if free_values.len() < RECYCLE_SLOTS
4969                && buffer.capacity() > 0
4970                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4971            {
4972                free_values.push(buffer);
4973            }
4974        }
4975    }
4976
4977    /// Pop a finished frame and keep its buffers.
4978    ///
4979    /// Every place that drops a frame goes through here: a recycled buffer is also where
4980    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4981    /// nothing but the reuse.
4982    fn pop_frame(&mut self) -> Option<()> {
4983        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4984        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4985        let last = self.frames.len().checked_sub(1)?;
4986        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4987        self.frames.truncate(last);
4988        Some(())
4989    }
4990
4991    /// Poll the host's interrupt handler, if one is installed.
4992    ///
4993    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4994    /// one `Option` test, and with no handler installed the whole function is that test —
4995    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4996    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4997    #[inline]
4998    fn check_interrupt(&mut self) -> JsResult<()> {
4999        if self.interrupt.is_none() {
5000            return Ok(());
5001        }
5002        if self.interrupt_counter > 0 {
5003            self.interrupt_counter -= 1;
5004            return Ok(());
5005        }
5006        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5007        // The closure is taken out for the duration so that a handler which re-enters the
5008        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5009        let mut handler = self.interrupt.take().expect("checked above");
5010        let abort = handler();
5011        self.interrupt = Some(handler);
5012        if abort {
5013            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5014            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5015            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5016            // documentation says.
5017            self.uncatchable = true;
5018            return Err(Signal::Throw(
5019                self.make_error("InternalError", "interrupted"),
5020            ));
5021        }
5022        Ok(())
5023    }
5024
5025    /// A memory checkpoint: does the heap still fit under its limit?
5026    ///
5027    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5028    /// a `Cell` read and a predictable branch, and the point of asking that often is that
5029    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5030    /// only at calls would let it run until the machine died, which is the exact failure
5031    /// `--memory-limit` exists to prevent.
5032    ///
5033    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5034    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5035    /// script that catches it, drops the reference and carries on is legitimate: measured
5036    /// on `qjs --memory-limit 1M`, the engine recovers.
5037    fn check_memory(&mut self) -> JsResult<()> {
5038        // One `Cell` read and a predictable branch when no limit is set, and an integer
5039        // compare when one is. Containers report their own growth as it happens
5040        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5041        // walking it here was the first version and it was O(live) per 256 instructions,
5042        // which turned a 100k-element push loop into a five-minute one.
5043        let Some(limit) = self.heap.memory_limit() else {
5044            return Ok(());
5045        };
5046        let used = self.heap.used_bytes();
5047        if used <= limit {
5048            // Back under the limit — a collection or a dropped reference did it. The next
5049            // time it goes over is a new failure, not a repeat of this one.
5050            self.oom_reported_at = 0;
5051            return Ok(());
5052        }
5053        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5054        // block runs normally after `out of memory` — it allocates nothing, so nothing
5055        // fails. A check that re-fired on every instruction made the handler itself throw,
5056        // which is a dead end: the error became unobservable from script.
5057        //
5058        // Comparing against the total at the last report gives the same behaviour: the
5059        // handler runs while the total is unchanged, and the very next allocation over the
5060        // limit fails.
5061        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5062        {
5063            return Ok(());
5064        }
5065        self.oom_reported_at = used;
5066        Err(Signal::Throw(
5067            self.make_error("InternalError", "out of memory"),
5068        ))
5069    }
5070
5071    /// Fail before allocating `payload` bytes, if they would not fit.
5072    ///
5073    /// For the allocations whose size comes from script data — `new Array(n)`,
5074    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5075    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5076    /// answering NULL for the one big request.
5077    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5078        if self.heap.fits(payload) {
5079            return Ok(());
5080        }
5081        Err(Signal::Throw(
5082            self.make_error("InternalError", "out of memory"),
5083        ))
5084    }
5085
5086    /// Bytes of frame state the live call chain accounts for.
5087    pub fn stack_used(&self) -> usize {
5088        match self.frames.last() {
5089            Some(frame) => frame.stack_base + frame.cost,
5090            None => 0,
5091        }
5092    }
5093
5094    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5095    ///
5096    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5097    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5098    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5099    /// instead. That is the whole difference between the two models: it rations C stack, we
5100    /// ration frame state, and both quantities are dominated by the value slots — which is
5101    /// why the two depths come out comparable rather than merely proportional.
5102    fn frame_cost(code: &CompiledCode) -> usize {
5103        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5104        std::mem::size_of::<Frame>()
5105            + std::mem::size_of::<Value>() * slots
5106            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5107    }
5108
5109    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5110    ///
5111    /// Only names the eval created are here: a name the frame already declared statically
5112    /// is written through to its own slot instead, so this cannot shadow a real local.
5113    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5114        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5115        let (local_vars, phase) = self.visible_local_vars()?;
5116        if !local_vars.contains(name) {
5117            return None;
5118        }
5119        local_vars.get(name, phase)
5120    }
5121
5122    /// The variables a direct `eval` declared, as the code currently running sees them.
5123    ///
5124    /// Inside an eval that is the *caller's* set — the eval's own variable environment
5125    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5126    /// else it is the current frame's, falling back to the frame the closure was created
5127    /// in.
5128    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5129    ///
5130    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5131    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5132    /// refcount operations (the clone out of the frame, the drop at the end of the match)
5133    /// just to be asked `is_none`.
5134    fn has_visible_local_vars(&self) -> bool {
5135        let index = match self.eval_caller.flatten() {
5136            Some(caller) => caller,
5137            None => match self.frames.len().checked_sub(1) {
5138                Some(top) => top,
5139                None => return false,
5140            },
5141        };
5142        match self.frames.get(index) {
5143            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5144            None => false,
5145        }
5146    }
5147
5148    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5149        // While an `eval` runs, its own frame is on top but its variable environment is
5150        // the *caller's* — so the caller is what the lookup has to start from.
5151        let (index, phase) = match self.eval_caller.flatten() {
5152            Some(caller) => (
5153                caller,
5154                if self.in_parameter_list_at(caller) {
5155                    0
5156                } else {
5157                    1
5158                },
5159            ),
5160            None => (
5161                self.frames.len().checked_sub(1)?,
5162                if self.in_parameter_list() { 0 } else { 1 },
5163            ),
5164        };
5165        let frame = self.frames.get(index)?;
5166        // The frame's own variables, or — for an arrow, which has no variable environment
5167        // of its own — the one it was created in, which `ClosureEnv` carries.
5168        if let Some(local_vars) = frame.local_vars.clone() {
5169            return Some((local_vars, phase));
5170        }
5171        frame
5172            .env
5173            .local_vars
5174            .clone()
5175            .map(|local_vars| (local_vars, frame.env.local_phase))
5176    }
5177
5178    /// Whether the innermost frame is still evaluating its parameter list.
5179    ///
5180    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5181    /// and a closure created there may only see that much of [`LocalVars`].
5182    fn in_parameter_list(&self) -> bool {
5183        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5184    }
5185
5186    /// [`Interp::in_parameter_list`] for a specific frame.
5187    fn in_parameter_list_at(&self, frame: usize) -> bool {
5188        let Some(frame) = self.frames.get(frame) else {
5189            return false;
5190        };
5191        let code = &frame.code.code;
5192        if !code.has_parameter_expressions {
5193            return false;
5194        }
5195        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5196        // function as its body and let a direct `eval` act accordingly.
5197        if code.body_start == (0, 0) {
5198            return false;
5199        }
5200        match code.position_at(frame.at as u32) {
5201            Some(position) => position < code.body_start,
5202            None => false,
5203        }
5204    }
5205
5206    fn frame(&self) -> &Frame {
5207        self.frames.last().expect("a frame is live")
5208    }
5209
5210    fn frame_mut(&mut self) -> &mut Frame {
5211        self.frames.last_mut().expect("a frame is live")
5212    }
5213
5214    // -- slot access --------------------------------------------------------
5215
5216    /// Move a local's value out, leaving `undefined` in the slot.
5217    ///
5218    /// `None` for a captured slot: its value lives in a cell shared with every closure
5219    /// that closed over it, so it can never be exclusively ours and must not be taken.
5220    ///
5221    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5222    /// for every read and fatal for this one — a clone is exactly the second handle that
5223    /// rules out growing the string in place.
5224    fn take_loc(&mut self, slot: usize) -> Option<Value> {
5225        let frame = self.frames.last_mut()?;
5226        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5227            return None;
5228        }
5229        frame
5230            .locals
5231            .get_mut(slot)
5232            .map(|value| std::mem::replace(value, Value::Undefined))
5233    }
5234
5235    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5236    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5237    ///
5238    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5239    /// it** — the value is put back before the general path runs — so a `valueOf` that
5240    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5241    /// error as it would have without the fusion. This is why the in-place attempt is a
5242    /// `take` and not a `get`: an optimisation that changes what an exception observes is
5243    /// a wrong answer with a good excuse.
5244    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5245        // The take is `matches!`-guarded on the *right* operand only, and the taken value
5246        // is put back on every path that does not append. An earlier version wrote the two
5247        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5248        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5249        // through with its value already taken and dropped: the general path below then
5250        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5251        // A wrong answer, from an optimisation, with every test green.
5252        if matches!(right, Value::String(_))
5253            && let Some(taken) = self.take_loc(slot)
5254        {
5255            if let Value::String(mut left) = taken {
5256                let appended = match left.get_mut() {
5257                    Some(string) => string.append_in_place(
5258                        // The pattern is the one `matches!` just checked.
5259                        match &right {
5260                            Value::String(text) => text,
5261                            _ => unreachable!("guarded above"),
5262                        },
5263                    ),
5264                    None => None,
5265                };
5266                self.put_loc(slot, Value::String(left));
5267                if let Some(added) = appended {
5268                    // The buffer grew where it stood, so the heap's running total has to
5269                    // be told: `measure_used` would report the new length, and the two must
5270                    // agree or the subtraction at free time leaves the counter wrong.
5271                    self.heap.adjust_payload(added as isize);
5272                    return Ok(());
5273                }
5274            } else {
5275                self.put_loc(slot, taken);
5276            }
5277        }
5278        // The two-number case, without an operand stack round trip. Everything below
5279        // this point is the *general* path: push both, call `binary_add`, pop the answer,
5280        // store it — five operations and two `Value` clones for what is one integer add.
5281        // `AddImmLoc` already answers this shape that way; the fusion above it was written
5282        // for string append and never got the numeric half, so `t += i` — a counting loop
5283        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5284        let left = self.get_loc(slot);
5285        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5286            self.put_loc(
5287                slot,
5288                match a.checked_add(*b) {
5289                    Some(sum) => Value::Int(sum),
5290                    None => Value::Float(*a as f64 + *b as f64),
5291                },
5292            );
5293            return Ok(());
5294        }
5295        self.push(left);
5296        self.push(right);
5297        self.binary_add()?;
5298        let value = self.pop();
5299        self.put_loc(slot, value);
5300        Ok(())
5301    }
5302
5303    fn get_arg(&self, slot: usize) -> Value {
5304        self.frame().read_arg(slot)
5305    }
5306
5307    fn put_arg(&mut self, slot: usize, value: Value) {
5308        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5309        if cell == -1 {
5310            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5311                *slot = value;
5312            }
5313        } else {
5314            self.frame().cells[cell as usize].set(value);
5315        }
5316    }
5317
5318    fn get_loc(&self, slot: usize) -> Value {
5319        // The cell mapping is `-1` for every slot that was not captured — which is all of
5320        // them in a function that creates no closure. `Frame::read_loc` tests that first,
5321        // so the common case is one array read and a clone: 20% of every loop iteration
5322        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5323        // sample of `dispatch:arith`).
5324        self.frame().read_loc(slot)
5325    }
5326
5327    fn put_loc(&mut self, slot: usize, value: Value) {
5328        // One borrow instead of three, and the cell check on the frame we already hold.
5329        let frame = self.frames.last_mut().expect("a frame is live");
5330        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5331        if cell < 0 {
5332            if let Some(slot) = frame.locals.get_mut(slot) {
5333                *slot = value;
5334            }
5335        } else if let Some(cell) = frame.cells.get(cell as usize) {
5336            cell.set(value);
5337        }
5338    }
5339
5340    // -- globals ------------------------------------------------------------
5341
5342    /// The name a global-slot operand refers to.
5343    fn global_name(&self, slot: usize) -> String {
5344        self.frame()
5345            .code
5346            .code
5347            .closure_vars
5348            .get(slot)
5349            .map(|c| c.name.clone())
5350            .unwrap_or_default()
5351    }
5352
5353    /// The facts about a global binding that decide where it lives.
5354    ///
5355    /// A script's globals split in two, and the split is observable: `var` and
5356    /// function declarations become properties of the global object (`globalThis.v`
5357    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5358    /// declarations live in the global *lexical* environment and are invisible there
5359    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5360    /// `is_lexical` flag means the answer is already in the bytecode.
5361    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5362        let name = self.global_name(slot);
5363        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5364        // while forwarding a reference through a nested function is built with the
5365        // flags cleared, so `const c` would look like an ordinary `var` from inside a
5366        // closure. Presence in the realm's lexical table is the same fact, recorded
5367        // once, and every slot sees it.
5368        let lexical = self.realm.globals.contains_key(&name);
5369        let is_const = self.realm.lexical_consts.contains(&name);
5370        (name, lexical, is_const)
5371    }
5372
5373    /// The value of `name` in the innermost active `with` object, if any.
5374    ///
5375    /// The active objects are the [`VarKind::With`] locals of every frame still running,
5376    /// innermost frame first and innermost block first within one. Walking frames rather
5377    /// than keeping a separate stack is what makes a closure called from inside a `with`
5378    /// see it, and what keeps the object alive only as long as the block is.
5379    /// The innermost active `with` object that has `name`, if any.
5380    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5381        let objects = self.eval_with.clone().unwrap_or_default();
5382        for object in objects {
5383            let key = self.string(name.to_string());
5384            if self
5385                .has_property(&key, &Value::Object(object.clone()))
5386                .ok()?
5387            {
5388                return Some(object);
5389            }
5390        }
5391        None
5392    }
5393
5394    /// Every active `with` object, innermost first.
5395    fn with_objects(&self) -> Vec<Gc<JsObject>> {
5396        let mut objects = Vec::new();
5397        for frame in self.frames.iter().rev() {
5398            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5399                if var.kind != js_compile::VarKind::With {
5400                    continue;
5401                }
5402                // A captured binding lives in its cell and not in the slot list, so the
5403                // cell is consulted first — a closure created inside the block is exactly
5404                // what makes the object captured. Before the store runs the slot still
5405                // holds `undefined`, and a `with` object is always boxed, so a non-object
5406                // entry is simply not in scope yet.
5407                let value = frame
5408                    .code
5409                    .loc_cell
5410                    .get(index)
5411                    .copied()
5412                    .filter(|cell| *cell >= 0)
5413                    .and_then(|cell| frame.cells.get(cell as usize))
5414                    .map(|cell| cell.get())
5415                    .or_else(|| frame.locals.get(index).cloned());
5416                if let Some(Value::Object(object)) = value {
5417                    objects.push(object);
5418                }
5419            }
5420        }
5421        objects
5422    }
5423
5424    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5425        for object in self.eval_with.clone().unwrap_or_default() {
5426            let key = self.string(name.to_string());
5427            if self.has_property(&key, &Value::Object(object.clone()))? {
5428                return Ok(Some(self.read_field(&Value::Object(object), name)?));
5429            }
5430        }
5431        Ok(None)
5432    }
5433
5434    /// Whether every scope between here and the global object is an ordinary one.
5435    ///
5436    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5437    /// bytecode resolved; when any is live the general path has to run in full order. When
5438    /// none is — every ordinary program — a global read is a property read and nothing
5439    /// else, and that is worth caching.
5440    fn scopes_are_plain(&self) -> bool {
5441        self.eval_caller.is_none()
5442            && self.eval_with.is_none()
5443            && self.eval_arguments.is_none()
5444            && self.eval_bindings.is_empty()
5445            && self.eval_scope.is_none()
5446            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5447            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5448            // its `ClosureEnv`, so the test has to be the same one the general path makes.
5449            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5450            // upstream corpus caught and no unit test did.
5451            && !self.has_visible_local_vars()
5452            && self.frame().env.eval_scope.is_none()
5453    }
5454
5455    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5456        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5457        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5458        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5459        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5460        // borrow outlive the `&mut self` the lookup needs.
5461        //
5462        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5463        // forwarded through a nested function has its flags cleared, so the flag cannot
5464        // be believed.
5465        let code = self.frame().code.clone();
5466        let name = code
5467            .code
5468            .closure_vars
5469            .get(slot)
5470            .map(|c| c.name.as_str())
5471            .unwrap_or_default();
5472        let lexical = self.realm.globals.contains_key(name);
5473        // The common case, first: an ordinary global `var`, with a cache in front of the
5474        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5475        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5476        // cache hit and return without touching any of it.
5477        if !lexical && self.scopes_are_plain() {
5478            return self.get_plain_global(name, slot);
5479        }
5480        if name == "arguments"
5481            && let Some(arguments) = &self.eval_arguments
5482        {
5483            return Ok(arguments.clone());
5484        }
5485        // A `with` block around the *call site* is part of the scope an `eval` sees, so
5486        // the objects live when the eval started are consulted before anything else. The
5487        // snapshot is taken at entry rather than scanning the frames on every read: a
5488        // block that has already finished still leaves its object in the slot, and a
5489        // bytecode read outside the block must not see it.
5490        if let Some(value) = self.with_lookup(name)? {
5491            return Ok(value);
5492        }
5493        // A variable a direct `eval` declared shadows everything the compiler resolved,
5494        // including an enclosing function's binding: the eval put it in the caller's own
5495        // variable environment, which is nearer than any captured scope.
5496        if let Some((local_vars, phase)) = self.visible_local_vars()
5497            && let Some(cell) = local_vars.get(name, phase)
5498        {
5499            return Ok(cell.get());
5500        }
5501        // The frame that called `eval` is the innermost scope the eval'd code sees, so
5502        // its local `a` wins over a global `a`.
5503        if let Some(value) = self.eval_binding_value(name) {
5504            return Ok(value);
5505        }
5506        // A closure created by an `eval` resolves its free names against the bindings
5507        // that eval saw, even after the eval (and its frames) are gone.
5508        if let Some(cell) = self
5509            .frame()
5510            .env
5511            .eval_scope
5512            .as_ref()
5513            .and_then(|scope| scope.get(name))
5514        {
5515            let value = cell.get();
5516            if matches!(value, Value::Uninitialized) {
5517                return Err(self.throw_reference(name));
5518            }
5519            return Ok(value);
5520        }
5521        // A binding declared by the strict `eval` currently running shadows anything
5522        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5523        if let Some(scope) = &self.eval_scope
5524            && let Some(value) = scope.get(name)
5525        {
5526            return Ok(value.clone());
5527        }
5528        if lexical {
5529            // A lexical global is a binding in a side table, so the dead zone is
5530            // visible and it is nowhere on the global object.
5531            if let Some(cell) = self.realm.globals.get(name) {
5532                let value = cell.get();
5533                if matches!(value, Value::Uninitialized) {
5534                    return Err(self.throw_reference(name));
5535                }
5536                return Ok(value);
5537            }
5538            return Err(self.throw_reference(name));
5539        }
5540        // A `var` global is an ordinary property, so the prototype chain and the
5541        // global object's own builtins are all reachable through it.
5542        match self.get_property(&self.realm.global.clone(), name)? {
5543            Some(value) => Ok(value),
5544            None => Err(self.throw_reference(name)),
5545        }
5546    }
5547
5548    /// Read a plain global `var`: a cached own data property, or the full lookup.
5549    ///
5550    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5551    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5552    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5553        let object = self.realm.global.clone();
5554        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5555        if let Some(cached) = &self.global_cache[site]
5556            && object.upgrades_to(&cached.object)
5557            && let Some(value) = object.data_property_at(cached.index, name)
5558        {
5559            return Ok(value);
5560        }
5561        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5562        // chain exactly as before, then remember the answer if it is worth remembering.
5563        let Some(value) = self.get_property(&object, name)? else {
5564            return Err(self.throw_reference(name));
5565        };
5566        if let Some(index) = object.own_data_index(name) {
5567            self.global_cache[site] = Some(GlobalCache {
5568                object: object.downgrade(),
5569                index,
5570            });
5571        }
5572        Ok(value)
5573    }
5574
5575    /// Store to a global binding.
5576    ///
5577    /// Returns a signal when the store is refused: a `const` global may only be
5578    /// written by its initialiser, and a non-configurable `var` global may not be
5579    /// deleted but is always writable.
5580    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5581        let (name, lexical, is_const) = self.global_binding(slot);
5582
5583        // An assignment inside a `with` writes through to the object that supplies the
5584        // name, which for an `eval` means consulting the same chain `get_global` does.
5585        if let Some(owner) = self.with_owner(&name) {
5586            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5587            return Ok(());
5588        }
5589        // A variable the running eval *declared* takes the write before any caller
5590        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5591        // environment even when an enclosing function has a `var c` of its own.
5592        if self.eval_caller.flatten().is_some()
5593            && let Some((local_vars, phase)) = self.visible_local_vars()
5594            && local_vars.contains(&name)
5595            && let Some(cell) = local_vars.get(&name, phase)
5596        {
5597            cell.set(value);
5598            return Ok(());
5599        }
5600        // A binding of the frame that called `eval` takes the write, which is what
5601        // makes `f("a = 3")` change the caller's `a`.
5602        if self.set_eval_binding(&name, &value)? {
5603            return Ok(());
5604        }
5605        // A closure that outlived its `eval` writes through to the same cell it reads.
5606        if let Some(cell) = self
5607            .frame()
5608            .env
5609            .eval_scope
5610            .as_ref()
5611            .and_then(|scope| scope.get(&name))
5612            .cloned()
5613        {
5614            cell.set(value);
5615            return Ok(());
5616        }
5617        // Inside a strict `eval`, a name it declared itself is stored there. An
5618        // *assignment* to a name nobody declared is not a declaration, so it falls
5619        // through: strict mode raises `ReferenceError` for it, which is what
5620        // `eval("1 + (@not_def = 1)")` has to do.
5621        if let Some(scope) = self.eval_scope.as_mut()
5622            && scope.contains_key(&name)
5623        {
5624            scope.insert(name, value);
5625            return Ok(());
5626        }
5627        if lexical {
5628            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5629                // A lexical global starts out `Uninitialized` and only `init_global` ends
5630                // that, so a store reaching here is either a plain assignment to a slot
5631                // still in its dead zone — `x = 1; let x` at the top level, a
5632                // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5633                if matches!(cell.get(), Value::Uninitialized) {
5634                    return Err(self.dead_zone_global(&name));
5635                }
5636                if is_const {
5637                    return Err(self.read_only_global(&name));
5638                }
5639                cell.set(value);
5640                return Ok(());
5641            }
5642            // Writing an undeclared lexical global is a `ReferenceError` in strict
5643            // mode and a silent global creation otherwise; creating the cell here
5644            // keeps both paths from losing the value.
5645            let cell = self.new_cell(value);
5646            self.realm.globals.insert(name, cell);
5647            return Ok(());
5648        }
5649        // A variable a direct `eval` declared in this call shadows the global object, even
5650        // when the global already has a property of that name — `var c = "global"` at the
5651        // top level must not capture `eval("var c = 1")` inside a function.
5652        if let Some((local_vars, phase)) = self.visible_local_vars()
5653            && local_vars.contains(&name)
5654            && let Some(cell) = local_vars.get(&name, phase)
5655        {
5656            cell.set(value);
5657            return Ok(());
5658        }
5659        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5660        // remembered a global's slot index since M12b, but the *store* side never did: it
5661        // converted the name to a `PropertyKey` (two allocations) and then scanned the
5662        // global object's whole table — which holds every builtin — on every assignment to
5663        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5664        // full global lookup per iteration; measured with a counter, `s` as a global made
5665        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5666        //
5667        // Re-validated exactly like the read: same object, same index, still the name, and
5668        // — the one extra check a store needs — still writable. A global that is an
5669        // accessor, non-writable, or inherited fails here and falls through to the full
5670        // path below, which reports the failure the way it always did.
5671        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5672        let global = self.realm.global.clone();
5673        if let Some(cached) = &self.global_cache[site]
5674            && global.upgrades_to(&cached.object)
5675            && global.write_data_at(cached.index, &name, value.clone())
5676        {
5677            return Ok(());
5678        }
5679        match global.own_property(&name) {
5680            // A `var` global is writable, so the store goes straight through — but
5681            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5682            // store (a non-writable or accessor-without-setter global) is a silent
5683            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5684            // split every other assignment has.
5685            Some(_) => {
5686                let on_failure = if self.current_strict() {
5687                    DeleteFailure::Throw
5688                } else {
5689                    DeleteFailure::Ignore
5690                };
5691                let result = self.set_property_with(&global, &name, value, on_failure);
5692                // Teach the cache the slot for a plain writable own data property, which is
5693                // what a declared `var` is. Without this the fast path above could never
5694                // fire for a global that is only ever *written* — its entry would have to
5695                // be put there by a read of the same slot, and a write-only loop has none.
5696                if result.is_ok()
5697                    && let Some(index) = global.own_data_index(&name)
5698                {
5699                    self.global_cache[site] = Some(GlobalCache {
5700                        object: global.downgrade(),
5701                        index,
5702                    });
5703                }
5704                result
5705            }
5706            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5707            // declaration creates a *configurable* property, which is what makes it
5708            // deletable and is the one way a global differs from a declared `var`.
5709            // In strict mode the same store is a `ReferenceError` instead: that is the
5710            // whole point of strict mode, and creating the global silently meant
5711            // `"use strict"; x = 1` looked like it worked.
5712            None => {
5713                if self.current_strict() {
5714                    return Err(self.throw_reference(&name));
5715                }
5716                // A direct eval declares here rather than on the global object: its
5717                // `var`s belong to the caller's variable environment. `declare_eval_local`
5718                // also covers a plain assignment to a variable an earlier eval made.
5719                if let Some(cell) = self.declare_eval_local(&name) {
5720                    cell.set(value);
5721                    return Ok(());
5722                }
5723                global.define_data(&name, value);
5724                Ok(())
5725            }
5726        }
5727    }
5728
5729    /// The value of a binding of the frame that called `eval`, if there is one.
5730    fn eval_binding_value(&self, name: &str) -> Option<Value> {
5731        let binding = self
5732            .eval_bindings
5733            .iter()
5734            .find(|binding| binding.name == name)?;
5735        let owner = self.frames.get(binding.frame)?;
5736        let (slot, index) = (binding.slot, binding.index);
5737        Some(match slot {
5738            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5739                cell if cell >= 0 => owner
5740                    .cells
5741                    .get(cell as usize)
5742                    .map(|cell| cell.get())
5743                    .unwrap_or(Value::Undefined),
5744                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5745            },
5746            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5747                cell if cell >= 0 => owner
5748                    .cells
5749                    .get(cell as usize)
5750                    .map(|cell| cell.get())
5751                    .unwrap_or(Value::Undefined),
5752                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5753            },
5754        })
5755    }
5756
5757    /// Write to a binding of the frame that called `eval`.
5758    ///
5759    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5760    /// matched binding can still refuse the store, which is why this is fallible: a
5761    /// `const` is read-only everywhere, and a named function expression's own name is
5762    /// read-only in strict mode.
5763    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5764        let Some(binding) = self
5765            .eval_bindings
5766            .iter()
5767            .find(|binding| binding.name == name)
5768        else {
5769            return Ok(false);
5770        };
5771        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5772        let strict = self.current_strict();
5773        let Some(owner) = self.frames.get_mut(frame) else {
5774            return Ok(false);
5775        };
5776        match slot {
5777            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5778                cell if cell >= 0 => {
5779                    if let Some(cell) = owner.cells.get(cell as usize) {
5780                        cell.set(value.clone());
5781                    }
5782                }
5783                _ => {
5784                    if let Some(slot) = owner.args.get_mut(index) {
5785                        *slot = value.clone();
5786                    }
5787                }
5788            },
5789            EvalSlot::Local => {
5790                let declared = owner.code.code.vars.get(index);
5791                // A `const` is read-only even through `eval`. The realm records this for
5792                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5793                // the bytecode, so this is where it has to be enforced.
5794                if declared.is_some_and(|var| var.is_const) {
5795                    return Err(self.read_only_local(name));
5796                }
5797                // The name of a named function expression is read-only too, but only
5798                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5799                // such a name is ignored, the same as a direct store would be.
5800                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5801                    return if strict {
5802                        Err(self.read_only_local(name))
5803                    } else {
5804                        Ok(true)
5805                    };
5806                }
5807                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5808                    cell if cell >= 0 => {
5809                        if let Some(cell) = owner.cells.get(cell as usize) {
5810                            cell.set(value.clone());
5811                        }
5812                    }
5813                    _ => {
5814                        if let Some(slot) = owner.locals.get_mut(index) {
5815                            *slot = value.clone();
5816                        }
5817                    }
5818                }
5819            }
5820        }
5821        Ok(true)
5822    }
5823
5824    /// The `TypeError` an assignment to a read-only binding raises.
5825    fn read_only_local(&self, name: &str) -> Signal {
5826        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5827    }
5828
5829    /// Declare `name` as a variable of the frame that called the running `eval`.
5830    ///
5831    /// `None` when there is no direct eval in progress, or it was called from the top
5832    /// level — then the caller's variable environment *is* the global one and the
5833    /// existing path is right.
5834    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5835        let caller = self.eval_caller.flatten()?;
5836        // The bottom frame is the top-level script, whose variable environment *is* the
5837        // global one — so `eval("var x = 1")` at the top level still creates a global.
5838        if caller == 0 {
5839            return None;
5840        }
5841        // A name the eval's *own* variable environment already binds is not a new
5842        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5843        // `arguments`, and creating a second binding would leave the first — the one
5844        // closures read — untouched. A binding of an *outer* frame does not count: a
5845        // declaration shadows it rather than writing through.
5846        if self
5847            .eval_bindings
5848            .iter()
5849            .any(|binding| binding.name == name && binding.frame == caller)
5850        {
5851            return None;
5852        }
5853        let phase = if self.in_parameter_list_at(caller) {
5854            0
5855        } else {
5856            1
5857        };
5858        self.frame_local_vars(caller)?;
5859        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5860        if let Some(cell) = local_vars.get(name, 1) {
5861            return Some(cell);
5862        }
5863        let cell = self.new_cell(Value::Undefined);
5864        Some(local_vars.declare(name, phase, cell))
5865    }
5866
5867    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5868    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5869        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5870            return Some(local_vars.clone());
5871        }
5872        let local_vars = Gc::new(self.heap, LocalVars::new());
5873        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5874        Some(local_vars)
5875    }
5876
5877    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5878    /// property of the global object. Used to decide whether a store inside an
5879    /// `eval` writes through to the realm or declares a binding of its own.
5880    ///
5881    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5882    /// write to `Object.prototype.toString`, and must not shadow it either.
5883    fn global_knows(&mut self, name: &str) -> bool {
5884        if self.realm.globals.contains_key(name) {
5885            return true;
5886        }
5887        self.realm.global.own_property(name).is_some()
5888    }
5889
5890    /// Whether the code currently running is strict.
5891    ///
5892    /// Read off the frame's function, which is where the parser's answer ended up; a
5893    /// native function never runs strict-only checks, and there is no frame at all
5894    /// before the first script.
5895    pub fn current_strict(&self) -> bool {
5896        self.frames
5897            .last()
5898            .is_some_and(|frame| frame.code.code.strict)
5899    }
5900
5901    /// Initialise a declared global, which is what ends its dead zone.
5902    ///
5903    /// A `var` global becomes a property of the global object: writable, so a later
5904    /// assignment goes through, and non-configurable, so `delete` refuses.
5905    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5906        let (name, lexical, _) = self.global_binding(slot);
5907        // A `var` declared by the strict `eval` currently running belongs to the
5908        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5909        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5910        // initialised in place, which is what a re-declaration inside eval does.
5911        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5912            self.eval_scope
5913                .as_mut()
5914                .expect("checked above")
5915                .insert(name, value);
5916            return Ok(());
5917        }
5918        if let Some(scope) = self.eval_scope.as_mut()
5919            && scope.contains_key(&name)
5920        {
5921            scope.insert(name, value);
5922            return Ok(());
5923        }
5924        if lexical {
5925            // The cell exists (created at declaration time) holding the dead-zone
5926            // marker; storing the value is what makes the binding readable.
5927            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5928                cell.set(value);
5929                return Ok(());
5930            }
5931            let cell = self.new_cell(value);
5932            self.realm.globals.insert(name, cell);
5933            return Ok(());
5934        }
5935        let global = self.realm.global.clone();
5936        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5937        // to answer `false` and leave the binding in place. `with_attributes` ties
5938        // `configurable` to `writable`, so the property is built field by field.
5939        global.define(
5940            &name,
5941            Property {
5942                value: Some(value),
5943                writable: true,
5944                enumerable: true,
5945                configurable: false,
5946                ..Property::default()
5947            },
5948        );
5949        Ok(())
5950    }
5951
5952    /// The `TypeError` a store to a `const` global raises.
5953    fn read_only_global(&self, name: &str) -> Signal {
5954        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5955    }
5956
5957    /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
5958    fn dead_zone_global(&self, name: &str) -> Signal {
5959        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
5960    }
5961
5962    // -- properties ---------------------------------------------------------
5963
5964    /// Read `object[key]`, following the prototype chain.
5965    ///
5966    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5967    /// lookup returns the owner rather than just the value.
5968    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5969        self.get_property_key(object, &PropertyKey::from(key))
5970    }
5971
5972    /// [`Interp::get_property`] with a key that may be a symbol.
5973    pub fn get_property_key(
5974        &mut self,
5975        object: &Gc<JsObject>,
5976        key: &PropertyKey,
5977    ) -> JsResult<Option<Value>> {
5978        self.get_property_key_for(object, None, key)
5979    }
5980
5981    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5982    ///
5983    /// The receiver matters when the property is found on a *prototype*: a getter has to
5984    /// see the object the read started from. For a primitive that is the primitive
5985    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5986    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5987    /// the owner.
5988    pub fn get_property_key_for(
5989        &mut self,
5990        object: &Gc<JsObject>,
5991        receiver: Option<&Value>,
5992        key: &PropertyKey,
5993    ) -> JsResult<Option<Value>> {
5994        // A proxy answers for itself, before any of the shortcuts below: `new
5995        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5996        // have.
5997        if object.proxy_state().is_some() {
5998            let receiver = receiver
5999                .cloned()
6000                .unwrap_or_else(|| Value::Object(object.clone()));
6001            return self.proxy_get(object, &receiver, key);
6002        }
6003        // A host class's `get_property` trap replaces the whole read, prototype walk
6004        // included — that is what makes a native accessor free rather than a JavaScript
6005        // getter call.
6006        if let Some(exotic) = object.exotic() {
6007            let receiver_value = receiver
6008                .cloned()
6009                .unwrap_or_else(|| Value::Object(object.clone()));
6010            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6011                return Ok(Some(value));
6012            }
6013            // With no `get_property` trap, a `get_own_property` trap still answers for the
6014            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6015            // and the hook lives exactly there. A key the trap reports as absent is still
6016            // looked for on the prototype, which is why the search resumes *above*.
6017            if let Some(property) = exotic.get_own_property(self, object, key)? {
6018                return match property {
6019                    Some(property) => self.read_property(property, object, receiver),
6020                    None => match lookup_key_above(object, key) {
6021                        Some((_, property)) => self.read_property(property, object, receiver),
6022                        None => Ok(None),
6023                    },
6024                };
6025            }
6026        }
6027        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6028        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6029        // The `[[Get]]` short-circuit therefore belongs to this one arm.
6030        //
6031        // Constructibility is exactly the split the reference makes: `function f(){}` and
6032        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6033        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6034        // function" — it *is* the predicate, which is why no extra marker is needed.
6035        if let Some(text) = key.as_str()
6036            && (text == "caller" || text == "arguments")
6037            && object.is_constructor()
6038            && object.is_callable()
6039            && !object.is_bound_function()
6040            // …and only when the body is **sloppy**. A strict body reaches the
6041            // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6042            // whole `Function/15.3.5.4_2-*gs` family is written against
6043            // (`onlyStrict`, so every function in them is strict).
6044            && !object.function_is_strict()
6045            && object.own_property(text).is_none()
6046        {
6047            return Ok(Some(Value::Undefined));
6048        }
6049        // The element-vector and `length` shortcuts are string-only: an array index
6050        // has no symbol spelling.
6051        if let Some(text) = key.as_str() {
6052            if let Some(value) = self.own_element(object, text) {
6053                return Ok(Some(value));
6054            }
6055            // `length` is not stored as a property: an array's length is its element
6056            // count, and keeping one copy of it is what makes `push`/`pop` and
6057            // `a.length = n` agree.
6058            if let Some(length) = object.array_length()
6059                && text == "length"
6060            {
6061                // Not `Value::Int(length as i32)`: see [`length_value`].
6062                return Ok(Some(crate::object::length_value(length)));
6063            }
6064        }
6065        // A proxy or a hooked exotic object anywhere above `object` makes the static
6066        // table walk below wrong: a proxy's own table is *empty by design* (the properties
6067        // live on its target), so the walk skipped that link entirely and everything behind
6068        // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6069        // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6070        // -target-is-proxy.js` are the four.
6071        if Self::chain_needs_dispatch(object) {
6072            return self.walk_get(object, receiver, key);
6073        }
6074        match lookup_key(object, key) {
6075            Some((_, property)) => self.read_property(property, object, receiver),
6076            None => Ok(None),
6077        }
6078    }
6079
6080    /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6081    /// answer for itself.
6082    ///
6083    /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6084    /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6085    /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6086    /// an inherited getter the object the read started from.
6087    fn walk_get(
6088        &mut self,
6089        start: &Gc<JsObject>,
6090        receiver: Option<&Value>,
6091        key: &PropertyKey,
6092    ) -> JsResult<Option<Value>> {
6093        let receiver = receiver
6094            .cloned()
6095            .unwrap_or_else(|| Value::Object(start.clone()));
6096        let mut current = Some(start.clone());
6097        while let Some(holder) = current {
6098            // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6099            // has to ask it, not read its (empty) own-property table. `Object.create(new
6100            // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6101            // instead found nothing.
6102            if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6103                return Ok(Some(value));
6104            }
6105            // A host class's `get_property` trap replaces the whole read for that holder,
6106            // prototype walk included — the same rule `get_property_key_for` applies to the
6107            // first object.
6108            if let Some(exotic) = holder.exotic()
6109                && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6110            {
6111                return Ok(Some(value));
6112            }
6113            if let Some(property) = self.object_get_own_property(&holder, key)? {
6114                return self.read_property(property, &holder, Some(&receiver));
6115            }
6116            current = self.object_prototype_of(&holder)?;
6117        }
6118        Ok(None)
6119    }
6120
6121    /// Whether `object` or anything above it has properties that cannot be read out of a
6122    /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6123    ///
6124    /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6125    /// is the hot path for every property read; this is the check that decides whether it
6126    /// is safe to take it.
6127    fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6128        object
6129            .chain()
6130            .iter()
6131            .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6132    }
6133
6134    /// The value a property read answers.
6135    ///
6136    /// One place rather than three, because an accessor has to run with the *receiver* as
6137    /// `this` whether the descriptor came from the property table, an exotic
6138    /// `get_own_property` trap, or a prototype above one.
6139    fn read_property(
6140        &mut self,
6141        property: Property,
6142        object: &Gc<JsObject>,
6143        receiver: Option<&Value>,
6144    ) -> JsResult<Option<Value>> {
6145        if property.is_accessor() {
6146            match &property.getter {
6147                Some(getter) if !matches!(getter, Value::Undefined) => {
6148                    let receiver = receiver
6149                        .cloned()
6150                        .unwrap_or_else(|| Value::Object(object.clone()));
6151                    self.call_value(getter.clone(), receiver, Vec::new())
6152                        .map(Some)
6153                }
6154                // An accessor with no getter reads as `undefined`.
6155                _ => Ok(Some(Value::Undefined)),
6156            }
6157        } else {
6158            Ok(property.value)
6159        }
6160    }
6161
6162    /// `super.key` — start the search at `proto`, but report to `receiver`.
6163    ///
6164    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6165    /// found on the prototype of a class has to see the *instance* as `this`, and a
6166    /// plain property read off `proto` would lose that.
6167    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6168        let start = self.require_object(proto)?;
6169        let key = self.propkey(key)?;
6170        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6171        if matches!(proto, Value::Null) {
6172            return Ok(Value::Undefined);
6173        }
6174        match lookup_key(&start, &key) {
6175            Some((_, property)) if property.is_accessor() => match &property.getter {
6176                Some(getter) if !matches!(getter, Value::Undefined) => {
6177                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
6178                }
6179                _ => Ok(Value::Undefined),
6180            },
6181            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6182            None => Ok(Value::Undefined),
6183        }
6184    }
6185
6186    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6187    ///
6188    /// A setter found on the prototype runs with `receiver` as `this`; a data property
6189    /// is shadowed by a new own property on the receiver, the same rule an ordinary
6190    /// assignment follows.
6191    fn super_write(
6192        &mut self,
6193        receiver: &Value,
6194        proto: &Value,
6195        key: &Value,
6196        value: Value,
6197    ) -> JsResult<()> {
6198        let target = self.require_object(receiver)?;
6199        let key = self.propkey(key)?;
6200        if !matches!(proto, Value::Null)
6201            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6202        {
6203            if property.is_accessor() {
6204                if let Some(setter) = &property.setter
6205                    && !matches!(setter, Value::Undefined)
6206                {
6207                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6208                }
6209                return Ok(());
6210            }
6211            // A data property on the prototype is writable or not; reading `owner` at
6212            // all is only for the attribute check.
6213            if !property.writable {
6214                return Err(self.type_error(format!("'{key}' is read-only")));
6215            }
6216            let _ = owner;
6217        }
6218        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6219    }
6220
6221    /// The object a `super` operation needs, or the `TypeError` the spec raises.
6222    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6223        match value.as_object() {
6224            Some(object) => Ok(object.clone()),
6225            None => Err(Signal::Throw(
6226                self.make_error("TypeError", "value is not an object"),
6227            )),
6228        }
6229    }
6230
6231    /// Build the class object `define_class` produces.
6232    ///
6233    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6234    /// whose prototype property is a fresh object inheriting from the parent's
6235    /// prototype, and whose own prototype is the parent constructor — which is what makes
6236    /// a static method inherited too.
6237    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6238        let ctor = self.pop();
6239        let parent = self.pop();
6240        let Value::Object(function) = &ctor else {
6241            return Err(Signal::Throw(
6242                self.make_error("TypeError", "class constructor must be a function"),
6243            ));
6244        };
6245        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6246        // but gives the instances no prototype at all.
6247        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6248            match &parent {
6249                Value::Null => (Some(self.realm.function_proto.clone()), None),
6250                Value::Object(parent_class) => {
6251                    // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6252                    // step 9 rejects a heritage without `[[Construct]]` *before* reading
6253                    // `superclass.prototype`, so an arrow function and a generator — both
6254                    // callable, neither constructible — are a `TypeError` and their
6255                    // `prototype` getter must never run
6256                    // (`subclass/superclass-arrow-function`, `…-generator-function`).
6257                    if !parent_class.is_constructor() {
6258                        return Err(Signal::Throw(
6259                            self.make_error("TypeError", "parent class must be constructor"),
6260                        ));
6261                    }
6262                    let proto = self.get_property(parent_class, "prototype")?;
6263                    match proto {
6264                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6265                        Some(Value::Null) => (Some(parent_class.clone()), None),
6266                        _ => {
6267                            return Err(Signal::Throw(self.make_error(
6268                                "TypeError",
6269                                "parent prototype must be an object or null",
6270                            )));
6271                        }
6272                    }
6273                }
6274                _ => {
6275                    return Err(Signal::Throw(
6276                        self.make_error("TypeError", "parent class must be constructor"),
6277                    ));
6278                }
6279            }
6280        } else {
6281            (
6282                Some(self.realm.function_proto.clone()),
6283                Some(self.realm.object_proto.clone()),
6284            )
6285        };
6286        let proto = self.new_object(parent_proto);
6287        function.set_proto(parent_ctor);
6288        // A class is not callable without `new`, and its `prototype` is not writable —
6289        // both follow from being a class and are what `class A {}; A()` throws on.
6290        function.set_class_constructor(true);
6291        function.set_home_object(None);
6292        self.set_function_name(&ctor, name);
6293        self.define_class_properties(function, &ctor, &proto)?;
6294        Ok((ctor, proto))
6295    }
6296
6297    /// Give the constructor its `prototype` and `length`, and the prototype its
6298    /// `constructor` back-pointer.
6299    fn define_class_properties(
6300        &mut self,
6301        function: &Gc<JsObject>,
6302        ctor: &Value,
6303        proto: &Gc<JsObject>,
6304    ) -> JsResult<()> {
6305        proto.define(
6306            "constructor",
6307            Property::with_attributes(ctor.clone(), true, false),
6308        );
6309        function.define(
6310            "prototype",
6311            Property::prototype_of(Value::Object(proto.clone()), false),
6312        );
6313        if let Some((code, _)) = bytecode_of(function) {
6314            let length = code.code.defined_args;
6315            function.define(
6316                "length",
6317                Property::name_or_length(Value::Int(length as i32)),
6318            );
6319        }
6320        Ok(())
6321    }
6322
6323    /// The own array element `key` names, if this object has one.
6324    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6325        // A typed array's elements live in its buffer, not in a property list: reading one
6326        // goes through the view's element type so a bounds check and a detached buffer are
6327        // both handled there.
6328        //
6329        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6330        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6331        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6332        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6333        // consulted. Testing with `array_index` rejected all three, which let a throwing
6334        // getter installed on `TypedArray.prototype["-1"]` run.
6335        if object.typed_array_parts().is_some() {
6336            let property_key = PropertyKey::from(key);
6337            let numeric = canonical_numeric_index(&property_key)?;
6338            if typed_array_index_is_valid(object, numeric) {
6339                return object.typed_array_element(numeric as usize);
6340            }
6341            // Canonical, but not a valid index: `undefined`, and *final*.
6342            return Some(Value::Undefined);
6343        }
6344        let index = array_index(key)?;
6345        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6346        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6347        // search early, which is why `Array.prototype[1] = 9` could not be seen through
6348        // `[1,,3][1]`.
6349        match object.array_get(index as usize) {
6350            Some(Value::Hole) | None => None,
6351            other => other,
6352        }
6353    }
6354
6355    /// Store `object[key] = value`, honouring setters and inherited properties.
6356    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6357        self.set_property_with(object, key, value, DeleteFailure::Throw)
6358    }
6359
6360    /// Store a property, choosing what to do when the object refuses.
6361    ///
6362    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6363    /// mode, which is the one place assignment differs by mode. Native code (the array
6364    /// methods, `JSON`) always asks for the throw.
6365    pub fn set_property_with(
6366        &mut self,
6367        object: &Gc<JsObject>,
6368        key: &str,
6369        value: Value,
6370        on_failure: DeleteFailure,
6371    ) -> JsResult<()> {
6372        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6373    }
6374
6375    /// [`Interp::set_property_with`] with a key that may be a symbol.
6376    pub fn set_property_with_key(
6377        &mut self,
6378        object: &Gc<JsObject>,
6379        key: &PropertyKey,
6380        value: Value,
6381        on_failure: DeleteFailure,
6382    ) -> JsResult<()> {
6383        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6384    }
6385
6386    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6387    ///
6388    /// The receiver split lives one level up, in
6389    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6390    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6391    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6392    /// stores into `object` itself, which is why the element branch below converts `V`
6393    /// before asking whether the index is valid: `V` may put it back in bounds
6394    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6395    fn set_property_with_key_receiver_aware(
6396        &mut self,
6397        object: &Gc<JsObject>,
6398        key: &PropertyKey,
6399        value: Value,
6400        on_failure: DeleteFailure,
6401    ) -> JsResult<()> {
6402        // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6403        // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6404        // Nothing about the receiver or the value changes that, so the whole operation is
6405        // one answer.
6406        //
6407        // Not implementing it explicitly left the ordinary algorithm in charge, and that
6408        // says "true" for names the namespace does not own as soon as the value matches or
6409        // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6410        // assignment stopped throwing (`await-ns-set-strict`).
6411        if object.module_namespace_marker() {
6412            return match on_failure {
6413                DeleteFailure::Ignore => Ok(()),
6414                DeleteFailure::Throw => Err(self.type_error(format!(
6415                    "cannot assign to property '{key}' of a module namespace object"
6416                ))),
6417            };
6418        }
6419        // A proxy's `set` trap decides, and its `false` means the same thing an
6420        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6421        if object.proxy_state().is_some() {
6422            let receiver = Value::Object(object.clone());
6423            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6424                return match (accepted, on_failure) {
6425                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6426                    (false, DeleteFailure::Throw) => {
6427                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6428                    }
6429                };
6430            }
6431        }
6432        // A host class's `set_property` trap decides for itself. `Some(false)` is a
6433        // refusal and means exactly what a proxy's `false` means.
6434        if let Some(exotic) = object.exotic() {
6435            let receiver = Value::Object(object.clone());
6436            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6437                return match (accepted, on_failure) {
6438                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6439                    (false, DeleteFailure::Throw) => {
6440                        Err(self.type_error(format!("property '{key}' is read-only")))
6441                    }
6442                };
6443            }
6444        }
6445        // The element and `length` shortcuts only exist for string keys: an array
6446        // index has no symbol spelling, and a symbol named `length` is an ordinary
6447        // property.
6448        let text = key.as_str();
6449        // A typed array's elements are a window onto its buffer: the store has to go
6450        // through the view's element type so the value is wrapped (or clamped) and so an
6451        // out-of-range or detached write is a silent no-op, as the spec says.
6452        //
6453        // The key test is `CanonicalNumericIndexString`, like every other index operation
6454        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6455        // does not exist, so they do nothing and leave no own property behind
6456        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6457        // path, which created a property named `"-0"`.
6458        //
6459        // The conversion comes **first**, before the index is checked at all, and that
6460        // order is observable twice over:
6461        //
6462        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6463        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6464        //   then store the converted value;
6465        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6466        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6467        //   run and its exception to escape.
6468        //
6469        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6470        // validity check, not a validity check that skips the conversion. The store itself
6471        // is a no-op when the index is invalid by then, which is why no extra guard is
6472        // needed around `typed_array_set`.
6473        if let Some(element) = object.typed_array_element_type()
6474            && let Some(numeric) = canonical_numeric_index(key)
6475        {
6476            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6477            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6478            // in `Interp`, because it is script-observable and the storage borrow inside
6479            // `typed_array_set` must not be held across it.
6480            let stored = self.element_value(element, value)?;
6481            if typed_array_index_is_valid(object, numeric)
6482                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6483            {
6484                return Err(self.type_error(reason));
6485            }
6486            return Ok(());
6487        }
6488        if let Some(text) = text
6489            && let Some(index) = array_index(text)
6490            && object.is_array()
6491        {
6492            // An accessor defined on an index lives in the property table while the
6493            // element slot is a hole, so the store has to go through the property first.
6494            // Writing the vector directly skipped the setter entirely.
6495            if let Some(existing) = object.own_property_key(key) {
6496                if existing.is_accessor() {
6497                    return match existing.setter.clone() {
6498                        Some(setter) if !matches!(setter, Value::Undefined) => {
6499                            let receiver = Value::Object(object.clone());
6500                            self.call_value(setter, receiver, vec![value]).map(|_| ())
6501                        }
6502                        _ => match on_failure {
6503                            DeleteFailure::Throw => Err(self.type_error(format!(
6504                                "cannot set property '{text}', it has only a getter"
6505                            ))),
6506                            DeleteFailure::Ignore => Ok(()),
6507                        },
6508                    };
6509                }
6510                if !existing.writable {
6511                    return match on_failure {
6512                        DeleteFailure::Throw => {
6513                            Err(self.type_error(format!("'{text}' is read-only")))
6514                        }
6515                        DeleteFailure::Ignore => Ok(()),
6516                    };
6517                }
6518            }
6519            {
6520                // Growing the array needs a writable `length`.
6521                if (index as usize) >= object.array_length().unwrap_or(0)
6522                    && !object.length_writable()
6523                {
6524                    return match on_failure {
6525                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6526                        DeleteFailure::Ignore => Ok(()),
6527                    };
6528                }
6529                // Adding an index past the end makes the array longer, which a
6530                // non-extensible array refuses.
6531                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6532                    return match on_failure {
6533                        DeleteFailure::Throw => Err(self.type_error(format!(
6534                            "cannot add property '{key}', object is not extensible"
6535                        ))),
6536                        DeleteFailure::Ignore => Ok(()),
6537                    };
6538                }
6539                if object.element_is_locked(index) {
6540                    return match on_failure {
6541                        DeleteFailure::Throw => {
6542                            Err(self.type_error(format!("'{key}' is read-only")))
6543                        }
6544                        DeleteFailure::Ignore => Ok(()),
6545                    };
6546                }
6547                // The element vector is only half of `[[Set]]` for an index: the
6548                // prototype chain is consulted first, and a setter there answers instead
6549                // of the element store. This branch used to write the element directly, so
6550                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6551                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6552                // the reference calls the setter and the array keeps no own index.
6553                //
6554                // An *exotic* prototype has no entry to find, because its indices live
6555                // outside the property table — `Object.setPrototypeOf([], typedArray)`
6556                // then looked like "nothing on the chain" and the store created the
6557                // element, where the view's `[[Set]]` answers `true` and does nothing for
6558                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6559                // checks the array's `length` stays 0). So the dispatch comes first.
6560                if !object.has_own_key(key)
6561                    && let Some(proto) = object.proto()
6562                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6563                {
6564                    let receiver = Value::Object(object.clone());
6565                    let accepted =
6566                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6567                    return if accepted {
6568                        Ok(())
6569                    } else {
6570                        match on_failure {
6571                            DeleteFailure::Throw => {
6572                                Err(self.type_error(format!("'{key}' is read-only")))
6573                            }
6574                            DeleteFailure::Ignore => Ok(()),
6575                        }
6576                    };
6577                }
6578                if let Some((owner, property)) = lookup_key(object, key)
6579                    && !owner.ptr_eq(object)
6580                {
6581                    match &property {
6582                        property if property.is_accessor() => {
6583                            match &property.setter {
6584                                Some(setter) if !matches!(setter, Value::Undefined) => {
6585                                    let receiver = Value::Object(object.clone());
6586                                    self.call_value(setter.clone(), receiver, vec![value])?;
6587                                }
6588                                _ => {
6589                                    return match on_failure {
6590                                        DeleteFailure::Throw => Err(self.type_error(format!(
6591                                            "cannot set property '{text}', it has only a getter"
6592                                        ))),
6593                                        DeleteFailure::Ignore => Ok(()),
6594                                    };
6595                                }
6596                            }
6597                            return Ok(());
6598                        }
6599                        property if !property.writable => {
6600                            return match on_failure {
6601                                DeleteFailure::Throw => {
6602                                    Err(self.type_error(format!("'{text}' is read-only")))
6603                                }
6604                                DeleteFailure::Ignore => Ok(()),
6605                            };
6606                        }
6607                        _ => {}
6608                    }
6609                }
6610                if object.array_set(self.heap, index as usize, value.clone()) {
6611                    return Ok(());
6612                }
6613                // Past the dense limit the slot is too far out to be worth one `Value`
6614                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6615                // constant time by keeping the index as an ordinary property. The store
6616                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6617                // to a legal program.
6618                object.define_key(key, Property::with_attributes(value, true, true));
6619                // Extend, never shorten: the index may be *inside* the current length (a
6620                // huge `length` with a sparse store), and shortening would delete the
6621                // sparse properties above it — including the one just stored.
6622                if index as usize + 1 > object.array_length().unwrap_or(0) {
6623                    object.array_set_length(self.heap, index as usize + 1);
6624                }
6625                return Ok(());
6626            }
6627        }
6628        if text == Some("length") && object.is_array() {
6629            // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6630            // test. A `valueOf` that locks `length` on its second call therefore turns the
6631            // store into a refused write rather than a silent success
6632            // (`length/define-own-prop-length-coercion-order-set`).
6633            let rounded = self.coerce_array_length_twice(&value)?;
6634            if !object.length_writable() {
6635                return match on_failure {
6636                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6637                    DeleteFailure::Ignore => Ok(()),
6638                };
6639            }
6640            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6641            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6642            // answered `NaN`, which left the assignment silently ignored
6643            // (`S15.4.5.2_A3_T2`).
6644            let _ = rounded;
6645            let length = self.to_js_number(&value)?;
6646            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6647            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6648            // `RangeError`s; the old code only tested "finite and non-negative" and then
6649            // truncated, so `[].length = 4294967297` quietly produced a length no array can
6650            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6651            let valid = length.is_finite()
6652                && length >= 0.0
6653                && length.fract() == 0.0
6654                && length <= u32::MAX as f64;
6655            if !valid {
6656                return Err(self.range_error("invalid array length"));
6657            }
6658            {
6659                let length = length as usize;
6660                // `a.length = n` with `n` below a non-configurable element cannot
6661                // drop that element, so the whole assignment fails. The spec makes
6662                // this a `TypeError` rather than a silent no-op, in any mode.
6663                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6664                    // Sloppy mode stops the truncation at the blocking element
6665                    // instead of failing; strict mode raises.
6666                    // Both modes stop at the blocking element; they differ in
6667                    // whether that is reported. The reference truncates *then*
6668                    // throws, so the array is left in the shortened state.
6669                    object.array_truncate(self.heap, blocked + 1);
6670                    return match on_failure {
6671                        DeleteFailure::Throw => {
6672                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
6673                        }
6674                        DeleteFailure::Ignore => Ok(()),
6675                    };
6676                }
6677                object.array_set_length(self.heap, length);
6678                return Ok(());
6679            }
6680        }
6681        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6682        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6683        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6684        //
6685        // The prototype step is a dispatch, not a lookup. Walking the chain here and
6686        // applying whatever came back is the same thing for an ordinary prototype and
6687        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6688        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6689        // answers "not mine, the receiver is not me" without touching the buffer. This
6690        // code used to find nothing owned by `o`, find no property on the view either,
6691        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6692        // object and never converted (`key-is-valid-index-prototype-chain-set`,
6693        // `key-is-canonical-invalid-index-prototype-chain-set`).
6694        //
6695        // The read-only and accessor rules of step 1 are what make
6696        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6697        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6698        let own = match self.lookup_for_write(object, key)? {
6699            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6700            _ => None,
6701        };
6702        if let Some(property) = own {
6703            if property.is_accessor() {
6704                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6705                    Some(setter) => {
6706                        let receiver = Value::Object(object.clone());
6707                        self.call_value(setter, receiver, vec![value])?;
6708                        Ok(())
6709                    }
6710                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6711                    // Sloppy code swallows that refusal, strict code raises — the same
6712                    // rule the read-only *data* property below follows, and skipping it
6713                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6714                    // return silently. The reference answers `TypeError: 'x' is
6715                    // read-only`.
6716                    None => match on_failure {
6717                        DeleteFailure::Throw => {
6718                            Err(self.type_error(format!("'{key}' is read-only")))
6719                        }
6720                        DeleteFailure::Ignore => Ok(()),
6721                    },
6722                };
6723            }
6724            // An own non-writable data property stops here: nothing may change it.
6725            if !property.writable {
6726                return match on_failure {
6727                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6728                    DeleteFailure::Ignore => Ok(()),
6729                };
6730            }
6731            // An existing writable own property keeps its attributes: only the value
6732            // moves. Redefining instead would reset them, which is how a
6733            // non-configurable global `var` used to become deletable.
6734            if object.write_value_key(key, value.clone()) {
6735                return Ok(());
6736            }
6737        }
6738        // Step 2: hand the store to the prototype, with `object` as the receiver.
6739        if let Some(proto) = object.proto() {
6740            let receiver = Value::Object(object.clone());
6741            let accepted =
6742                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6743            return if accepted {
6744                Ok(())
6745            } else {
6746                match on_failure {
6747                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6748                    DeleteFailure::Ignore => Ok(()),
6749                }
6750            };
6751        }
6752        // Step 3: create one, and a non-extensible object cannot.
6753        if !object.is_extensible() {
6754            return match on_failure {
6755                DeleteFailure::Throw => Err(self.type_error(format!(
6756                    "cannot add property {key}, object is not extensible"
6757                ))),
6758                DeleteFailure::Ignore => Ok(()),
6759            };
6760        }
6761        object.define_data_key(key, value);
6762        Ok(())
6763    }
6764
6765    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6766    ///
6767    /// The distinction the fast path above does not need: it is called with the store's
6768    /// receiver already being the object it writes to. Here `object` is the one whose
6769    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6770    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6771    /// and not a write to `object`.
6772    ///
6773    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6774    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6775    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6776    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6777    /// descriptor on the prototype refuses instead, which is the same rule that keeps
6778    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6779    ///
6780    /// Answers `false` where the spec says `false`; the caller turns that into the
6781    /// strict-mode `TypeError` or the sloppy-mode silence.
6782    fn ordinary_set_with_receiver(
6783        &mut self,
6784        object: &Gc<JsObject>,
6785        receiver: &Value,
6786        key: &PropertyKey,
6787        value: Value,
6788        on_failure: DeleteFailure,
6789    ) -> JsResult<bool> {
6790        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6791        if object.proxy_state().is_some() {
6792            return Ok(self
6793                .proxy_set(object, key, value, receiver)?
6794                .unwrap_or(true));
6795        }
6796        // A host class decides for itself, with the receiver the caller named.
6797        if let Some(exotic) = object.exotic()
6798            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6799        {
6800            return Ok(accepted);
6801        }
6802        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6803        // rather than the receiver, but the receiver may still *be* the view:
6804        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6805        // itself as receiver, and then the first half applies — convert `V` once, store
6806        // if the index is valid, answer `true` either way. The conversion is the observable
6807        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6808        //
6809        // Only the second half, a view that is *not* the receiver, skips the conversion
6810        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6811        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6812        // below with the value still unconverted.
6813        if object.typed_array_element_type().is_some()
6814            && let Some(numeric) = canonical_numeric_index(key)
6815        {
6816            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6817                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6818                return Ok(true);
6819            }
6820            if !typed_array_index_is_valid(object, numeric) {
6821                return Ok(true);
6822            }
6823        }
6824        let own = self.object_get_own_property(object, key)?;
6825        if let Some(own) = own {
6826            if own.is_accessor() {
6827                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6828                    Some(setter) => {
6829                        self.call_value(setter, receiver.clone(), vec![value])?;
6830                        Ok(true)
6831                    }
6832                    None => Ok(false),
6833                };
6834            }
6835            // A non-writable data descriptor refuses, own or inherited. Either way the
6836            // receiver must not gain a shadowing property.
6837            if !own.writable {
6838                return Ok(false);
6839            }
6840            // Step 1.d: the *receiver's* own descriptor decides whether it can be
6841            // created or written, and it is created as an ordinary data property.
6842            let Some(receiver_object) = receiver.as_object().cloned() else {
6843                return Ok(false);
6844            };
6845            return match self.object_get_own_property(&receiver_object, key)? {
6846                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6847                Some(existing) => self.object_define_own_property(
6848                    &receiver_object,
6849                    key,
6850                    Property {
6851                        value: Some(value),
6852                        ..existing
6853                    },
6854                ),
6855                None => {
6856                    self.object_define_own_property(&receiver_object, key, Property::data(value))
6857                }
6858            };
6859        }
6860        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6861        if let Some(proto) = object.proto() {
6862            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6863        }
6864        // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6865        // *default* data descriptor here, so control falls into step 2 exactly as if the
6866        // target had owned a writable property — which means the **receiver's** own
6867        // descriptor is asked for before the write. Skipping that question went straight to
6868        // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6869        // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6870        // exactly those calls).
6871        let Some(receiver_object) = receiver.as_object().cloned() else {
6872            return Ok(false);
6873        };
6874        match self.object_get_own_property(&receiver_object, key)? {
6875            Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6876            Some(existing) => self.object_define_own_property(
6877                &receiver_object,
6878                key,
6879                Property {
6880                    value: Some(value),
6881                    ..existing
6882                },
6883            ),
6884            None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6885        }
6886    }
6887
6888    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6889    ///
6890    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6891    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6892    /// a virtual accessor gets its setter run without implementing `set_property` at all.
6893    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6894    /// the prototype, so the walk resumes above the object.
6895    fn lookup_for_write(
6896        &mut self,
6897        object: &Gc<JsObject>,
6898        key: &PropertyKey,
6899    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6900        let Some(exotic) = object.exotic() else {
6901            return Ok(lookup_key(object, key));
6902        };
6903        Ok(match exotic.get_own_property(self, object, key)? {
6904            Some(Some(property)) => Some((object.clone(), property)),
6905            Some(None) => lookup_key_above(object, key),
6906            None => lookup_key(object, key),
6907        })
6908    }
6909
6910    /// Delete `object[key]`.
6911    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6912        self.delete_property_key(object, &PropertyKey::from(key))
6913    }
6914
6915    /// [`Interp::delete_property`] with a key that may be a symbol.
6916    pub fn delete_property_key(
6917        &mut self,
6918        object: &Gc<JsObject>,
6919        key: &PropertyKey,
6920    ) -> JsResult<bool> {
6921        // A proxy decides for itself, and may even throw; the invariant checks live in
6922        // `proxy_delete`.
6923        if let Some(answer) = self.proxy_delete(object, key)? {
6924            return Ok(answer);
6925        }
6926        // A host class's `delete_property` trap decides; `false` is a refusal, which the
6927        // caller reports as a failed delete.
6928        if let Some(exotic) = object.exotic()
6929            && let Some(answer) = exotic.delete_property(self, object, key)?
6930        {
6931            return Ok(answer);
6932        }
6933        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6934        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6935        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6936        // one answers `false` because the elements are non-configurable. The prototype
6937        // chain is not consulted either, which is what makes a throwing getter on
6938        // `TypedArray.prototype["-1"]` stay unrun.
6939        if object.typed_array_parts().is_some()
6940            && object.proxy_state().is_none()
6941            && let Some(numeric) = canonical_numeric_index(key)
6942        {
6943            return Ok(!typed_array_index_is_valid(object, numeric));
6944        }
6945        let mapped_index = key.as_str().and_then(array_index);
6946        if let Some(index) = mapped_index
6947            && let Some(length) = object.array_length()
6948            && (index as usize) < length
6949        {
6950            // An accessor defined on an index lives in the property table rather than the
6951            // element vector, so both have to be cleared: `delete` after
6952            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6953            object.delete_key(key);
6954            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6955            // index stops answering `in`.
6956            if object.element_is_undeletable(index) {
6957                return Ok(false);
6958            }
6959            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6960            // so a later `defineProperty(arguments, "0", {value})` writes to the object
6961            // and no longer through to the parameter. A refused delete leaves the
6962            // mapping alone.
6963            object.drop_mapped_argument(index as usize);
6964            object.array_set(self.heap, index as usize, Value::Hole);
6965            return Ok(true);
6966        }
6967        // An array's `length` is a non-configurable own property that lives outside the
6968        // property table, so `delete_key` finds nothing and reports success — `Reflect
6969        // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6970        // §10.4.4.1 step 3 refuses it.
6971        if key.as_str() == Some("length") && object.array_length().is_some() {
6972            return Ok(false);
6973        }
6974        // The same for an object that is not an array: only a delete that actually
6975        // removed the property ends the alias.
6976        let deleted = object.delete_key(key);
6977        if deleted && let Some(index) = mapped_index {
6978            object.drop_mapped_argument(index as usize);
6979        }
6980        Ok(deleted)
6981    }
6982
6983    // -- proxy traps --------------------------------------------------------
6984    //
6985    // A proxy's internal methods all look the same: ask the handler for the trap, call it
6986    // with the target and the operation's own arguments, then check the answer against
6987    // the target. The checks are not decoration — they are what stops a proxy from
6988    // reporting a `non-configurable` property as missing, which would let a frozen object
6989    // be rewritten by standing in front of it.
6990
6991    /// The target and handler of `object`, or `None` when it is not a proxy.
6992    ///
6993    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6994    /// one has to fail: the slots the traps would have been read from are gone.
6995    pub(crate) fn proxy_parts(
6996        &mut self,
6997        object: &Gc<JsObject>,
6998    ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6999        let Some(state) = object.proxy_state() else {
7000            return Ok(None);
7001        };
7002        let state = state.borrow();
7003        match (&state.target, &state.handler) {
7004            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7005            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7006        }
7007    }
7008
7009    /// Call `handler[name]`, or answer `None` when the trap is absent.
7010    ///
7011    /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7012    /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7013    /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7014    /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7015    /// one per trap plus the `target-is-proxy` variants.
7016    ///
7017    /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7018    /// this cannot simply be "any non-callable means no trap".
7019    fn proxy_trap(
7020        &mut self,
7021        handler: &Value,
7022        name: &str,
7023        args: Vec<Value>,
7024    ) -> JsResult<Option<Value>> {
7025        let Value::Object(table) = handler else {
7026            return Err(self.type_error("proxy handler is not an object"));
7027        };
7028        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7029        match trap {
7030            Value::Undefined | Value::Null => Ok(None),
7031            Value::Object(function) if function.is_callable() => {
7032                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7033                Ok(Some(answer))
7034            }
7035            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7036        }
7037    }
7038
7039    /// Whether the target's own property `key` is one it refuses to lose.
7040    ///
7041    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7042    /// its value behind the target's back.
7043    ///
7044    /// A **method**, not a free function, because §10.5.1's invariants say
7045    /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7046    /// property table directly finds nothing (a proxy's table is empty by design), so every
7047    /// invariant check silently passed for a proxy target. That is what
7048    /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7049    /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7050    /// where an array's elements and its `length` — both fixed, both outside the table —
7051    /// are covered.
7052    fn fixed_property(
7053        &mut self,
7054        target: &Gc<JsObject>,
7055        key: &PropertyKey,
7056    ) -> JsResult<Option<Property>> {
7057        Ok(self
7058            .object_get_own_property(target, key)?
7059            .filter(|property| !property.configurable))
7060    }
7061
7062    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7063    fn proxy_get(
7064        &mut self,
7065        object: &Gc<JsObject>,
7066        receiver: &Value,
7067        key: &PropertyKey,
7068    ) -> JsResult<Option<Value>> {
7069        let Some((target, handler)) = self.proxy_parts(object)? else {
7070            return Ok(None);
7071        };
7072        let key_value = self.key_value(key);
7073        let Some(result) = self.proxy_trap(
7074            &handler,
7075            "get",
7076            vec![Value::Object(target.clone()), key_value, receiver.clone()],
7077        )?
7078        else {
7079            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7080            // inherited getter still sees the proxy.
7081            return Ok(Some(
7082                self.get_property_key_for(&target, Some(receiver), key)?
7083                    .unwrap_or(Value::Undefined),
7084            ));
7085        };
7086        if let Some(fixed) = self.fixed_property(&target, key)? {
7087            if fixed.is_accessor() {
7088                // A fixed accessor with no getter must read as `undefined`.
7089                let has_getter = fixed
7090                    .getter
7091                    .as_ref()
7092                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
7093                if !has_getter && !matches!(result, Value::Undefined) {
7094                    return Err(self.type_error(format!(
7095                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
7096                    )));
7097                }
7098            } else if !fixed.writable {
7099                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7100                if !fixed_value.same_value(&result) {
7101                    return Err(self.type_error(format!(
7102                        "proxy 'get' disagrees with the non-configurable property '{key}'"
7103                    )));
7104                }
7105            }
7106        }
7107        Ok(Some(result))
7108    }
7109
7110    /// `[[Set]]` on a proxy.
7111    ///
7112    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7113    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7114    /// read-only store has.
7115    fn proxy_set(
7116        &mut self,
7117        object: &Gc<JsObject>,
7118        key: &PropertyKey,
7119        value: Value,
7120        receiver: &Value,
7121    ) -> JsResult<Option<bool>> {
7122        let Some((target, handler)) = self.proxy_parts(object)? else {
7123            return Ok(None);
7124        };
7125        let key_value = self.key_value(key);
7126        let Some(result) = self.proxy_trap(
7127            &handler,
7128            "set",
7129            vec![
7130                Value::Object(target.clone()),
7131                key_value,
7132                value.clone(),
7133                receiver.clone(),
7134            ],
7135        )?
7136        else {
7137            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7138            // given — not the target. `OrdinarySet` step 3 is
7139            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7140            // object whose prototype is a typed array has to reach the proxy's own
7141            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7142            // calls and expects exactly one. Storing on the target instead put the value
7143            // in the target and never consulted the trap.
7144            let accepted = self.ordinary_set_with_receiver(
7145                &target,
7146                receiver,
7147                key,
7148                value,
7149                DeleteFailure::Ignore,
7150            )?;
7151            return Ok(Some(accepted));
7152        };
7153        if !result.to_boolean() {
7154            return Ok(Some(false));
7155        }
7156        if let Some(fixed) = self.fixed_property(&target, key)? {
7157            if fixed.is_accessor() {
7158                let has_setter = fixed
7159                    .setter
7160                    .as_ref()
7161                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
7162                if !has_setter {
7163                    return Err(self.type_error(format!(
7164                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7165                    )));
7166                }
7167            } else if !fixed.writable {
7168                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7169                if !fixed_value.same_value(&value) {
7170                    return Err(self.type_error(format!(
7171                        "proxy 'set' changed the non-configurable property '{key}'"
7172                    )));
7173                }
7174            }
7175        }
7176        // A new property cannot appear on a target that refuses new properties.
7177        if self.object_get_own_property(&target, key)?.is_none()
7178            && !self.object_is_extensible(&target)?
7179        {
7180            return Err(self.type_error(format!(
7181                "proxy 'set' added '{key}' to a non-extensible target"
7182            )));
7183        }
7184        Ok(Some(true))
7185    }
7186
7187    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7188    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7189        let Some((target, handler)) = self.proxy_parts(object)? else {
7190            return Ok(None);
7191        };
7192        let key_value = self.key_value(key);
7193        let Some(result) = self.proxy_trap(
7194            &handler,
7195            "has",
7196            vec![Value::Object(target.clone()), key_value],
7197        )?
7198        else {
7199            return Ok(Some(self.has_own_or_inherited(&target, key)?));
7200        };
7201        if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7202            return Err(self.type_error(format!(
7203                "proxy 'has' denied the non-configurable property '{key}'"
7204            )));
7205        }
7206        // A non-extensible target cannot grow, so every own property it *has* is fixed.
7207        if !result.to_boolean()
7208            && !self.object_is_extensible(&target)?
7209            && self.object_get_own_property(&target, key)?.is_some()
7210        {
7211            return Err(self.type_error(format!(
7212                "proxy 'has' denied the own property '{key}' of a non-extensible target"
7213            )));
7214        }
7215        Ok(Some(result.to_boolean()))
7216    }
7217
7218    /// `[[Delete]]` on a proxy.
7219    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7220        let Some((target, handler)) = self.proxy_parts(object)? else {
7221            return Ok(None);
7222        };
7223        let key_value = self.key_value(key);
7224        let Some(result) = self.proxy_trap(
7225            &handler,
7226            "deleteProperty",
7227            vec![Value::Object(target.clone()), key_value],
7228        )?
7229        else {
7230            return Ok(Some(self.delete_property_key(&target, key)?));
7231        };
7232        if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7233            return Err(self.type_error(format!(
7234                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7235            )));
7236        }
7237        if result.to_boolean()
7238            && !self.object_is_extensible(&target)?
7239            && self.object_get_own_property(&target, key)?.is_some()
7240        {
7241            return Err(self.type_error(format!(
7242                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7243            )));
7244        }
7245        Ok(Some(result.to_boolean()))
7246    }
7247
7248    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7249    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7250        let Some((target, handler)) = self.proxy_parts(object)? else {
7251            return Ok(None);
7252        };
7253        let Some(result) =
7254            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7255        else {
7256            // No trap: the target's own keys, already in the order an object reports.
7257            return Ok(Some(self.object_own_property_keys(&target)?));
7258        };
7259        // `CreateListFromArrayLike` with the string-or-symbol restriction.
7260        let list = self.list_from_array_like(&result, true)?;
7261        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7262        for value in list {
7263            let key = self.propkey(&value)?;
7264            if keys.contains(&key) {
7265                return Err(self.type_error(format!(
7266                    "proxy 'ownKeys' returned the duplicate key '{key}'"
7267                )));
7268            }
7269            keys.push(key);
7270        }
7271        // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7272        // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7273        // table is empty, which made every check below vacuous.
7274        let target_keys = self.object_own_property_keys(&target)?;
7275        let extensible = self.object_is_extensible(&target)?;
7276        for key in &target_keys {
7277            if keys.contains(key) {
7278                continue;
7279            }
7280            if self.fixed_property(&target, key)?.is_some() {
7281                return Err(self.type_error(format!(
7282                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7283                )));
7284            }
7285            if !extensible {
7286                return Err(self.type_error(format!(
7287                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7288                )));
7289            }
7290        }
7291        if !extensible {
7292            // §10.5.11 step 12: the lists must match one for one, in any order.
7293            if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7294            {
7295                return Err(
7296                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7297                );
7298            }
7299        }
7300        Ok(Some(keys))
7301    }
7302
7303    /// `[[GetOwnProperty]]` on a proxy.
7304    fn proxy_get_own_property(
7305        &mut self,
7306        object: &Gc<JsObject>,
7307        key: &PropertyKey,
7308    ) -> JsResult<Option<Option<Property>>> {
7309        let Some((target, handler)) = self.proxy_parts(object)? else {
7310            return Ok(None);
7311        };
7312        let key_value = self.key_value(key);
7313        let Some(result) = self.proxy_trap(
7314            &handler,
7315            "getOwnPropertyDescriptor",
7316            vec![Value::Object(target.clone()), key_value],
7317        )?
7318        else {
7319            // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7320            // property table. Two things ride on that choice: a target that is itself a
7321            // proxy has to re-dispatch (its own table is empty, so reading it reported
7322            // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7323            // indices and `length` live outside the table and need the ordinary synthesis.
7324            // `object_get_own_property` does both.
7325            return Ok(Some(self.object_get_own_property(&target, key)?));
7326        };
7327        // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7328        // `ToPropertyDescriptor` runs, because that operation would box the primitive
7329        // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7330        // empty descriptor instead of refusing.
7331        if !matches!(result, Value::Undefined | Value::Object(_)) {
7332            return Err(self.type_error(
7333                "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7334            ));
7335        }
7336        let target_desc = self.object_get_own_property(&target, key)?;
7337        let extensible = self.object_is_extensible(&target)?;
7338        let Some(descriptor) = (match result {
7339            Value::Undefined => None,
7340            _ => Some(self.property_from_descriptor(&result)?),
7341        }) else {
7342            // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7343            // descriptor is configurable *and* the target can still grow back.
7344            if let Some(target_desc) = &target_desc {
7345                if !target_desc.configurable {
7346                    return Err(self.type_error(format!(
7347                        "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7348                    )));
7349                }
7350                if !extensible {
7351                    return Err(self.type_error(format!(
7352                        "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7353                    )));
7354                }
7355            }
7356            return Ok(Some(None));
7357        };
7358        // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7359        // which is a stronger requirement than "the target is not contradicting it" — the
7360        // four branches below are each one test262 case.
7361        if !descriptor.configurable {
7362            let Some(target_desc) = &target_desc else {
7363                return Err(self.type_error(format!(
7364                    "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7365                )));
7366            };
7367            if target_desc.configurable {
7368                return Err(self.type_error(format!(
7369                    "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7370                )));
7371            }
7372            let target_is_data = !target_desc.is_accessor();
7373            let result_is_data = !descriptor.is_accessor();
7374            if result_is_data && !target_is_data {
7375                return Err(self.type_error(format!(
7376                    "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7377                )));
7378            }
7379            if target_is_data && !target_desc.writable {
7380                if !result_is_data {
7381                    return Err(self.type_error(format!(
7382                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7383                    )));
7384                }
7385                if descriptor.writable {
7386                    return Err(self.type_error(format!(
7387                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7388                    )));
7389                }
7390                let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7391                let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7392                if !fixed_value.same_value(&reported) {
7393                    return Err(self.type_error(format!(
7394                        "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7395                    )));
7396                }
7397            }
7398            // Step 16.d: a reported *read-only* data property needs a real read-only data
7399            // property behind it. Missing this let a trap bolt a frozen property onto a
7400            // writable target intent (`resultdesc-is-not-configurable-not-writable-
7401            // targetdesc-is-writable`).
7402            if result_is_data && !descriptor.writable {
7403                if !target_is_data {
7404                    return Err(self.type_error(format!(
7405                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7406                    )));
7407                }
7408                if target_desc.writable {
7409                    return Err(self.type_error(format!(
7410                        "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7411                    )));
7412                }
7413            }
7414            if descriptor.is_accessor() {
7415                // Step 16.e: a getter the target does not have may not be invented, and
7416                // vice versa.
7417                let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7418                    (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7419                    (Some(a), Some(b)) => a.same_value(b),
7420                    _ => false,
7421                };
7422                if !same(&target_desc.getter, &descriptor.getter)
7423                    || !same(&target_desc.setter, &descriptor.setter)
7424                {
7425                    return Err(self.type_error(format!(
7426                        "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7427                    )));
7428                }
7429            }
7430        }
7431        // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7432        // where the target's own is locked. Without it a handler could advertise
7433        // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7434        // that believed it would try to redefine something it cannot.
7435        if descriptor.configurable
7436            && let Some(target_desc) = &target_desc
7437            && !target_desc.configurable
7438        {
7439            return Err(self.type_error(format!(
7440                "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7441            )));
7442        }
7443        // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7444        // through the trap either, however well-formed the descriptor is. This is the
7445        // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7446        // the frozen target does not own.
7447        if !extensible {
7448            let Some(target_desc) = &target_desc else {
7449                return Err(self.type_error(format!(
7450                    "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7451                )));
7452            };
7453            if target_desc.is_accessor() == descriptor.is_accessor() {
7454                let target_is_data = !target_desc.is_accessor();
7455                let result_is_data = !descriptor.is_accessor();
7456                if target_is_data && !target_desc.writable && descriptor.writable {
7457                    return Err(self.type_error(format!(
7458                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7459                    )));
7460                }
7461                if !result_is_data && !target_is_data {
7462                    let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7463                        (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7464                        (Some(a), Some(b)) => a.same_value(b),
7465                        _ => false,
7466                    };
7467                    if !same(&target_desc.getter, &descriptor.getter)
7468                        || !same(&target_desc.setter, &descriptor.setter)
7469                    {
7470                        return Err(self.type_error(format!(
7471                            "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7472                        )));
7473                    }
7474                }
7475            }
7476        }
7477        Ok(Some(Some(descriptor)))
7478    }
7479
7480    /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7481    ///
7482    /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7483    /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7484    /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7485    /// for a data property. `Property` cannot express "this field is absent", so the whole
7486    /// property path is skipped and the descriptor is assembled here field by field.
7487    ///
7488    /// `current` is the property the trap reported, used only to tell a data property from
7489    /// an accessor.
7490    pub fn proxy_seal_property(
7491        &mut self,
7492        object: &Gc<JsObject>,
7493        key: &PropertyKey,
7494        frozen: bool,
7495        current: &Property,
7496    ) -> JsResult<bool> {
7497        let Some((_target, handler)) = self.proxy_parts(object)? else {
7498            return Err(self.type_error("not a proxy"));
7499        };
7500        let descriptor = self.new_object(None);
7501        descriptor.define_data("configurable", Value::Bool(false));
7502        if frozen && !current.is_accessor() {
7503            descriptor.define_data("writable", Value::Bool(false));
7504        }
7505        let key_value = self.key_value(key);
7506        let target = object
7507            .proxy_state()
7508            .and_then(|state| state.borrow().target.clone());
7509        let Some(target) = target else {
7510            return Err(self.type_error("cannot use a proxy that has been revoked"));
7511        };
7512        let Some(result) = self.proxy_trap(
7513            &handler,
7514            "defineProperty",
7515            vec![Value::Object(target), key_value, Value::Object(descriptor)],
7516        )?
7517        else {
7518            // No trap means the definition belongs to the target; `false` is its answer.
7519            return Ok(false);
7520        };
7521        Ok(result.to_boolean())
7522    }
7523
7524    /// `[[DefineOwnProperty]]` on a proxy.
7525    fn proxy_define_property(
7526        &mut self,
7527        object: &Gc<JsObject>,
7528        key: &PropertyKey,
7529        property: Property,
7530    ) -> JsResult<Option<bool>> {
7531        let Some((target, handler)) = self.proxy_parts(object)? else {
7532            return Ok(None);
7533        };
7534        let key_value = self.key_value(key);
7535        let descriptor = self.descriptor_from_property(&property);
7536        let Some(result) = self.proxy_trap(
7537            &handler,
7538            "defineProperty",
7539            vec![Value::Object(target.clone()), key_value, descriptor],
7540        )?
7541        else {
7542            // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7543            // going" answer and `object_define_own_property` turns it into exactly that
7544            // forwarding — see the note there. (Reading it as "not a proxy" would define
7545            // the property on the proxy object itself, whose table is empty and which no
7546            // read ever consults.)
7547            return Ok(None);
7548        };
7549        if !result.to_boolean() {
7550            return Ok(Some(false));
7551        }
7552        // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7553        // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7554        // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7555        // and treating them alike made four cases pass a descriptor the target contradicts.
7556        let target_desc = self.object_get_own_property(&target, key)?;
7557        let extensible = self.object_is_extensible(&target)?;
7558        let named = property
7559            .descriptor_fields
7560            .unwrap_or(crate::object::DescriptorFields {
7561                value: false,
7562                writable: false,
7563                enumerable: false,
7564                configurable: false,
7565                get: false,
7566                set: false,
7567            });
7568        if named.configurable && !property.configurable {
7569            let Some(target_desc) = &target_desc else {
7570                return Err(self.type_error(format!(
7571                    "proxy 'defineProperty' invented the non-configurable '{key}'"
7572                )));
7573            };
7574            if target_desc.configurable {
7575                return Err(self.type_error(format!(
7576                    "proxy 'defineProperty' made '{key}' non-configurable"
7577                )));
7578            }
7579        }
7580        // Step 11's other half: reporting that a property was made *configurable* needs a
7581        // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7582        // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7583        // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7584        // target`).
7585        if named.configurable
7586            && property.configurable
7587            && let Some(target_desc) = &target_desc
7588            && !target_desc.configurable
7589        {
7590            return Err(
7591                self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7592            );
7593        }
7594        // Step 12: a property cannot be reported *made writable* when the target's copy is
7595        // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7596        // the trap is allowed to claim a definition it did not perform, as long as the
7597        // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7598        // legal, and refusing it broke the commonest way to seed a proxy).
7599        if named.writable
7600            && property.writable
7601            && let Some(target_desc) = &target_desc
7602            && !target_desc.writable
7603        {
7604            return Err(self.type_error(format!(
7605                "proxy 'defineProperty' made the read-only '{key}' writable"
7606            )));
7607        }
7608        // Step 13: making a property read-only needs an existing read-only property.
7609        if named.writable
7610            && !property.writable
7611            && let Some(target_desc) = &target_desc
7612            && !target_desc.is_accessor()
7613            && target_desc.writable
7614        {
7615            return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7616        }
7617        // Step 14: a non-writable, non-configurable property's value is fixed.
7618        if named.value
7619            && let Some(target_desc) = &target_desc
7620            && !target_desc.is_accessor()
7621            && !target_desc.writable
7622            && !target_desc.configurable
7623        {
7624            let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7625            let reported = property.value.clone().unwrap_or(Value::Undefined);
7626            if !fixed_value.same_value(&reported) {
7627                return Err(self.type_error(format!(
7628                    "proxy 'defineProperty' changed the value of '{key}'"
7629                )));
7630            }
7631        }
7632        // Step 15: a non-extensible target cannot grow.
7633        if target_desc.is_none() && !extensible {
7634            return Err(self.type_error(format!(
7635                "proxy 'defineProperty' added '{key}' to a non-extensible target"
7636            )));
7637        }
7638        Ok(Some(true))
7639    }
7640
7641    /// `[[GetPrototypeOf]]` on a proxy.
7642    fn proxy_get_prototype_of(
7643        &mut self,
7644        object: &Gc<JsObject>,
7645    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7646        let Some((target, handler)) = self.proxy_parts(object)? else {
7647            return Ok(None);
7648        };
7649        let Some(result) = self.proxy_trap(
7650            &handler,
7651            "getPrototypeOf",
7652            vec![Value::Object(target.clone())],
7653        )?
7654        else {
7655            // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7656            // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7657            // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7658            // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7659            // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7660            return Ok(Some(self.object_prototype_of(&target)?));
7661        };
7662        let proto = match &result {
7663            Value::Null => None,
7664            Value::Object(proto) => Some(proto.clone()),
7665            _ => {
7666                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7667            }
7668        };
7669        if !self.object_is_extensible(&target)? {
7670            let actual = self.object_prototype_of(&target)?;
7671            if !same_proto(proto.as_ref(), actual.as_ref()) {
7672                return Err(self.type_error(
7673                    "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7674                ));
7675            }
7676        }
7677        Ok(Some(proto))
7678    }
7679
7680    /// `[[SetPrototypeOf]]` on a proxy.
7681    fn proxy_set_prototype_of(
7682        &mut self,
7683        object: &Gc<JsObject>,
7684        proto: Option<Gc<JsObject>>,
7685    ) -> JsResult<Option<bool>> {
7686        let Some((target, handler)) = self.proxy_parts(object)? else {
7687            return Ok(None);
7688        };
7689        let proto_value = match &proto {
7690            Some(proto) => Value::Object(proto.clone()),
7691            None => Value::Null,
7692        };
7693        let Some(result) = self.proxy_trap(
7694            &handler,
7695            "setPrototypeOf",
7696            vec![Value::Object(target.clone()), proto_value],
7697        )?
7698        else {
7699            // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7700            // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7701            // its stored prototype overwritten behind its back.
7702            return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7703        };
7704        if result.to_boolean()
7705            && !self.object_is_extensible(&target)?
7706            && !same_proto(
7707                Some(&proto).and_then(|p| p.clone()).as_ref(),
7708                self.object_prototype_of(&target)?.as_ref(),
7709            )
7710        {
7711            return Err(self.type_error(
7712                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7713            ));
7714        }
7715        Ok(Some(result.to_boolean()))
7716    }
7717
7718    /// `[[IsExtensible]]` on a proxy.
7719    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7720        let Some((target, handler)) = self.proxy_parts(object)? else {
7721            return Ok(None);
7722        };
7723        let Some(result) = self.proxy_trap(
7724            &handler,
7725            "isExtensible",
7726            vec![Value::Object(target.clone())],
7727        )?
7728        else {
7729            return Ok(Some(self.object_is_extensible(&target)?));
7730        };
7731        // The answer is not the proxy's to invent: it must agree with the target, or a
7732        // script could learn `false` while the target keeps accepting new properties.
7733        if result.to_boolean() != self.object_is_extensible(&target)? {
7734            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7735        }
7736        Ok(Some(result.to_boolean()))
7737    }
7738
7739    /// `[[PreventExtensions]]` on a proxy.
7740    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7741        let Some((target, handler)) = self.proxy_parts(object)? else {
7742            return Ok(None);
7743        };
7744        let Some(result) = self.proxy_trap(
7745            &handler,
7746            "preventExtensions",
7747            vec![Value::Object(target.clone())],
7748        )?
7749        else {
7750            // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7751            // its answer can be `false`.
7752            return Ok(Some(self.object_prevent_extensions(&target)?));
7753        };
7754        if result.to_boolean() && self.object_is_extensible(&target)? {
7755            return Err(self.type_error(
7756                "proxy 'preventExtensions' reported success but the target is still extensible",
7757            ));
7758        }
7759        Ok(Some(result.to_boolean()))
7760    }
7761
7762    /// `[[Call]]` on a proxy, through the `apply` trap.
7763    fn proxy_apply(
7764        &mut self,
7765        object: &Gc<JsObject>,
7766        this: Value,
7767        args: Vec<Value>,
7768    ) -> JsResult<Option<Value>> {
7769        let Some((target, handler)) = self.proxy_parts(object)? else {
7770            return Ok(None);
7771        };
7772        // The trap gets the arguments as one array, which is the shape the spec passes
7773        // and the shape `apply` traps are written against (`args[0]` is the first one).
7774        let arguments = self.new_array(args.clone());
7775        let this_for_trap = this.clone();
7776        let Some(result) = self.proxy_trap(
7777            &handler,
7778            "apply",
7779            vec![
7780                Value::Object(target.clone()),
7781                this_for_trap,
7782                Value::Object(arguments),
7783            ],
7784        )?
7785        else {
7786            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7787        };
7788        Ok(Some(result))
7789    }
7790
7791    /// `[[Construct]]` on a proxy, through the `construct` trap.
7792    fn proxy_construct(
7793        &mut self,
7794        object: &Gc<JsObject>,
7795        args: Vec<Value>,
7796        new_target: &Value,
7797    ) -> JsResult<Option<Value>> {
7798        let Some((target, handler)) = self.proxy_parts(object)? else {
7799            return Ok(None);
7800        };
7801        if !target.is_callable() {
7802            return Err(self.type_error("proxy target is not a constructor"));
7803        }
7804        let arguments = self.new_array(args.clone());
7805        let Some(result) = self.proxy_trap(
7806            &handler,
7807            "construct",
7808            vec![
7809                Value::Object(target.clone()),
7810                Value::Object(arguments),
7811                new_target.clone(),
7812            ],
7813        )?
7814        else {
7815            return Ok(Some(self.construct(
7816                Value::Object(target),
7817                new_target.clone(),
7818                args,
7819            )?));
7820        };
7821        if !matches!(result, Value::Object(_)) {
7822            return Err(self.type_error("proxy 'construct' must return an object"));
7823        }
7824        Ok(Some(result))
7825    }
7826
7827    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7828    pub(crate) fn has_own_or_inherited(
7829        &mut self,
7830        object: &Gc<JsObject>,
7831        key: &PropertyKey,
7832    ) -> JsResult<bool> {
7833        // The object itself first: it may be a proxy, and then the answer is its trap's.
7834        if let Some(answer) = self.proxy_has(object, key)? {
7835            return Ok(answer);
7836        }
7837        // An integer-indexed exotic object answers a canonical numeric index from
7838        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7839        // prototype chain. That is observable twice: a view the buffer has been resized
7840        // away from has no indices, so `2 in view` is `false` even when
7841        // `Object.getPrototypeOf(view)[2]` exists (what
7842        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7843        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7844        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7845        // goes through here, which is why the same rule is repeated in `has_property_key`
7846        // rather than living only there.
7847        if object.typed_array_parts().is_some()
7848            && let Some(numeric) = canonical_numeric_index(key)
7849        {
7850            return Ok(typed_array_index_is_valid(object, numeric));
7851        }
7852        // A host class answers `in` for its own keys, which may live nowhere in a property
7853        // table — `"x" in point` is true because the class says so, not because a property
7854        // exists.
7855        if let Some(exotic) = object.exotic()
7856            && let Some(answer) = exotic.has_property(self, object, key)?
7857        {
7858            return Ok(answer);
7859        }
7860        // `has_own` rather than `own_property_key`: an array's elements and its derived
7861        // `length` are invisible to the property table, and `Array.prototype` is an array.
7862        // A host class's `get_own_property` counts too, because the reference's
7863        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7864        // lives — a class with only `get_own_property` answers `in` through it.
7865        if self.exotic_has_own(object, key)? {
7866            return Ok(true);
7867        }
7868        // A hole is *not* the end of the search: the chain may still have the key, which
7869        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7870        for ancestor in object.chain() {
7871            // A proxy further up the chain answers for itself.
7872            if let Some(answer) = self.proxy_has(&ancestor, key)? {
7873                return Ok(answer);
7874            }
7875            // Same for a host class: a prototype may be one, and `in` reaches it.
7876            if let Some(exotic) = ancestor.exotic()
7877                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7878            {
7879                return Ok(answer);
7880            }
7881            if self.exotic_has_own(&ancestor, key)? {
7882                return Ok(true);
7883            }
7884        }
7885        Ok(false)
7886    }
7887
7888    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7889    /// trap included.
7890    ///
7891    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7892    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7893    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7894        if let Some(exotic) = object.exotic()
7895            && let Some(answer) = exotic.get_own_property(self, object, key)?
7896        {
7897            return Ok(answer.is_some());
7898        }
7899        Ok(has_own(object, key))
7900    }
7901
7902    /// `CreateListFromArrayLike`, optionally restricted to property keys.
7903    ///
7904    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7905    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7906    /// `TypeError` instead of a property named `"1.5"`.
7907    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7908        let object = self.object_from(value)?;
7909        let length = self
7910            .get_property(&object, "length")?
7911            .map(|value| value.to_number())
7912            .unwrap_or(0.0);
7913        if !length.is_finite() || length < 0.0 {
7914            return Err(self.type_error("invalid array-like length"));
7915        }
7916        let length = length as usize;
7917        let mut items = Vec::with_capacity(length.min(1024));
7918        for index in 0..length {
7919            let item = self
7920                .get_property(&object, &index.to_string())?
7921                .unwrap_or(Value::Undefined);
7922            if keys_only && matches!(&item, Value::Symbol(_)) {
7923                items.push(item);
7924                continue;
7925            }
7926            if keys_only && !matches!(&item, Value::String(_)) {
7927                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7928            }
7929            items.push(item);
7930        }
7931        Ok(items)
7932    }
7933
7934    /// A `Property` from the descriptor object a trap returned.
7935    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7936        let object = self.object_from(value)?;
7937        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7938            interp.get_property(&object, name)
7939        };
7940        let getter = field(self, "get")?;
7941        let setter = field(self, "set")?;
7942        let accessor = getter.is_some() || setter.is_some();
7943        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7944            Ok(interp
7945                .get_property(&object, name)?
7946                .is_some_and(|value| value.to_boolean()))
7947        };
7948        let enumerable = boolean(self, "enumerable")?;
7949        let configurable = boolean(self, "configurable")?;
7950        if accessor {
7951            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7952                return Err(
7953                    self.type_error("a descriptor cannot be both a data property and an accessor")
7954                );
7955            }
7956            Ok(Property {
7957                getter: getter.or(Some(Value::Undefined)),
7958                setter: setter.or(Some(Value::Undefined)),
7959                enumerable,
7960                configurable,
7961                writable: false,
7962                value: None,
7963                descriptor_fields: None,
7964            })
7965        } else {
7966            Ok(Property {
7967                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7968                writable: boolean(self, "writable")?,
7969                enumerable,
7970                configurable,
7971                getter: None,
7972                setter: None,
7973                descriptor_fields: None,
7974            })
7975        }
7976    }
7977
7978    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7979    fn descriptor_from_property(&mut self, property: &Property) -> Value {
7980        let object = self.new_object(None);
7981        // A partial descriptor names only some fields, and the trap must see exactly those:
7982        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7983        // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7984        // case, where every field is present.
7985        let fields = property.descriptor_fields;
7986        let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7987            fields.is_none_or(|fields| field(&fields))
7988        };
7989        if property.is_accessor() {
7990            let getter = property.getter.clone().unwrap_or(Value::Undefined);
7991            let setter = property.setter.clone().unwrap_or(Value::Undefined);
7992            object.define_data("get", getter);
7993            object.define_data("set", setter);
7994        } else {
7995            if names(|fields| fields.value) {
7996                let value = property.value.clone().unwrap_or(Value::Undefined);
7997                object.define_data("value", value);
7998            }
7999            if names(|fields| fields.writable) {
8000                object.define_data("writable", Value::Bool(property.writable));
8001            }
8002        }
8003        if names(|fields| fields.enumerable) {
8004            object.define_data("enumerable", Value::Bool(property.enumerable));
8005        }
8006        if names(|fields| fields.configurable) {
8007            object.define_data("configurable", Value::Bool(property.configurable));
8008        }
8009        Value::Object(object)
8010    }
8011
8012    // -- calling ------------------------------------------------------------
8013
8014    /// Call `callee` with `this` and `args`.
8015    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8016        let Value::Object(function) = &callee else {
8017            // `typeof x === "function"` is not enough to make `x()` legal: only a
8018            // callable object is. `null` and `undefined` need no special wording
8019            // here — their `ToString` already reads the way the reference's does.
8020            let what = format!("{} is not a function", callee.to_js_string());
8021            return Err(Signal::Throw(self.make_error("TypeError", &what)));
8022        };
8023        // A proxy of a function is called through its `apply` trap. It has no
8024        // `ObjectKind::Function` of its own, so this has to come before the dispatch
8025        // below, and a proxy of a non-function has nothing to forward to.
8026        if function.proxy_state().is_some() {
8027            return match self.proxy_apply(function, this, args)? {
8028                Some(result) => Ok(result),
8029                None => Err(Signal::Throw(
8030                    self.make_error("TypeError", "proxy target is not callable"),
8031                )),
8032            };
8033        }
8034        let callable = function.with(|data| match &data.kind {
8035            ObjectKind::Function(callable) => match callable {
8036                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8037                // The `Rc` is cloned out so the borrow of this object's data is released
8038                // before the closure runs: the closure may touch the same object.
8039                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8040                Callable::Bound {
8041                    target,
8042                    this,
8043                    args: leading,
8044                } => Some(NativeCall::Bound {
8045                    target: target.clone(),
8046                    this: this.clone(),
8047                    leading: leading.clone(),
8048                }),
8049                Callable::Bytecode { code, env } => {
8050                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
8051                }
8052                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8053                Callable::PromiseResolve(promise) => {
8054                    Some(NativeCall::PromiseResolve(promise.clone()))
8055                }
8056                Callable::PromiseReject(promise) => {
8057                    Some(NativeCall::PromiseReject(promise.clone()))
8058                }
8059                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8060                    state: state.clone(),
8061                }),
8062                Callable::ThenShim {
8063                    handler,
8064                    resolve,
8065                    reject,
8066                    fulfilled,
8067                } => Some(NativeCall::ThenShim {
8068                    handler: handler.clone(),
8069                    resolve: resolve.clone(),
8070                    reject: reject.clone(),
8071                    fulfilled: *fulfilled,
8072                }),
8073                Callable::AwaitResume {
8074                    coroutine,
8075                    promise,
8076                    kind,
8077                } => Some(NativeCall::AwaitResume {
8078                    coroutine: coroutine.clone(),
8079                    promise: promise.clone(),
8080                    kind: *kind,
8081                }),
8082                Callable::CombinatorSettle {
8083                    state,
8084                    index,
8085                    fulfilled,
8086                } => Some(NativeCall::CombinatorSettle {
8087                    state: state.clone(),
8088                    index: *index,
8089                    fulfilled: *fulfilled,
8090                }),
8091                Callable::FinallyShim {
8092                    callback,
8093                    fulfilled,
8094                    constructor,
8095                } => Some(NativeCall::FinallyShim {
8096                    callback: callback.clone(),
8097                    fulfilled: *fulfilled,
8098                    constructor: constructor.clone(),
8099                }),
8100                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8101                Callable::CompletedReturn {
8102                    generator,
8103                    promise,
8104                    rejected,
8105                } => Some(NativeCall::CompletedReturn {
8106                    generator: generator.clone(),
8107                    promise: promise.clone(),
8108                    rejected: *rejected,
8109                }),
8110                Callable::YieldResult {
8111                    generator,
8112                    promise,
8113                    done,
8114                } => Some(NativeCall::YieldResult {
8115                    generator: generator.clone(),
8116                    promise: promise.clone(),
8117                    done: *done,
8118                }),
8119                Callable::DisposeStep {
8120                    remaining,
8121                    promise,
8122                    error,
8123                    rejected,
8124                    awaited,
8125                    needs_await,
8126                } => Some(NativeCall::DisposeStep {
8127                    remaining: remaining.clone(),
8128                    promise: promise.clone(),
8129                    error: error.clone(),
8130                    rejected: *rejected,
8131                    awaited: *awaited,
8132                    needs_await: *needs_await,
8133                }),
8134                Callable::GeneratorResume {
8135                    generator,
8136                    promise,
8137                    kind,
8138                } => Some(NativeCall::GeneratorResume {
8139                    generator: generator.clone(),
8140                    promise: promise.clone(),
8141                    kind: *kind,
8142                }),
8143                Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8144                Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8145                Callable::SettlePromise {
8146                    promise,
8147                    value,
8148                    rejected,
8149                } => Some(NativeCall::SettlePromise {
8150                    promise: promise.clone(),
8151                    value: value.clone(),
8152                    rejected: *rejected,
8153                }),
8154            },
8155            _ => None,
8156        });
8157        match callable {
8158            Some(NativeCall::Host(func)) => {
8159                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8160                // function by name rather than stopping at the caller.
8161                let frame_less = function
8162                    .own_property("_frame_less")
8163                    .and_then(|property| property.value)
8164                    .is_some_and(|value| value.to_boolean());
8165                let outer = if frame_less {
8166                    None
8167                } else {
8168                    self.native_frames
8169                        .push((function.clone(), self.frames.len()));
8170                    Some(self.current_native.replace(function.clone()))
8171                };
8172                // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8173                // constructor reads it through `current_new_target` because it is handed
8174                // `undefined` for `this`. Taking the parked value here is what stops a
8175                // *plain* call made from inside a constructor body from seeing the
8176                // enclosing `new.target`.
8177                let parked = self.pending_new_target.take();
8178                let result = {
8179                    let outer_new_target = std::mem::replace(
8180                        &mut self.active_new_target,
8181                        parked.unwrap_or(Value::Undefined),
8182                    );
8183                    let result = {
8184                        let mut body = func.borrow_mut();
8185                        body(self, this, &args)
8186                    };
8187                    self.active_new_target = outer_new_target;
8188                    result
8189                };
8190                if !frame_less {
8191                    self.native_frames.pop();
8192                    self.current_native = outer.flatten();
8193                }
8194                result
8195            }
8196            Some(NativeCall::Native(func)) => {
8197                // A function marked `_frame_less` is one the reference implements
8198                // without a call frame — `eval` is the only one so far.
8199                let frame_less = function
8200                    .own_property("_frame_less")
8201                    .and_then(|property| property.value)
8202                    .is_some_and(|value| value.to_boolean());
8203                let outer = if frame_less {
8204                    None
8205                } else {
8206                    self.native_frames
8207                        .push((function.clone(), self.frames.len()));
8208                    Some(self.current_native.replace(function.clone()))
8209                };
8210                let parked = self.pending_new_target.take();
8211                let outer_new_target = std::mem::replace(
8212                    &mut self.active_new_target,
8213                    parked.unwrap_or(Value::Undefined),
8214                );
8215                let result = func(self, this, &args);
8216                self.active_new_target = outer_new_target;
8217                if !frame_less {
8218                    self.native_frames.pop();
8219                    self.current_native = outer.flatten();
8220                }
8221                result
8222            }
8223            Some(NativeCall::Revoker(slots)) => {
8224                // Idempotent: revoking twice answers `undefined` again rather than
8225                // complaining, which is what the spec says and what a `finally` block
8226                // relies on.
8227                let mut state = slots.borrow_mut();
8228                state.target = None;
8229                state.handler = None;
8230                Ok(Value::Undefined)
8231            }
8232            Some(NativeCall::PromiseResolve(promise)) => {
8233                // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8234                // else, so a resolve after a reject does nothing *and* a resolve after a
8235                // resolve-with-thenable does nothing — the promise is still `Pending` then,
8236                // because the adoption is a queued job.
8237                let value = args.first().cloned().unwrap_or(Value::Undefined);
8238                if !self.claim_resolution(&promise) {
8239                    return Ok(Value::Undefined);
8240                }
8241                // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8242                // the resolve function performs `RejectPromise` and returns `undefined`.
8243                // (`ResolvePromise` itself throws as well, so the engine's own callers see
8244                // it; only this wrapper swallows it.)
8245                let _ = self.resolve_promise_with(&promise, value);
8246                Ok(Value::Undefined)
8247            }
8248            Some(NativeCall::PromiseReject(promise)) => {
8249                let reason = args.first().cloned().unwrap_or(Value::Undefined);
8250                // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8251                if !self.claim_resolution(&promise) {
8252                    return Ok(Value::Undefined);
8253                }
8254                self.reject_promise(&promise, reason);
8255                Ok(Value::Undefined)
8256            }
8257            Some(NativeCall::ThenShim {
8258                handler,
8259                resolve,
8260                reject,
8261                fulfilled,
8262            }) => {
8263                // `PerformPromiseThen` with a capability: run the handler, then settle
8264                // through the capability's own pair. A throw from the handler is the
8265                // rejection, and a throw from the capability's `resolve` is not caught —
8266                // exactly the spec's `?`.
8267                let value = args.first().cloned().unwrap_or(Value::Undefined);
8268                match handler {
8269                    Some(handler) => {
8270                        match self.call_value(handler, Value::Undefined, vec![value]) {
8271                            Ok(result) => {
8272                                self.call_value(resolve, Value::Undefined, vec![result])?;
8273                            }
8274                            Err(Signal::Throw(reason)) => {
8275                                self.call_value(reject, Value::Undefined, vec![reason])?;
8276                            }
8277                            Err(signal) => return Err(signal),
8278                        }
8279                    }
8280                    None => {
8281                        let handler = if fulfilled { resolve } else { reject };
8282                        self.call_value(handler, Value::Undefined, vec![value])?;
8283                    }
8284                }
8285                Ok(Value::Undefined)
8286            }
8287            Some(NativeCall::CapabilityExecutor { state }) => {
8288                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8289                // slot holds a value yet. The test is on the *values*, not on a call count —
8290                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8291                // called-twice`'s first case does exactly that), while a second call after a
8292                // real pair is the `TypeError`.
8293                let defined = |name: &str| {
8294                    state
8295                        .own_property(name)
8296                        .and_then(|property| property.value)
8297                        .is_some_and(|value| !matches!(value, Value::Undefined))
8298                };
8299                if defined("resolve") || defined("reject") {
8300                    return Err(self.type_error("promise capability executor called twice"));
8301                }
8302                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8303                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8304                state.define_data("resolve", resolve);
8305                state.define_data("reject", reject);
8306                Ok(Value::Undefined)
8307            }
8308            Some(NativeCall::CombinatorSettle {
8309                state,
8310                index,
8311                fulfilled,
8312            }) => {
8313                let value = args.first().cloned().unwrap_or(Value::Undefined);
8314                self.settle_combinator(&state, index, fulfilled, value)?;
8315                Ok(Value::Undefined)
8316            }
8317            Some(NativeCall::AwaitResume {
8318                coroutine,
8319                promise,
8320                kind,
8321            }) => {
8322                // Resume *inline*, in the reaction that delivered the value. Deferring it
8323                // by another job inserts a tick between every `await` and its
8324                // continuation, which reorders `await` against unrelated `then` chains —
8325                // `f().then(g)` then runs before `f`'s own next statement.
8326                self.drive_async(
8327                    &coroutine,
8328                    &promise,
8329                    kind,
8330                    args.first().cloned().unwrap_or(Value::Undefined),
8331                )
8332                .map(|()| Value::Undefined)
8333            }
8334            Some(NativeCall::ReturnValue(value)) => Ok(value),
8335            Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8336            Some(NativeCall::FinallyShim {
8337                callback,
8338                fulfilled,
8339                constructor,
8340            }) => {
8341                // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8342                // own value is discarded; what the caller sees is the *original* outcome,
8343                // delayed until `PromiseResolve(C, result)` has settled.
8344                //
8345                // Two details are observable and both have a test:
8346                //
8347                // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8348                //   `PerformPromiseThen`. A callback that returns a thenable with its own
8349                //   `then` must have that `then` called
8350                //   (`resolved-observable-then-calls` counts it);
8351                // * only the **fulfil** handler is supplied. A returned promise that
8352                //   *rejects* rejects the whole `finally`, rather than having its failure
8353                //   swallowed and the original value passed through.
8354                let original = args.first().cloned().unwrap_or(Value::Undefined);
8355                let result = match &callback {
8356                    Some(callback) => {
8357                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8358                    }
8359                    None => Value::Undefined,
8360                };
8361                // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8362                // constructor is reused rather than rewrapped, which is what keeps
8363                // `mp1.finally(() => mp2)` from gaining a layer.
8364                let resolved = self.promise_resolve_for(&constructor, result)?;
8365                let thunk = if fulfilled {
8366                    Callable::ReturnValue(original)
8367                } else {
8368                    Callable::ThrowValue(original)
8369                };
8370                // `length: 0` and `name: ""`, and **not** a constructor — the three things
8371                // `resolved-observable-then-calls-argument` reads off the thunk while it has
8372                // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8373                // function with no `length` at all.
8374                let thunk = self.builtin_function("", 0, thunk);
8375                let then = self.read_field(&resolved, "then")?;
8376                if !matches!(&then, Value::Object(object) if object.is_callable()) {
8377                    return Err(self.type_error("then is not a function"));
8378                }
8379                self.call_value(then, resolved, vec![Value::Object(thunk)])
8380            }
8381            Some(NativeCall::DisposeStep {
8382                remaining,
8383                promise,
8384                error,
8385                rejected,
8386                awaited,
8387                needs_await,
8388            }) => {
8389                let error = if rejected {
8390                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
8391                    self.merge_dispose_error(reason, error)
8392                } else {
8393                    error
8394                };
8395                self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8396                Ok(Value::Undefined)
8397            }
8398            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
8399            Some(NativeCall::CompletedReturn {
8400                generator,
8401                promise,
8402                rejected,
8403            }) => {
8404                let value = args.first().cloned().unwrap_or(Value::Undefined);
8405                let outcome = if rejected {
8406                    AsyncOutcome::Error(value)
8407                } else {
8408                    AsyncOutcome::Value(self.iterator_result(value, true)?)
8409                };
8410                self.settle_async_request(&generator, &promise, outcome)?;
8411                Ok(Value::Undefined)
8412            }
8413            Some(NativeCall::YieldResult {
8414                generator,
8415                promise,
8416                done,
8417            }) => {
8418                let value = args.first().cloned().unwrap_or(Value::Undefined);
8419                let result = self.iterator_result(value, done)?;
8420                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8421                Ok(Value::Undefined)
8422            }
8423            Some(NativeCall::GeneratorResume {
8424                generator,
8425                promise,
8426                kind,
8427            }) => {
8428                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8429                // tick and reorders the generator against other chains.
8430                self.step_async_generator(
8431                    &generator,
8432                    &promise,
8433                    kind,
8434                    args.first().cloned().unwrap_or(Value::Undefined),
8435                )
8436                .map(|()| Value::Undefined)
8437            }
8438            Some(NativeCall::SettlePromise {
8439                promise,
8440                value,
8441                rejected,
8442            }) => {
8443                if rejected {
8444                    self.reject_promise(&promise, value);
8445                } else {
8446                    self.fulfill_promise(&promise, value);
8447                }
8448                Ok(Value::Undefined)
8449            }
8450            Some(NativeCall::Bound {
8451                target,
8452                this: bound_this,
8453                leading,
8454            }) => {
8455                let mut all = leading;
8456                all.extend(args);
8457                self.call_value(target, bound_this, all)
8458            }
8459            Some(NativeCall::Bytecode(code, env)) => {
8460                if code.code.kind.is_generator() {
8461                    return self.new_generator(callee, this, args);
8462                }
8463                if code.code.kind.is_async() {
8464                    // Same coroutine machinery as a generator; the difference is only in
8465                    // what the completion does — see `new_async_function`.
8466                    return self.new_async_function(callee, this, args);
8467                }
8468                self.execute(code, env, this, args, callee)
8469            }
8470            None => Err(Signal::Throw(
8471                self.make_error("TypeError", "not a function"),
8472            )),
8473        }
8474    }
8475
8476    /// Give a freshly built function its own `prototype` object.
8477    ///
8478    /// Every function that can be used with `new` carries one, and its
8479    /// `constructor` points back at the function — a reference cycle, which is
8480    /// exactly what the collector's cycle pass exists to reclaim.
8481    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8482        self.install_function_prototype_with(function, None);
8483    }
8484
8485    /// [`Interp::install_function_prototype`] with an explicit parent for the new
8486    /// `prototype` object.
8487    ///
8488    /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8489    /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8490    /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8491    /// `None` means `%Object.prototype%`.
8492    fn install_function_prototype_with(
8493        &mut self,
8494        function: &Gc<JsObject>,
8495        parent: Option<Gc<JsObject>>,
8496    ) {
8497        let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8498        let prototype = self.new_object(Some(parent));
8499        let constructor = Value::Object(function.clone());
8500        prototype.define(
8501            "constructor",
8502            Property::with_attributes(constructor, true, false),
8503        );
8504        let value = Value::Object(prototype);
8505        function.define("prototype", Property::prototype_of(value, true));
8506    }
8507
8508    /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8509    /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8510    /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8511    ///
8512    /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8513    /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8514    /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8515    /// is `[]` there.
8516    fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8517        let prototype = self.new_object(Some(parent));
8518        let value = Value::Object(prototype);
8519        function.define("prototype", Property::prototype_of(value, true));
8520    }
8521
8522    /// The `[[Prototype]]` a newly created generator object gets:
8523    /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8524    ///
8525    /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8526    /// function's `prototype` is writable, so a script can replace it with anything, and
8527    /// only an *object* is consulted.
8528    fn generator_instance_proto(
8529        &mut self,
8530        function: &Gc<JsObject>,
8531        default: Gc<JsObject>,
8532    ) -> JsResult<Gc<JsObject>> {
8533        match self.get_property(function, "prototype")? {
8534            Some(Value::Object(prototype)) => Ok(prototype),
8535            _ => Ok(default),
8536        }
8537    }
8538
8539    /// A getter or setter that reads or writes the reference cell behind a mapped
8540    /// `arguments` index.
8541    ///
8542    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8543    /// count — which is what the collector treats as "a reference from outside the
8544    /// heap". The closure therefore keeps the cell alive for exactly as long as the
8545    /// accessor is reachable, which is the same lifetime the arguments object has.
8546    ///
8547    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8548    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8549    /// parameter value and the arguments object reaches the closure, never the other
8550    /// way round. Nothing the collector has to see is hidden.
8551    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8552        let name = if is_setter { "set" } else { "get" };
8553        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8554            if is_setter {
8555                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8556                Ok(Value::Undefined)
8557            } else {
8558                Ok(cell.get())
8559            }
8560        };
8561        self.new_host_function(name, 1, Box::new(func))
8562    }
8563
8564    /// The object `special_object` builds.
8565    ///
8566    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8567    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8568    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8569    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8570    /// write through `arguments` does not reach the parameter.
8571    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8572        match magic {
8573            0 | 1 => {
8574                let args = self.frame().passed().to_vec();
8575                let proto = self.realm.object_proto.clone();
8576                let object = self.new_object(Some(proto));
8577                // The marker `Object.prototype.toString` needs: an arguments object is an
8578                // ordinary object apart from reporting `[object Arguments]`, and that has
8579                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8580                // show up ahead of them in a key listing anyway — it is non-enumerable.
8581                self.internal_set(&object, "_class", self.string("Arguments"));
8582                // `length` is writable and configurable but neither enumerable nor a
8583                // plain data property: `Object.keys(arguments)` lists the indices only,
8584                // which is how `{...arguments}` copies them without the length.
8585                object.define(
8586                    "length",
8587                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
8588                );
8589                // `magic == 1` is sloppy mode, where each index is *mapped* to the
8590                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8591                // change `a`, and assigning `a` has to change `arguments[0]`.
8592                //
8593                // The shared storage is the parameter's reference cell. The compiler
8594                // gives every parameter of such a function one (see
8595                // `provide_body_arguments`), and the cell outlives the frame, so this
8596                // keeps working after the arguments object escapes.
8597                //
8598                // The index becomes an accessor rather than a data property. A mapped
8599                // index reports as a plain writable/enumerable data property through
8600                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8601                // the getter/setter pair is only the plumbing underneath.
8602                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8603                    let frame = self.frame();
8604                    frame
8605                        .code
8606                        .arg_cell
8607                        .iter()
8608                        .map(|cell| {
8609                            (*cell >= 0)
8610                                .then(|| frame.cells.get(*cell as usize).cloned())
8611                                .flatten()
8612                        })
8613                        .collect()
8614                } else {
8615                    Vec::new()
8616                };
8617                // Tell the object which indices are mapped, so
8618                // `Object.getOwnPropertyDescriptor` can report them as the data
8619                // properties the spec describes instead of the accessors that
8620                // implement the aliasing.
8621                if magic == 1 {
8622                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8623                    for cell in &mapped_cells {
8624                        table.push(cell.clone());
8625                    }
8626                    object.set_mapped_arguments(table);
8627                }
8628                for (index, value) in args.into_iter().enumerate() {
8629                    match mapped_cells.get(index).cloned().flatten() {
8630                        Some(cell) => {
8631                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8632                            let setter = self.new_mapped_arguments_accessor(cell, true);
8633                            object.define(
8634                                &index.to_string(),
8635                                Property::accessor_with(
8636                                    Some(Value::Object(getter)),
8637                                    Some(Value::Object(setter)),
8638                                    true,
8639                                ),
8640                            );
8641                        }
8642                        None => object.define_data(&index.to_string(), value),
8643                    }
8644                }
8645                // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8646                // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8647                // non-enumerable and non-configurable. It is not a nicety — it is the only
8648                // documented way to reach `%ThrowTypeError%`:
8649                //
8650                //     Object.getOwnPropertyDescriptor(function(){"use strict";
8651                //         return arguments;}(), "callee").get
8652                //
8653                // and the whole `ThrowTypeError/` directory is written against that
8654                // expression. Without it 13 cases failed with `cannot read property 'get'
8655                // of undefined`, which reads like a test harness bug rather than a missing
8656                // accessor.
8657                //
8658                // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8659                // writable data property holding the function being called, and
8660                // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8661                // `hasOwnProperty("callee")` hold there.
8662                if magic == 1 {
8663                    let callee = self.frame().callee.clone();
8664                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8665                    object.define("callee", Property::with_attributes(callee, true, false));
8666                } else if let Some(thrower) = self.realm.throw_type_error.clone()
8667                    && object.own_property("callee").is_none()
8668                {
8669                    object.define(
8670                        "callee",
8671                        Property {
8672                            getter: Some(Value::Object(thrower.clone())),
8673                            setter: Some(Value::Object(thrower)),
8674                            enumerable: false,
8675                            configurable: false,
8676                            ..Property::default()
8677                        },
8678                    );
8679                }
8680                // An arguments object is iterable: `[...arguments]` and
8681                // `for (const a of arguments)` both work, through the *array* iterator
8682                // because the object is array-like. Without this the whole spread form
8683                // reported "not iterable".
8684                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8685                let values = self
8686                    .realm
8687                    .array_proto
8688                    .own_property("values")
8689                    .and_then(|property| property.value);
8690                if let Some(values) = values {
8691                    object.define_key(
8692                        &iterator_key,
8693                        Property::with_attributes(values, true, false),
8694                    );
8695                }
8696                Ok(Value::Object(object))
8697            }
8698            // `this.active_func`: the constructor `super()` resolves against.
8699            //
8700            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8701            // own, so it inherits this from the function it was written in along with `this`
8702            // — and that is a lexical relationship, not a stack one: an arrow that escaped
8703            // the constructor and is called back later (`iter.return = () => super()`) has
8704            // the constructor nowhere on the stack. The compiler therefore reads it out of
8705            // a closure variable of the enclosing function, exactly as the reference does
8706            // with its `this_active_func` local.
8707            2 => Ok(self
8708                .current_callee()
8709                .map_or(Value::Undefined, Value::Object)),
8710            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8711            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8712            // its own either, so the lookup walks out to the nearest non-arrow frame for
8713            // the same reason as `this.active_func` above — without that, `super()` inside
8714            // an arrow passed `undefined` as the new target and the parent constructor was
8715            // then rejected for being invoked without `new`.
8716            3 => Ok(self
8717                .eval_new_target
8718                .clone()
8719                .unwrap_or_else(|| self.frame().new_target.clone())),
8720            // `[[HomeObject]]` of the function being run: what `super` is relative to.
8721            // An arrow has none of its own, so the lookup walks out to the enclosing
8722            // method — which is why `super` works inside an arrow inside a method.
8723            4 => Ok(self
8724                .frames
8725                .iter()
8726                .rev()
8727                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8728                .map_or(Value::Undefined, Value::Object)),
8729            // `import.meta`: the innermost module body's meta object. Outside a module
8730            // the compiler never emits this, so an empty fallback is unreachable rather
8731            // than permissive.
8732            6 => {
8733                let name = self.module_stack.last().cloned();
8734                let meta = name
8735                    .and_then(|name| self.modules.get(&name).cloned())
8736                    .and_then(|module| module.with(|r| r.import_meta.clone()));
8737                Ok(meta.map_or(Value::Undefined, Value::Object))
8738            }
8739            other => Err(Signal::Throw(self.make_error(
8740                "InternalError",
8741                &format!("special_object {other} is not implemented yet"),
8742            ))),
8743        }
8744    }
8745
8746    /// `[[HomeObject]]` of the innermost function that has one, if any.
8747    ///
8748    /// An arrow has none, so the search walks out to the enclosing method — the same
8749    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8750    /// inside a method.
8751    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8752        self.frames
8753            .iter()
8754            .rev()
8755            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8756    }
8757
8758    /// The dispose method a `using` declaration should snapshot, or an error.
8759    ///
8760    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8761    /// is what makes a resource that only knows the synchronous protocol usable in both
8762    /// forms.
8763    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8764        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8765        if value.is_nullish() {
8766            return Ok(Value::Undefined);
8767        }
8768        let Some(object) = value.as_object() else {
8769            return Err(self.type_error("not an object"));
8770        };
8771        let mut method = if await_form {
8772            let found = self.get_property_key(
8773                object,
8774                &self.realm.well_known_key(WellKnown::AsyncDisposable),
8775            )?;
8776            match found {
8777                Some(found) if !found.is_nullish() => Some(found),
8778                _ => self
8779                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8780            }
8781        } else {
8782            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8783        };
8784        let Some(found) = method.take() else {
8785            return Err(self.type_error("value is not disposable"));
8786        };
8787        if found.is_nullish() {
8788            return Err(self.type_error("value is not disposable"));
8789        }
8790        let callable = found.as_object().is_some_and(|object| object.is_callable());
8791        if !callable {
8792            return Err(self.type_error("dispose method is not a function"));
8793        }
8794        Ok(found)
8795    }
8796
8797    /// Call one resource's disposer, folding a failure into `error_state`.
8798    ///
8799    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8800    /// because a captured `using` binding lives in its reference cell and the local slot is
8801    /// stale — a closure over the resource is legal and must not change what is disposed.
8802    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8803        let value = self.get_loc(slot);
8804        let method = self.get_loc(slot + 1);
8805        // A resource that was never initialised — its declaration threw — or that is
8806        // `null`/`undefined` has nothing to dispose.
8807        if value.is_nullish() || matches!(value, Value::Uninitialized) {
8808            return Ok(error_state);
8809        }
8810        if matches!(method, Value::Undefined | Value::Uninitialized) {
8811            return Ok(error_state);
8812        }
8813        match self.call_value(method, value, Vec::new()) {
8814            Ok(_) => Ok(error_state),
8815            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8816            Err(other) => Err(other),
8817        }
8818    }
8819
8820    /// Combine a disposal failure with whatever was already going wrong.
8821    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8822        if matches!(error_state, Value::Uninitialized) {
8823            return new_error;
8824        }
8825        self.new_suppressed_error(new_error, error_state)
8826    }
8827
8828    /// A `SuppressedError` instance built straight from its prototype.
8829    ///
8830    /// Not through the constructor: a script that rewrites
8831    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8832    /// error wrapping.
8833    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8834        let proto = self
8835            .realm
8836            .suppressed_error_proto
8837            .clone()
8838            .unwrap_or_else(|| self.realm.error_proto.clone());
8839        let object = self.new_object(Some(proto));
8840        object.define("error", Property::with_attributes(error, true, true));
8841        object.define(
8842            "suppressed",
8843            Property::with_attributes(suppressed, true, true),
8844        );
8845        object.define(
8846            "message",
8847            Property::with_attributes(self.string("SuppressedError"), true, true),
8848        );
8849        self.internal_set(&object, "_class", self.string("Error"));
8850        self.add_stack(&object);
8851        Value::Object(object)
8852    }
8853
8854    /// Call `callee`, or push its frame and let the main loop run it.
8855    ///
8856    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8857    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8858    /// continues, so `function f(){ return f() }` costs heap and stops at
8859    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8860    /// is entered directly, and natives do not re-enter JavaScript in this
8861    /// milestone.
8862    ///
8863    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8864    /// because the returning frame will.
8865    /// The elements of an array-like value, as a call argument list.
8866    ///
8867    /// `apply` accepts any array-like, not only a real array: the reference reads
8868    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8869    /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8870    ///
8871    /// Used by the paths that take a *length* from script data — the typed-array
8872    /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8873    /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8874    /// `RangeError` rather than a silently clamped count.
8875    pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8876        let number = self.to_js_number(value)?;
8877        if number.is_nan() {
8878            return Ok(0);
8879        }
8880        let number = number.trunc();
8881        if number < 0.0 || number > 9_007_199_254_740_991.0 {
8882            return Err(self.range_error("invalid length"));
8883        }
8884        Ok(number as usize)
8885    }
8886
8887    /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8888    /// other callers that take an argument list from script data.
8889    ///
8890    /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8891    /// constructor and `Array.from` need `ToIndex` instead (see
8892    /// [`Interp::to_index`]), which is why they do not go through here.
8893    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8894        let Some(object) = value.as_object().cloned() else {
8895            if value.is_nullish() {
8896                // `f.apply(this, null)` passes no arguments at all.
8897                return Ok(Vec::new());
8898            }
8899            return Err(self.type_error("createListFromArrayLike called on non-object"));
8900        };
8901        let length = match self.get_property(&object, "length")? {
8902            Some(length) => length.to_number(),
8903            None => 0.0,
8904        };
8905        if !length.is_finite() || length <= 0.0 {
8906            return Ok(Vec::new());
8907        }
8908        let length = (length as usize).min(1_000_000);
8909        let mut args = Vec::with_capacity(length);
8910        for index in 0..length {
8911            let element = self.get_property(&object, &index.to_string())?;
8912            args.push(element.unwrap_or(Value::Undefined));
8913        }
8914        Ok(args)
8915    }
8916
8917    /// Turn a call to a generator function into a generator object.
8918    ///
8919    /// The frame is built exactly as an ordinary call would build it, then detached and
8920    /// stored in the generator before any body instruction runs — which is what makes
8921    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8922    /// is `initial_yield`, the first instruction of every suspending body.
8923    pub fn new_generator(
8924        &mut self,
8925        function: Value,
8926        this: Value,
8927        args: Vec<Value>,
8928    ) -> JsResult<Value> {
8929        let Some(object) = function.as_object().cloned() else {
8930            return Err(self.type_error("not a generator function"));
8931        };
8932        let Some((code, env)) = bytecode_of(&object) else {
8933            return Err(self.type_error("not a generator function"));
8934        };
8935        let is_async = code.code.kind.is_async();
8936        self.push_frame(code, env, this, args, function)?;
8937        let frame = self.frames.pop().expect("push_frame just pushed it");
8938        // A fresh generator is *suspended at start*: the body has not run, so a
8939        // `return`/`throw` on it finishes without executing anything.
8940        let mut state = GeneratorState {
8941            frame: Some(frame),
8942            phase: GeneratorPhase::SuspendedStart,
8943            parked_on_await: false,
8944            parked_on_yield_star: false,
8945            requests: std::collections::VecDeque::new(),
8946            async_busy: false,
8947            is_async,
8948        };
8949        // Run to the first suspension. For a generator that is `initial_yield`, so no
8950        // body code runs; for a malformed body it would be the first `yield`.
8951        // An `async function*` answers an async generator: same coroutine, but its
8952        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8953        let default_proto = if is_async {
8954            self.realm
8955                .async_generator_proto
8956                .clone()
8957                .unwrap_or_else(|| self.realm.generator_proto.clone())
8958        } else {
8959            self.realm.generator_proto.clone()
8960        };
8961        // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8962        // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8963        // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8964        // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8965        let proto = self.generator_instance_proto(&object, default_proto)?;
8966        let generator = self.new_object(Some(proto));
8967        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8968            Ok(_) => {}
8969            Err(error) => return Err(error),
8970        }
8971        generator.with_mut(|data| {
8972            data.kind = ObjectKind::Generator(Box::new(state));
8973        });
8974        Ok(Value::Object(generator))
8975    }
8976
8977    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8978    ///
8979    /// Returns the `{value, done}` object itself rather than the pair, because a
8980    /// `yield*` suspension already has one — the inner iterator's own result — and the
8981    /// protocol says to hand that straight through rather than nest it.
8982    /// Advance a generator and report *why* it parked.
8983    ///
8984    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8985    /// "hand this value to the caller" — but an async generator does: an `await` has to
8986    /// settle before it can answer, while a `yield` is the answer.
8987    fn resume_generator_detailed(
8988        &mut self,
8989        generator: &Gc<JsObject>,
8990        kind: ResumeKind,
8991        value: Value,
8992    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8993        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8994            ObjectKind::Generator(state) => {
8995                let is_async = state.is_async;
8996                Some(std::mem::replace(
8997                    state.as_mut(),
8998                    GeneratorState {
8999                        frame: None,
9000                        phase: GeneratorPhase::Executing,
9001                        parked_on_await: false,
9002                        parked_on_yield_star: false,
9003                        requests: std::collections::VecDeque::new(),
9004                        // **Busy while the body runs**, so a `next()` called *from inside*
9005                        // the body queues instead of being served. §27.6.3.7
9006                        // `AsyncGeneratorResumeNext` returns immediately for the state
9007                        // "executing", and the request is served once the body suspends;
9008                        // with `false` here the re-entrant call found an empty frame and
9009                        // rejected (`request-queue-order-state-executing`).
9010                        async_busy: is_async,
9011                        is_async,
9012                    },
9013                ))
9014            }
9015            _ => None,
9016        }) else {
9017            return Err(self.type_error("not a generator"));
9018        };
9019        let result = self.step_generator(&mut state, kind, value);
9020        // Requests queued *while* the body ran live on the placeholder, because the real
9021        // state is out of the object for the duration. They have to be folded back in
9022        // before the placeholder is overwritten, or the promise they carry never settles.
9023        let queued = generator.with_mut(|data| match &mut data.kind {
9024            ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9025            _ => std::collections::VecDeque::new(),
9026        });
9027        state.requests.extend(queued);
9028        generator.with_mut(|data| {
9029            data.kind = ObjectKind::Generator(Box::new(state));
9030        });
9031        result
9032    }
9033
9034    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9035    ///
9036    /// Returns the `{value, done}` object itself rather than the pair, because a
9037    /// `yield*` suspension already has one — the inner iterator's own result — and the
9038    /// protocol says to hand that straight through rather than nest it.
9039    pub fn resume_generator(
9040        &mut self,
9041        generator: &Gc<JsObject>,
9042        kind: ResumeKind,
9043        value: Value,
9044    ) -> JsResult<Value> {
9045        let (value, done, ready, _reason) =
9046            self.resume_generator_detailed(generator, kind, value)?;
9047        if ready {
9048            return Ok(value);
9049        }
9050        self.iterator_result(value, done)
9051    }
9052
9053    /// `next`/`return`/`throw` on an async generator, which answer a promise.
9054    ///
9055    /// The body is the same coroutine a sync generator runs; what changes is that an
9056    /// `await` inside it has to settle before the method can answer, so the step is
9057    /// driven off the job queue rather than returning inline.
9058    pub fn resume_async_generator(
9059        &mut self,
9060        generator: &Gc<JsObject>,
9061        kind: ResumeKind,
9062        value: Value,
9063    ) -> JsResult<Value> {
9064        let promise = self.new_promise();
9065        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9066        // that order, and the second value must reach the *second* `yield`.
9067        let idle = generator.with_mut(|data| match &mut data.kind {
9068            ObjectKind::Generator(state) => {
9069                state.requests.push_back(AsyncRequest {
9070                    kind,
9071                    value,
9072                    promise: promise.clone(),
9073                });
9074                !state.async_busy
9075            }
9076            _ => false,
9077        });
9078        if idle {
9079            self.next_async_request(generator)?;
9080        }
9081        Ok(Value::Object(promise))
9082    }
9083
9084    /// Serve the front queued request, if the generator is free to run one.
9085    ///
9086    /// A finished generator answers from the queue without running anything:
9087    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9088    /// first, and `throw(e)` rejects.
9089    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9090        enum Front {
9091            Idle,
9092            Run(ResumeKind, Value, Gc<JsObject>),
9093            Finished(ResumeKind, Value, Gc<JsObject>),
9094        }
9095        let front = generator.with_mut(|data| match &mut data.kind {
9096            ObjectKind::Generator(state) => {
9097                let Some(request) = state.requests.front() else {
9098                    return Front::Idle;
9099                };
9100                // Busy means a request is still in flight — awaiting inside the body, not
9101                // finished. Serving another now would interleave two requests.
9102                if state.async_busy && state.phase != GeneratorPhase::Completed {
9103                    return Front::Idle;
9104                }
9105                let kind = request.kind;
9106                let value = request.value.clone();
9107                let promise = request.promise.clone();
9108                state.async_busy = true;
9109                if state.phase == GeneratorPhase::Completed {
9110                    Front::Finished(kind, value, promise)
9111                } else {
9112                    Front::Run(kind, value, promise)
9113                }
9114            }
9115            _ => Front::Idle,
9116        });
9117        match front {
9118            Front::Idle => Ok(()),
9119            Front::Run(kind, value, promise) => {
9120                self.step_async_generator(generator, &promise, kind, value)
9121            }
9122            Front::Finished(kind, value, promise) => match kind {
9123                ResumeKind::Throw => {
9124                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9125                }
9126                ResumeKind::Next | ResumeKind::Start => {
9127                    let result = self.iterator_result(Value::Undefined, true)?;
9128                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9129                }
9130                ResumeKind::Return => {
9131                    // `js_async_generator_completed_return`: the value is awaited before it
9132                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9133                    // finished generator answers `1`, not a promise.
9134                    let resolved = match self.promise_resolve_intrinsic(value) {
9135                        Ok(resolved) => resolved,
9136                        Err(Signal::Throw(reason)) => {
9137                            return self.settle_async_request(
9138                                generator,
9139                                &promise,
9140                                AsyncOutcome::Error(reason),
9141                            );
9142                        }
9143                        Err(other) => return Err(other),
9144                    };
9145                    let done = JsObject::function(
9146                        self.heap,
9147                        Some(self.realm.function_proto.clone()),
9148                        Callable::CompletedReturn {
9149                            generator: generator.clone(),
9150                            promise: promise.clone(),
9151                            rejected: false,
9152                        },
9153                    );
9154                    let failed = JsObject::function(
9155                        self.heap,
9156                        Some(self.realm.function_proto.clone()),
9157                        Callable::CompletedReturn {
9158                            generator: generator.clone(),
9159                            promise: promise.clone(),
9160                            rejected: true,
9161                        },
9162                    );
9163                    let Value::Object(resolved) = resolved else {
9164                        return self.settle_async_request(
9165                            generator,
9166                            &promise,
9167                            AsyncOutcome::Error(Value::Undefined),
9168                        );
9169                    };
9170                    self.perform_then(
9171                        &resolved,
9172                        Some(Value::Object(done)),
9173                        Some(Value::Object(failed)),
9174                    )?;
9175                    Ok(())
9176                }
9177            },
9178        }
9179    }
9180
9181    /// Settle the front request and start the next one.
9182    ///
9183    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9184    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9185    /// generator would strand every later request.
9186    fn settle_async_request(
9187        &mut self,
9188        generator: &Gc<JsObject>,
9189        promise: &Gc<JsObject>,
9190        outcome: AsyncOutcome,
9191    ) -> JsResult<()> {
9192        let settled = generator.with_mut(|data| match &mut data.kind {
9193            ObjectKind::Generator(state) => {
9194                let front = state.requests.front();
9195                debug_assert!(
9196                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9197                    "a request settled outside its turn"
9198                );
9199                state.requests.pop_front();
9200                state.async_busy = false;
9201                true
9202            }
9203            _ => false,
9204        });
9205        if settled {
9206            match outcome {
9207                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9208                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9209            }
9210        }
9211        self.next_async_request(generator)
9212    }
9213
9214    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9215    ///
9216    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9217    /// disposer runs **synchronously** — the reference starts it before returning, which
9218    /// a test can observe by logging after the call — and the rest follow once their
9219    /// predecessor settles.
9220    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9221        let promise = self.new_promise();
9222        // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9223        // any resource at all, because every `await using` resource has the async-dispose
9224        // hint — including the null/undefined ones that have nothing to call. If none of them
9225        // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9226        // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9227        // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9228        let needs_await = !resources.is_empty();
9229        let mut pairs = Vec::with_capacity(resources.len());
9230        for (value, method) in resources {
9231            let pair = self.new_array(vec![value, method]);
9232            pairs.push(Value::Object(pair));
9233        }
9234        let remaining = self.new_array(pairs);
9235        self.dispose_step(
9236            &remaining,
9237            &promise,
9238            Value::Uninitialized,
9239            false,
9240            needs_await,
9241        )?;
9242        Ok(Value::Object(promise))
9243    }
9244
9245    /// One link of the `disposeAsync` chain.
9246    ///
9247    /// Loops while the disposers finish synchronously, and parks on the first thenable it
9248    /// meets — pushing itself back in as the continuation, with the accumulated error
9249    /// carried along so a later failure can still be folded into the `SuppressedError`.
9250    fn dispose_step(
9251        &mut self,
9252        remaining: &Gc<JsObject>,
9253        promise: &Gc<JsObject>,
9254        mut error: Value,
9255        awaited: bool,
9256        needs_await: bool,
9257    ) -> JsResult<()> {
9258        loop {
9259            let length = remaining.array_length().unwrap_or(0);
9260            if length == 0 {
9261                // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9262                // still has to happen. Re-entering this same step past an already-fulfilled
9263                // promise is exactly one tick, and it keeps the folding of `error` in one place.
9264                if needs_await && !awaited {
9265                    let finished = self.new_array(Vec::new());
9266                    let thunk = JsObject::function(
9267                        self.heap,
9268                        Some(self.realm.function_proto.clone()),
9269                        Callable::DisposeStep {
9270                            remaining: finished.clone(),
9271                            promise: promise.clone(),
9272                            error,
9273                            rejected: false,
9274                            awaited: true,
9275                            needs_await: false,
9276                        },
9277                    );
9278                    let tick = self.promise_resolve_value(Value::Undefined)?;
9279                    if let Value::Object(tick) = tick {
9280                        self.perform_then(
9281                            &tick,
9282                            Some(Value::Object(thunk.clone())),
9283                            Some(Value::Object(thunk)),
9284                        )?;
9285                    }
9286                    return Ok(());
9287                }
9288                if matches!(error, Value::Uninitialized) {
9289                    self.fulfill_promise(promise, Value::Undefined);
9290                } else {
9291                    self.reject_promise(promise, error);
9292                }
9293                return Ok(());
9294            }
9295            let Some(Value::Object(pair)) = remaining
9296                .array_get(length - 1)
9297                .filter(|v| !matches!(v, Value::Hole))
9298            else {
9299                remaining.array_truncate(self.heap, length - 1);
9300                continue;
9301            };
9302            remaining.array_truncate(self.heap, length - 1);
9303            let value = pair.array_get(0).unwrap_or(Value::Undefined);
9304            let Some(Value::Object(method)) = pair.array_get(1) else {
9305                continue;
9306            };
9307            if !method.is_callable() {
9308                continue;
9309            }
9310            match self.call_value(Value::Object(method), value, Vec::new()) {
9311                Ok(result) => {
9312                    if !self.is_thenable(&result)? {
9313                        // Finished synchronously; the next disposer is the next iteration.
9314                        continue;
9315                    }
9316                    let awaited = match self.promise_resolve_value(result) {
9317                        Ok(awaited) => awaited,
9318                        Err(Signal::Throw(reason)) => {
9319                            self.reject_promise(promise, reason);
9320                            return Ok(());
9321                        }
9322                        Err(other) => return Err(other),
9323                    };
9324                    let Value::Object(awaited) = awaited else {
9325                        continue;
9326                    };
9327                    let ok = JsObject::function(
9328                        self.heap,
9329                        Some(self.realm.function_proto.clone()),
9330                        Callable::DisposeStep {
9331                            remaining: remaining.clone(),
9332                            promise: promise.clone(),
9333                            error: error.clone(),
9334                            rejected: false,
9335                            awaited: true,
9336                            needs_await,
9337                        },
9338                    );
9339                    let failed = JsObject::function(
9340                        self.heap,
9341                        Some(self.realm.function_proto.clone()),
9342                        Callable::DisposeStep {
9343                            remaining: remaining.clone(),
9344                            promise: promise.clone(),
9345                            error,
9346                            rejected: true,
9347                            awaited: true,
9348                            needs_await,
9349                        },
9350                    );
9351                    self.perform_then(
9352                        &awaited,
9353                        Some(Value::Object(ok)),
9354                        Some(Value::Object(failed)),
9355                    )?;
9356                    return Ok(());
9357                }
9358                Err(Signal::Throw(thrown)) => {
9359                    error = self.merge_dispose_error(thrown, error);
9360                }
9361                Err(other) => return Err(other),
9362            }
9363        }
9364    }
9365
9366    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9367    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9368        let Value::Object(object) = value else {
9369            return Ok(false);
9370        };
9371        Ok(matches!(
9372            self.get_property(object, "then")?,
9373            Some(Value::Object(then)) if then.is_callable()
9374        ))
9375    }
9376
9377    /// One step of an async generator, settling `promise` with an `{value, done}` result.
9378    fn step_async_generator(
9379        &mut self,
9380        generator: &Gc<JsObject>,
9381        promise: &Gc<JsObject>,
9382        kind: ResumeKind,
9383        value: Value,
9384    ) -> JsResult<()> {
9385        // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9386        // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9387        // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9388        // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9389        // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9390        // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9391        // out of the same read, one as a rejection and one as a rethrow.
9392        //
9393        // Narrow on purpose: only a value that is *already a promise* is inspected, so
9394        // nothing changes for `return 1` and the extra read is a plain data-property
9395        // lookup on the intrinsic case.
9396        if kind == ResumeKind::Return
9397            && let Value::Object(object) = &value
9398            && self.promise_state(object).is_some()
9399            && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9400        {
9401            return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9402        }
9403        let stepped = self.resume_generator_detailed(generator, kind, value);
9404        let (value, done, ready, reason) = match stepped {
9405            Ok(stepped) => stepped,
9406            Err(Signal::Throw(reason)) => {
9407                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9408            }
9409            Err(other) => return Err(other),
9410        };
9411        // Only an `await` has to wait before the method can answer.
9412        if !done && reason == Some(SuspendKind::Await) {
9413            let awaited = match self.promise_resolve_value(value) {
9414                Ok(awaited) => awaited,
9415                Err(Signal::Throw(reason)) => {
9416                    return self.settle_async_request(
9417                        generator,
9418                        promise,
9419                        AsyncOutcome::Error(reason),
9420                    );
9421                }
9422                Err(other) => return Err(other),
9423            };
9424            let Value::Object(awaited) = awaited else {
9425                return Ok(());
9426            };
9427            let resumed = JsObject::function(
9428                self.heap,
9429                Some(self.realm.function_proto.clone()),
9430                Callable::GeneratorResume {
9431                    generator: generator.clone(),
9432                    promise: promise.clone(),
9433                    kind: ResumeKind::Next,
9434                },
9435            );
9436            let raised = JsObject::function(
9437                self.heap,
9438                Some(self.realm.function_proto.clone()),
9439                Callable::GeneratorResume {
9440                    generator: generator.clone(),
9441                    promise: promise.clone(),
9442                    kind: ResumeKind::Throw,
9443                },
9444            );
9445            self.perform_then(
9446                &awaited,
9447                Some(Value::Object(resumed)),
9448                Some(Value::Object(raised)),
9449            )?;
9450            return Ok(());
9451        }
9452        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9453        // completes it — both arrive as the settled value rather than as the promise
9454        // object. A plain value skips the round trip, which is also what keeps `yield 1`
9455        // from costing an extra tick.
9456        let awaits_value = self.is_thenable(&value)?;
9457        if awaits_value {
9458            // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9459            // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9460            // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9461            // no `PromiseResolve` appears, so that path keeps the shortcut.
9462            let awaited = match if done {
9463                self.promise_resolve_intrinsic(value)
9464            } else {
9465                self.promise_resolve_value(value)
9466            } {
9467                Ok(awaited) => awaited,
9468                Err(Signal::Throw(reason)) => {
9469                    return self.settle_async_request(
9470                        generator,
9471                        promise,
9472                        AsyncOutcome::Error(reason),
9473                    );
9474                }
9475                Err(other) => return Err(other),
9476            };
9477            let Value::Object(awaited) = awaited else {
9478                return Ok(());
9479            };
9480            // A rejected yield throws *at the yield* inside the body, so the rejection
9481            // resumes the generator rather than the method's promise.
9482            let answer = JsObject::function(
9483                self.heap,
9484                Some(self.realm.function_proto.clone()),
9485                Callable::YieldResult {
9486                    generator: generator.clone(),
9487                    promise: promise.clone(),
9488                    done,
9489                },
9490            );
9491            let raise = JsObject::function(
9492                self.heap,
9493                Some(self.realm.function_proto.clone()),
9494                Callable::GeneratorResume {
9495                    generator: generator.clone(),
9496                    promise: promise.clone(),
9497                    kind: ResumeKind::Throw,
9498                },
9499            );
9500            self.perform_then(
9501                &awaited,
9502                Some(Value::Object(answer)),
9503                Some(Value::Object(raise)),
9504            )?;
9505            return Ok(());
9506        }
9507        let result = if ready {
9508            // `yield*` handed back the inner iterator's own result object.
9509            value
9510        } else {
9511            self.iterator_result(value, done)?
9512        };
9513        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9514    }
9515
9516    /// The `{value, done}` object an iterator method answers with.
9517    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9518        let result = self.new_object(Some(self.realm.object_proto.clone()));
9519        result.define_data("value", value);
9520        result.define_data("done", Value::Bool(done));
9521        Ok(Value::Object(result))
9522    }
9523
9524    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9525    fn step_generator(
9526        &mut self,
9527        state: &mut GeneratorState,
9528        kind: ResumeKind,
9529        value: Value,
9530    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9531        match state.phase {
9532            GeneratorPhase::Executing => {
9533                return Err(self.type_error("cannot invoke a running generator"));
9534            }
9535            GeneratorPhase::Completed => {
9536                // A finished generator answers every resumption without running.
9537                return Ok(match kind {
9538                    ResumeKind::Throw => return Err(Signal::Throw(value)),
9539                    ResumeKind::Return => (value, true, false, None),
9540                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9541                });
9542            }
9543            GeneratorPhase::SuspendedStart => {
9544                if kind != ResumeKind::Next && kind != ResumeKind::Start {
9545                    // The body never started, so there is nothing to unwind or return
9546                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9547                    state.frame = None;
9548                    state.phase = GeneratorPhase::Completed;
9549                    return Ok(match kind {
9550                        ResumeKind::Throw => return Err(Signal::Throw(value)),
9551                        _ => (value, true, false, None),
9552                    });
9553                }
9554            }
9555            GeneratorPhase::SuspendedYield => {}
9556        }
9557
9558        let Some(mut frame) = state.frame.take() else {
9559            return Ok((Value::Undefined, true, false, None));
9560        };
9561        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9562        // number that says which method resumed it; the emitted `if_false` branches on
9563        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9564        let mut raised = None;
9565        match kind {
9566            ResumeKind::Next | ResumeKind::Start => {
9567                if state.phase == GeneratorPhase::SuspendedYield {
9568                    frame.stack.push(value);
9569                    // An `await` resumes with its value alone; only a `yield` gets the
9570                    // magic number that says which of `next`/`return` resumed it.
9571                    if !state.parked_on_await {
9572                        frame.stack.push(Value::Int(RESUME_NEXT));
9573                    }
9574                }
9575            }
9576            ResumeKind::Return => {
9577                // A `return` on a not-yet-started generator is handled above, so this is
9578                // always a real resumption.
9579                frame.stack.push(value);
9580                frame.stack.push(Value::Int(RESUME_RETURN));
9581            }
9582            ResumeKind::Throw => {
9583                // At a `yield*` the exception is *data* for the delegation: the compiled
9584                // code resumes with the value and magic `2` and calls the inner iterator's
9585                // `throw`. Everywhere else it is raised at the suspension point, so the
9586                // body's own handler sees it.
9587                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9588                    frame.stack.push(value);
9589                    frame.stack.push(Value::Int(RESUME_THROW));
9590                } else {
9591                    raised = Some(value);
9592                }
9593            }
9594        }
9595        state.phase = GeneratorPhase::Executing;
9596
9597        let depth = self.frames.len();
9598        self.frames.push(frame);
9599        // A `throw` unwinds from where the frame parked, exactly as if the exception had
9600        // happened at the `yield`.
9601        if let Some(mut exception) = raised {
9602            if self.catch_here(&mut exception).is_none() {
9603                self.pop_frame();
9604                state.phase = GeneratorPhase::Completed;
9605                return Err(Signal::Throw(exception));
9606            }
9607        }
9608
9609        // Only the generator's *own* frame ends the generator. The body may call ordinary
9610        // functions, and those push frames of their own: a `Step::Return` from one of them
9611        // is a nested call finishing, not the generator completing. Miscounting that is
9612        // silent — the generator reports the callee's value as its own result and marks
9613        // itself done — so the depth comparison is load-bearing, not defensive.
9614        let own_frame = depth + 1;
9615        loop {
9616            match self.step() {
9617                Ok(Step::Continue) => {}
9618                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9619                    let mut frame = self.frames.pop().expect("a frame is live");
9620                    // `yield` left the value on the stack; `initial_yield` left nothing.
9621                    let yielded = if reason == SuspendKind::Initial {
9622                        Value::Undefined
9623                    } else {
9624                        frame.stack.pop().unwrap_or(Value::Undefined)
9625                    };
9626                    state.frame = Some(frame);
9627                    state.parked_on_await = reason == SuspendKind::Await;
9628                    state.parked_on_yield_star =
9629                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9630                    state.phase = if reason == SuspendKind::Initial {
9631                        GeneratorPhase::SuspendedStart
9632                    } else {
9633                        GeneratorPhase::SuspendedYield
9634                    };
9635                    // `yield*` hands the inner iterator's own result object straight
9636                    // back, so the caller sees one `{value, done}` rather than a nested
9637                    // one — which is why the third field says "already a result".
9638                    return Ok((
9639                        yielded,
9640                        false,
9641                        reason == SuspendKind::YieldStar,
9642                        Some(reason),
9643                    ));
9644                }
9645                Ok(Step::Suspend(_)) => {
9646                    // A `yield` in a frame other than the generator's would mean a
9647                    // generator body entered as an ordinary call, which
9648                    // `call_or_push` prevents.
9649                    self.unwind_to(depth);
9650                    state.phase = GeneratorPhase::Completed;
9651                    return Err(Signal::Throw(self.make_error(
9652                        "InternalError",
9653                        "a generator body ran as an ordinary call",
9654                    )));
9655                }
9656                Ok(Step::Return(value)) => {
9657                    self.pop_frame();
9658                    if self.frames.len() > depth {
9659                        // A nested call finished: hand the value back to its caller and
9660                        // keep running the generator body.
9661                        self.frames
9662                            .last_mut()
9663                            .expect("a caller is live")
9664                            .stack
9665                            .push(value);
9666                        continue;
9667                    }
9668                    state.phase = GeneratorPhase::Completed;
9669                    // The reference closes the generator's closure variables here; ours
9670                    // live in cells the frame owned, which the drop below releases.
9671                    return Ok((value, true, false, None));
9672                }
9673                Err(Signal::Throw(exception)) => {
9674                    // The frame that threw gets the first chance to catch, exactly as in
9675                    // the ordinary call loop; a frame above the generator's is popped and
9676                    // the exception carries on down.
9677                    let mut exception = exception;
9678                    loop {
9679                        if self.frames.len() <= depth {
9680                            // The generator's own frame is gone, so nothing here caught it.
9681                            state.phase = GeneratorPhase::Completed;
9682                            return Err(Signal::Throw(exception));
9683                        }
9684                        if self.catch_here(&mut exception).is_some() {
9685                            break;
9686                        }
9687                        self.pop_frame();
9688                    }
9689                }
9690                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9691            }
9692        }
9693    }
9694
9695    /// Pop frames until `depth` are left, keeping their buffers.
9696    fn unwind_to(&mut self, depth: usize) {
9697        while self.frames.len() > depth {
9698            self.pop_frame();
9699        }
9700    }
9701    fn call_or_push(
9702        &mut self,
9703        callee: Value,
9704        this: Value,
9705        args: Vec<Value>,
9706    ) -> JsResult<Option<Value>> {
9707        if let Value::Object(function) = &callee
9708            && let Some((code, env)) = bytecode_of(function)
9709        {
9710            // Calling a generator function does not run anything: it captures the
9711            // arguments in a frame and hands back the generator object.
9712            if code.code.kind.is_generator() {
9713                return self.new_generator(callee, this, args).map(Some);
9714            }
9715            // An async function answers a promise and runs its body as a coroutine, so it
9716            // takes the same path as a plain call into it.
9717            if code.code.kind.is_async() {
9718                return self.new_async_function(callee, this, args).map(Some);
9719            }
9720            self.push_frame(code, env, this, args, callee)?;
9721            return Ok(None);
9722        }
9723        self.call_value(callee, this, args).map(Some)
9724    }
9725
9726    /// `new callee(args)`.
9727    ///
9728    /// A constructor differs from a plain call in three ways: it gets a fresh object
9729    /// as `this` whose prototype is the constructor's `prototype` property, its
9730    /// return value is *replaced* by that object unless it returns an object itself,
9731    /// and a native constructor is expected to initialise the object it is given
9732    /// rather than build one.
9733    pub fn construct(
9734        &mut self,
9735        callee: Value,
9736        new_target: Value,
9737        args: Vec<Value>,
9738    ) -> JsResult<Value> {
9739        // `new` on a bound function constructs its *target*, prepending the arguments
9740        // the bind fixed and ignoring the bound `this` — a bound function is a
9741        // constructor only when its target is one, and `new` always makes a fresh
9742        // object of the target's prototype rather than reusing the bound receiver.
9743        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9744        // ran the body with `this === null` and threw on `this.x = a`.
9745        let mut callee = callee;
9746        let mut new_target = new_target;
9747        let mut args = args;
9748        loop {
9749            let Some(object) = callee.as_object().cloned() else {
9750                return Err(Signal::Throw(
9751                    self.make_error("TypeError", "not a constructor"),
9752                ));
9753            };
9754            // A proxy of a function constructs through its `construct` trap, and the
9755            // trap's answer is the result directly — no fresh object is made here.
9756            if object.proxy_state().is_some() {
9757                return match self.proxy_construct(&object, args, &new_target)? {
9758                    Some(result) => Ok(result),
9759                    None => Err(Signal::Throw(
9760                        self.make_error("TypeError", "proxy target is not a constructor"),
9761                    )),
9762                };
9763            }
9764            // A generator function has no `[[Construct]]`, and the reference names it in
9765            // the message: `new (function* G(){})()` reports "G is not a constructor".
9766            if object.with(|data| match &data.kind {
9767                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9768                    code.code.kind.is_generator()
9769                }
9770                _ => false,
9771            }) {
9772                let name = object
9773                    .own_property("name")
9774                    .and_then(|property| property.value)
9775                    .map(|value| value.to_js_string())
9776                    .unwrap_or_default();
9777                return Err(Signal::Throw(
9778                    self.make_error("TypeError", &format!("{name} is not a constructor")),
9779                ));
9780            }
9781            let bound = object.with(|data| match &data.kind {
9782                ObjectKind::Function(Callable::Bound {
9783                    target,
9784                    args: leading,
9785                    ..
9786                }) => Some((target.clone(), leading.clone())),
9787                _ => None,
9788            });
9789            let Some((target, leading)) = bound else {
9790                // Not a bound function, so this object is the callee. §7.2.4
9791                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9792                // refusals above cover only the built-ins the reference also refuses by
9793                // name. Everything else — a method, an arrow, an async function — has no
9794                // `[[Construct]]` either, and answering "yes" here made
9795                // `new (Array.prototype.map)` build an object instead of throwing.
9796                if !object.is_constructor() {
9797                    let name = object
9798                        .own_property("name")
9799                        .and_then(|property| property.value)
9800                        .map(|value| value.to_js_string())
9801                        .unwrap_or_default();
9802                    return Err(Signal::Throw(
9803                        self.make_error("TypeError", &format!("{name} is not a constructor")),
9804                    ));
9805                }
9806                break;
9807            };
9808            let mut all = leading;
9809            all.extend(args);
9810            args = all;
9811            // A bound function that is its own `new.target` stands in for its target:
9812            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9813            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9814            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9815                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9816                _ => false,
9817            };
9818            if same_wrapper {
9819                new_target = target.clone();
9820            }
9821            callee = target;
9822        }
9823        let Value::Object(function) = &callee else {
9824            unreachable!("the loop above only breaks on an object");
9825        };
9826        // The fresh object's prototype comes from `new.target`, not from the callee: a
9827        // derived constructor reaches here through `super()`, and the instance must be a
9828        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9829        // an object inheriting `D.prototype` rather than `C.prototype`.
9830        let prototype_source = match new_target.as_object() {
9831            Some(target) => target.clone(),
9832            None => function.clone(),
9833        };
9834        // A native constructor builds its own instance, through `new_ctor_instance`, once it
9835        // has validated its arguments. Pre-building one here would read
9836        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9837        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9838        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9839        let is_native = function.native_creates_own_instance();
9840        let this = if is_native {
9841            Value::Undefined
9842        } else {
9843            let prototype = self.get_property(&prototype_source, "prototype")?;
9844            let prototype = match prototype {
9845                Some(Value::Object(proto)) => Some(proto),
9846                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9847                // object, the answer is the realm's *intrinsic* prototype for this
9848                // constructor, not `%Object.prototype%`.
9849                _ => {
9850                    // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9851                    // and that is a `TypeError` for a revoked proxy. Without it, `new
9852                    // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9853                    // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9854                    // trap, so it is already revoked when this fallback runs.
9855                    if prototype_source.proxy_state().is_some() {
9856                        self.proxy_parts(&prototype_source)?;
9857                    }
9858                    let fallback = self.get_property(function, "prototype")?;
9859                    match fallback {
9860                        Some(Value::Object(proto)) => Some(proto),
9861                        _ => Some(self.realm.object_proto.clone()),
9862                    }
9863                }
9864            };
9865            Value::Object(self.new_object(prototype))
9866        };
9867        // `new.target` inside the body is the constructor that was written, so a bound
9868        // function's target sees itself rather than the bound wrapper.
9869        //
9870        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9871        // `?`, so assigning `None` after the call would be skipped and the failed
9872        // `new.target` would stay visible to every later native call. The symptom was a
9873        // native constructor refusing a plain call — `var s = Symbol(); new
9874        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9875        // "FinalizationRegistry is not a constructor".
9876        let outer_new_target = self.pending_new_target.replace(new_target);
9877        let callee = callee.clone();
9878        let result = self.call_value(callee, this.clone(), args);
9879        self.pending_new_target = outer_new_target;
9880        let result = result?;
9881        // A constructor that returns an object overrides `this`; any other return value
9882        // (including `undefined`) is ignored — **except** in a derived constructor, where
9883        // §15.7.1 step 12 makes a non-object return a `TypeError`
9884        // (`Function/internals/Construct/derived-return-val`).
9885        let derived = function.with(|data| match &data.kind {
9886            ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9887                code.code.is_derived_constructor
9888            }
9889            _ => false,
9890        });
9891        Ok(match result {
9892            Value::Object(_) => result,
9893            // A bare `return;` answers `undefined`, which is **legal** even in a derived
9894            // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9895            Value::Undefined => this,
9896            _ if derived => {
9897                return Err(Signal::Throw(self.make_error(
9898                    "TypeError",
9899                    "derived constructor may only return an object or undefined",
9900                )));
9901            }
9902            _ => this,
9903        })
9904    }
9905
9906    /// `new.target` for the call currently being made.
9907    ///
9908    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9909    /// it as `this`), but a *host* constructor that builds its own instance is handed
9910    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9911    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9912    /// it here.
9913    ///
9914    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9915    /// receives for a plain call.
9916    pub fn current_new_target(&self) -> Value {
9917        self.active_new_target.clone()
9918    }
9919
9920    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9921    ///
9922    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9923    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9924    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9925        let constructor = self.realm.errors.get("AggregateError").cloned();
9926        let Some(constructor) = constructor else {
9927            return self.make_error("AggregateError", message);
9928        };
9929        let list = self.new_array(errors);
9930        match self.construct(
9931            Value::Object(constructor.clone()),
9932            Value::Object(constructor),
9933            vec![Value::Object(list), self.string(message)],
9934        ) {
9935            Ok(value) => value,
9936            // A user could have replaced `AggregateError` with something that throws; the
9937            // engine still owes the caller a rejection, so it falls back rather than
9938            // turning `Promise.any`'s rejection into a throw.
9939            Err(_) => self.make_error("AggregateError", message),
9940        }
9941    }
9942
9943    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9944    ///
9945    /// The error classes themselves arrive with the builtins milestone; what
9946    /// matters here is that the thrown value stringifies the way a script printing
9947    /// the caught value expects.
9948    ///
9949    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9950    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9951    /// rely on when they print a caught value.
9952    pub fn make_error(&self, name: &str, message: &str) -> Value {
9953        let proto = self
9954            .realm
9955            .errors
9956            .get(name)
9957            .map(|constructor| self.prototype_of(constructor))
9958            .unwrap_or_else(|| self.realm.error_proto.clone());
9959        let error = self.new_object(Some(proto));
9960        // `name` and `message` are own properties of the instance, which is what
9961        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9962        // `Error`.
9963        error.define(
9964            "name",
9965            Property::with_attributes(self.string(name), true, false),
9966        );
9967        error.define(
9968            "message",
9969            Property::with_attributes(self.string(message), true, false),
9970        );
9971        // The internal class, which is what tells a printer this is an error rather than a
9972        // plain object with `name` and `message` properties. The constructor path sets it
9973        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9974        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9975        // literally `"Error"` in both places — the *name* is read from `name`, which is why
9976        // a `RangeError` still prints as `RangeError`.
9977        self.internal_set(&error, "_class", self.string("Error"));
9978        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9979        // answered `false` from `Error.isError` while a constructed one answered `true`,
9980        // because only the constructor set the slot. The reference answers `true` for both
9981        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9982        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9983        // tests `typeof stack === "string"` to decide on a trailing newline, so every
9984        // engine-thrown error lost its blank line.
9985        self.internal_set(&error, "_error_data", Value::Bool(true));
9986        // The trace is captured where the error is *made*, which is where the reference
9987        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9988        // way out, so a caught engine error already has its stack even if the handler
9989        // never rethrows it.
9990        self.add_stack(&error);
9991        Value::Object(error)
9992    }
9993
9994    /// Give an error object its `stack` property, from the current frame stack.
9995    ///
9996    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9997    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9998    /// `stack` a script set, is not rewritten.
9999    pub fn add_stack(&self, object: &Gc<JsObject>) {
10000        self.add_stack_skipping(object, 0);
10001    }
10002
10003    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10004    ///
10005    /// An `Error` constructor passes 1: the reference builds those traces with
10006    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10007    /// constructor itself, while a `RangeError` raised inside `toISOString` does
10008    /// report `at toISOString (native)`.
10009    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10010        if object.has_own("stack") {
10011            return;
10012        }
10013        // The trace is *captured* here but not installed as a property: `stack` is an
10014        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10015        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10016        // is kept in a hidden slot and the getter materialises it on first read.
10017        //
10018        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10019        // shows it — this is the same discipline `_error_data` and `_class` follow.
10020        let trace = self.stack_trace_skipping(skip);
10021        let text = self.string(trace);
10022        self.internal_set(object, "_stack_trace", text);
10023    }
10024
10025    /// The function object currently being called, if any.
10026    ///
10027    /// A native function is a bare `fn` pointer, so it cannot capture which class
10028    /// it belongs to; it reads that from the callee instead. This is also what a
10029    /// stack trace would use.
10030    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10031        match &self.frames.last()?.callee {
10032            Value::Object(object) => Some(object.clone()),
10033            _ => None,
10034        }
10035    }
10036
10037    /// The `prototype` property of a constructor, falling back to
10038    /// `Object.prototype` for anything that is not shaped like one.
10039    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10040        constructor
10041            .own_property("prototype")
10042            .and_then(|property| property.value)
10043            .and_then(|value| value.as_object().cloned())
10044            .unwrap_or_else(|| self.realm.object_proto.clone())
10045    }
10046
10047    /// Throw a `TypeError` carrying `message`.
10048    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10049        Signal::Throw(self.make_error("TypeError", message.as_ref()))
10050    }
10051
10052    /// Throw a `RangeError` carrying `message`.
10053    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10054        Signal::Throw(self.make_error("RangeError", message.as_ref()))
10055    }
10056
10057    /// A `ReferenceError`, as the value to throw.
10058    ///
10059    /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10060    /// and its siblings report a `ReferenceError` there, which is what
10061    /// `adopt|defer|move/throws-if-disposed` assert.
10062    pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10063        Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10064    }
10065
10066    /// The `ReferenceError` a read of an uninitialised binding raises.
10067    /// The name of the binding `slot` refers to, for an error message.
10068    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10069        match kind {
10070            VarSlot::Loc => self
10071                .frame()
10072                .code
10073                .code
10074                .vars
10075                .get(slot)
10076                .map(|v| v.name.clone()),
10077            VarSlot::Closure => self
10078                .frame()
10079                .code
10080                .code
10081                .closure_vars
10082                .get(slot)
10083                .map(|c| c.name.clone()),
10084        }
10085        .unwrap_or_default()
10086    }
10087
10088    /// Whether `slot` names a `const` binding, which rejects every store after its
10089    /// initialiser.
10090    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10091        match kind {
10092            VarSlot::Loc => self
10093                .frame()
10094                .code
10095                .code
10096                .vars
10097                .get(slot)
10098                .is_some_and(|v| v.is_const),
10099            VarSlot::Closure => self
10100                .frame()
10101                .code
10102                .code
10103                .closure_vars
10104                .get(slot)
10105                .is_some_and(|c| c.is_const),
10106        }
10107    }
10108
10109    /// The `TypeError` a store to a `const` binding raises.
10110    ///
10111    /// `const` is enforced here rather than at compile time because the binding can be
10112    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10113    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10114    /// both halves of what "checked store" means: the dead zone is over, and the
10115    /// binding is writable.
10116    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10117        let name = self.binding_name(slot, kind);
10118        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10119    }
10120
10121    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10122        let name = match kind {
10123            VarSlot::Loc => self
10124                .frame()
10125                .code
10126                .code
10127                .vars
10128                .get(slot)
10129                .map(|v| v.name.clone()),
10130            VarSlot::Closure => self
10131                .frame()
10132                .code
10133                .code
10134                .closure_vars
10135                .get(slot)
10136                .map(|c| c.name.clone()),
10137        }
10138        .unwrap_or_default();
10139        // The reference has a wording of its own for `this`, because the dead zone it sits
10140        // in is the derived constructor's rather than a `let`'s: `constructor(){ return; }`
10141        // reports `this is not initialized`.
10142        let message = if name == "this" {
10143            "this is not initialized".to_string()
10144        } else {
10145            format!("cannot access '{name}' before initialization")
10146        };
10147        Signal::Throw(self.make_error("ReferenceError", &message))
10148    }
10149
10150    fn throw_reference(&self, name: &str) -> Signal {
10151        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10152    }
10153
10154    // -- the instruction loop -----------------------------------------------
10155
10156    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10157    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10158    // measured at 16% of a tight arithmetic loop's total time.
10159    #[inline(always)]
10160    fn step(&mut self) -> JsResult<Step> {
10161        // The instruction is already decoded (see [`crate::insn`]), so this is an index
10162        // and a `Copy` read rather than a table lookup plus a width switch. Only the
10163        // borrow lives across the boundary; nothing is cloned.
10164        // **One** borrow of the frame: fetch the record, then advance in the same scope.
10165        // The obvious version borrowed it three times (`last` to read, `last_mut` to
10166        // write, and once more inside the handler), and each is a bounds check plus an
10167        // `Option` unwrap — on the one path every instruction takes.
10168        let Some((insn, next)) = ({
10169            let frame = self
10170                .frames
10171                .last_mut()
10172                .expect("step() is only called with a live frame");
10173            // Past the last instruction is a normal return: the compiler ends a function
10174            // with `return`, and a jump to the end of a block lands here.
10175            let insn = frame.insns().get(frame.pc).copied();
10176            match insn {
10177                None => None,
10178                Some(insn) => {
10179                    // A fused record stands for the next few instructions, so the next
10180                    // `pc` is its width ahead — the instructions it replaces are never
10181                    // dispatched. `at` is the byte offset a stack trace reports; it stays
10182                    // an offset because the line table is keyed by bytes.
10183                    frame.at = insn.offset as usize;
10184                    frame.pc += insn.width();
10185                    Some((insn, frame.pc))
10186                }
10187            }
10188        }) else {
10189            return Ok(Step::Return(Value::Undefined));
10190        };
10191        self.check_memory()?;
10192        self.check_interrupt()?;
10193        if insn.fused == crate::insn::Fused::None {
10194            self.execute_instruction(insn.op, insn.a, insn.b, next)
10195        } else {
10196            self.execute_fused(insn)
10197        }
10198    }
10199
10200    /// Run a fused instruction: several bytecode instructions in one dispatch.
10201    ///
10202    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10203    /// it cannot throw and cannot allocate — and anything else falls back to the real
10204    /// instructions, in their real order, so an exception leaves the operand stack
10205    /// exactly as it would have been.
10206    #[inline]
10207    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10208        use crate::insn::Fused;
10209        let slot = insn.a as usize;
10210        match insn.fused {
10211            // `x = k`: `push k; put_loc x`.
10212            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10213            // `x += k`: `get_loc x; push k; add; put_loc x`.
10214            Fused::AddImmLoc => {
10215                let delta = insn.b as i32;
10216                match self.get_loc(slot) {
10217                    Value::Int(left) => {
10218                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10219                        // that built two `Value`s, called a function, and matched on them
10220                        // again to reach this same `checked_add`. It is the innermost
10221                        // operation of every accumulator in every program.
10222                        let answer = match left.checked_add(delta) {
10223                            Some(sum) => Value::Int(sum),
10224                            None => Value::Float(left as f64 + delta as f64),
10225                        };
10226                        self.put_loc(slot, answer);
10227                    }
10228                    other => {
10229                        self.push(other);
10230                        self.push(Value::Int(delta));
10231                        self.binary_add()?;
10232                        let value = self.pop();
10233                        self.put_loc(slot, value);
10234                    }
10235                }
10236            }
10237            // `x += "literal"` and `x += y`: the two shapes that can append in place.
10238            Fused::AddAtomLoc => {
10239                let text = self.atom_wtf8(insn.b as usize);
10240                let right = self.string_wtf8(text);
10241                self.add_into_loc(slot, right)?;
10242            }
10243            Fused::AddLocLoc => {
10244                let source = (insn.a & 0xFFFF) as usize;
10245                let target = (insn.a >> 16) as usize;
10246                let right = self.get_loc(source);
10247                self.add_into_loc(target, right)?;
10248            }
10249            Fused::AddArgLoc => {
10250                let source = (insn.a & 0xFFFF) as usize;
10251                let target = (insn.a >> 16) as usize;
10252                let right = self.get_arg(source);
10253                self.add_into_loc(target, right)?;
10254            }
10255            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10256            Fused::PostIncLoc => match self.get_loc(slot) {
10257                Value::Int(left) => {
10258                    let answer = match left.checked_add(1) {
10259                        Some(sum) => Value::Int(sum),
10260                        None => Value::Float(left as f64 + 1.0),
10261                    };
10262                    self.put_loc(slot, answer);
10263                }
10264                other => {
10265                    self.push(other);
10266                    let raw = self.pop();
10267                    let (old, updated) = self.advance_numeric(raw, true)?;
10268                    self.push(old);
10269                    self.push(updated);
10270                    let value = self.pop();
10271                    self.put_loc(slot, value);
10272                    self.pop();
10273                }
10274            },
10275            // `if (!(x < arg)) goto target`: a loop header.
10276            //
10277            // The comparison is computed rather than replayed on the operand stack. That
10278            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10279            // that throws: the effects happen in the same order, and a handler truncates
10280            // the stack down to its marker, so the intermediate values are unobservable.
10281            Fused::LtLocArgJump => {
10282                let loc = (insn.a >> 16) as usize;
10283                let arg = (insn.a & 0xFFFF) as usize;
10284                let left = self.get_loc(loc);
10285                let right = self.get_arg(arg);
10286                let taken = match (&left, &right) {
10287                    (Value::Int(left), Value::Int(right)) => !(left < right),
10288                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10289                };
10290                if taken {
10291                    self.frame_mut().pc = insn.b as usize;
10292                }
10293            }
10294            // `i < k` in a loop header, where `k` is an integer literal.
10295            Fused::LtLocImmJump => {
10296                let left = self.get_loc(insn.a as usize);
10297                let right = Value::Int(insn.imm as i32);
10298                let taken = match &left {
10299                    Value::Int(left) => !(*left < insn.imm as i32),
10300                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10301                };
10302                if taken {
10303                    self.frame_mut().pc = insn.b as usize;
10304                }
10305            }
10306            Fused::None => unreachable!("only called for a fused record"),
10307        }
10308        Ok(Step::Continue)
10309    }
10310
10311    /// Run records that cannot call script, cannot throw and cannot change frames.
10312    ///
10313    /// Returns `Some(value)` when the function ran off the end of its instructions (a
10314    /// normal return), and `None` when it stopped in front of an instruction the slow path
10315    /// has to handle — `pc` is written back either way, so `step` resumes at the right
10316    /// place.
10317    ///
10318    /// **The invariant is the whole point.** Every arm here is restricted to work that
10319    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10320    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10321    /// that the memory limit has to see. An opcode whose operands turn out to need any of
10322    /// that **stops the loop** instead of trying, so the slow path gets the instruction
10323    /// untouched and with its operands still on the stack. That is why the fallback is a
10324    /// `break` and not a duplicated slow arm: a second implementation of the same
10325    /// semantics is how a wrong answer gets in with no test noticing.
10326    ///
10327    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10328    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10329    fn run_fast(&mut self) -> JsResult<Option<Value>> {
10330        use crate::insn::Fused;
10331        // The outer loop exists only so a `Call` can come back through here: once a
10332        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10333        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10334        // frame. Re-entering re-reads both from whichever frame is now on top. Every
10335        // other exit from the inner loop returns, so this costs one loop per call.
10336        'outer: loop {
10337            // One reference-count bump per *slow* instruction (a call, an allocation, a
10338            // property access), never one per instruction — that distinction is worth
10339            // two orders of magnitude and was measured as such.
10340            let (code, mut pc) = {
10341                let frame = self.frame();
10342                (frame.code.clone(), frame.pc)
10343            };
10344            let insns = &code.insns;
10345            loop {
10346                let Some(insn) = insns.get(pc).copied() else {
10347                    self.frame_mut().pc = pc;
10348                    return Ok(Some(Value::Undefined));
10349                };
10350                match insn.fused {
10351                    // `x = k`
10352                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10353                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10354                    // object — stops the loop so `binary_add` can decide.
10355                    Fused::AddImmLoc => {
10356                        let slot = insn.a as usize;
10357                        let delta = insn.b as i32;
10358                        let Value::Int(left) = self.get_loc(slot) else {
10359                            return Ok(self.stop(pc));
10360                        };
10361                        let sum = match left.checked_add(delta) {
10362                            Some(sum) => Value::Int(sum),
10363                            None => Value::Float(left as f64 + delta as f64),
10364                        };
10365                        self.put_loc(slot, sum);
10366                    }
10367                    // `x += "literal"` / `x += y`: the operand is a string, so the append
10368                    // either allocates one or grows one. Both are the slow path's business;
10369                    // the fusion's job is only to make the *slot* the sole owner, which is what
10370                    // `execute_fused` needs and what `get_loc` alone destroys.
10371                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10372                        return Ok(self.stop(pc));
10373                    }
10374                    // `x++` on an integer, old value dropped.
10375                    Fused::PostIncLoc => {
10376                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10377                        // value is read in place and overwritten in place, so the reference
10378                        // count it held is released by the same assignment that stores the
10379                        // new one. `get_loc` plus `put_loc` did two borrows, two table
10380                        // lookups and a clone, and this arm is the whole body of a counting
10381                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10382                        let slot = insn.a as usize;
10383                        let frame = self.frames.last_mut().expect("a frame is live");
10384                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10385                        let target = if cell < 0 {
10386                            frame.locals.get_mut(slot)
10387                        } else {
10388                            None
10389                        };
10390                        let Some(target) = target else {
10391                            return Ok(self.stop(pc));
10392                        };
10393                        let Value::Int(left) = *target else {
10394                            return Ok(self.stop(pc));
10395                        };
10396                        *target = match left.checked_add(1) {
10397                            Some(sum) => Value::Int(sum),
10398                            None => Value::Float(left as f64 + 1.0),
10399                        };
10400                    }
10401                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
10402                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10403                    // bound stayed small integers.
10404                    Fused::LtLocArgJump => {
10405                        let loc = (insn.a >> 16) as usize;
10406                        let arg = (insn.a & 0xFFFF) as usize;
10407                        // One borrow for both slots: this arm *is* the whole loop of a
10408                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
10409                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
10410                        // `dispatch:empty-loop`.
10411                        let (left, right) = {
10412                            let frame = self.frame();
10413                            (frame.read_loc(loc), frame.read_arg(arg))
10414                        };
10415                        // Heavily measured: the bound is very often a `Float` even when the
10416                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10417                        // `JSON.parse` or a division is one — so requiring both sides to be
10418                        // `Int` sent every iteration of those loops down the slow path. The
10419                        // comparison below is the same one `relational` makes for two numbers.
10420                        if !is_number(&left) || !is_number(&right) {
10421                            return Ok(self.stop(pc));
10422                        }
10423                        // `if_false` branches on the comparison being false, which is **not**
10424                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10425                        // `>=` is also false and would keep it running forever. Clippy wants the
10426                        // negation folded; that would be a wrong answer.
10427                        let ordered = left.to_number() < right.to_number();
10428                        let take_branch = !ordered;
10429                        if take_branch {
10430                            pc = insn.b as usize;
10431                            continue;
10432                        }
10433                    }
10434                    // The same header with a literal bound: `if (!(x < k)) goto target`.
10435                    // The bound is an immediate, so only the counter needs a type test.
10436                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
10437                    Fused::LtLocImmJump => {
10438                        let left = self.get_loc(insn.a as usize);
10439                        if !is_number(&left) {
10440                            return Ok(self.stop(pc));
10441                        }
10442                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10443                        if take_branch {
10444                            pc = insn.b as usize;
10445                            continue;
10446                        }
10447                    }
10448                    Fused::None => match insn.op {
10449                        // -- branches ---------------------------------------------------
10450                        // A jump is an assignment now, because the target is an instruction
10451                        // index. No arithmetic, no resolution table.
10452                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10453                            let target = insn.a as usize;
10454                            // A **back-edge** is a loop, and it is the only place an
10455                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
10456                            // to a jump to itself and never leaves this loop, so the
10457                            // per-instruction checks in `step` never run. That is exactly the
10458                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
10459                            // nothing to a `for(;;){}` until it did, which is what
10460                            // `tests/c/embed.c` is for.
10461                            //
10462                            // Polling here rather than on every instruction in this loop is
10463                            // also the reference's choice (`OP_goto` calls
10464                            // `js_poll_interrupts`), and it costs one compare per branch
10465                            // instead of one decrement per instruction.
10466                            if target <= pc {
10467                                self.frame_mut().pc = target;
10468                                self.check_memory()?;
10469                                self.check_interrupt()?;
10470                            }
10471                            pc = target;
10472                            continue;
10473                        }
10474                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10475                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10476                            let taken = self.pop().to_boolean();
10477                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10478                            if taken == want {
10479                                pc = insn.a as usize;
10480                                continue;
10481                            }
10482                        }
10483                        // -- slot access -------------------------------------------------
10484                        // A load's slot is already an operand (see `insn::implicit_operand`);
10485                        // a captured one goes through its cell, which runs no script.
10486                        Opcode::GetLoc
10487                        | Opcode::GetLoc8
10488                        | Opcode::GetLoc0
10489                        | Opcode::GetLoc1
10490                        | Opcode::GetLoc2
10491                        | Opcode::GetLoc3 => {
10492                            let value = self.get_loc(insn.a as usize);
10493                            self.push(value);
10494                        }
10495                        Opcode::PutLoc
10496                        | Opcode::PutLoc8
10497                        | Opcode::PutLoc0
10498                        | Opcode::PutLoc1
10499                        | Opcode::PutLoc2
10500                        | Opcode::PutLoc3 => {
10501                            let value = self.pop();
10502                            self.put_loc(insn.a as usize, value);
10503                        }
10504                        Opcode::GetArg
10505                        | Opcode::GetArg0
10506                        | Opcode::GetArg1
10507                        | Opcode::GetArg2
10508                        | Opcode::GetArg3 => {
10509                            let value = self.get_arg(insn.a as usize);
10510                            self.push(value);
10511                        }
10512                        Opcode::PutArg
10513                        | Opcode::PutArg0
10514                        | Opcode::PutArg1
10515                        | Opcode::PutArg2
10516                        | Opcode::PutArg3 => {
10517                            let value = self.pop();
10518                            self.put_arg(insn.a as usize, value);
10519                        }
10520                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
10521                        // for why a non-hole own element is exactly the slow path's answer.
10522                        // The two operands are *peeked*, so a miss leaves the stack as the
10523                        // slow path expects to find it.
10524                        Opcode::GetArrayEl => {
10525                            // One lookup, not two. The guard used `if …is_some()` and the arm
10526                            // then called it again to get the value — two `peek`s, two
10527                            // `array_get`s and two `Value` clones for one element.
10528                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
10529                            // double call was the first version of the `get_field` fast path.
10530                            let Some(value) = self.fast_array_get() else {
10531                                return Ok(self.stop(pc));
10532                            };
10533                            // `a[i]` consumes both operands and leaves the element in their
10534                            // place: one `truncate` and one write, no `pop`/`push` pair.
10535                            let frame = self.frame_mut();
10536                            frame.stack.truncate(frame.stack.len() - 2);
10537                            frame.stack.push(value);
10538                        }
10539                        // `a[i] = v` on a dense array with an integer index: see
10540                        // `fast_array_set` for why the whole store is one step.
10541                        Opcode::PutArrayEl if self.fast_array_set() => {}
10542                        // `o.x` resolved from the inline cache without leaving the loop.
10543                        //
10544                        // The cache is keyed by `(receiver identity, atom, site)` and a
10545                        // monomorphic read re-validates the same chain every iteration, so
10546                        // each one used to cost a `stop(pc)` — a write of `pc` into the
10547                        // frame, a return out of this loop, a re-dispatch through `step` and
10548                        // a re-entry. `property:monomorphic` spent 18% in
10549                        // `read_field_cached` and 21% in `push`, both across that boundary.
10550                        //
10551                        // The site is `pc + width`, which is exactly the `next` the slow arm
10552                        // passes — the two must agree or every fast lookup misses and
10553                        // re-records the same entry forever.
10554                        //
10555                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10556                        // slow arm finds the receiver where it expects it.
10557                        // `name` resolved from the global-variable cache inside the loop.
10558                        //
10559                        // Same shape as `get_field` above and for the same reason: `get_var`
10560                        // was not in the fast loop, so reading a global — which `fib` does
10561                        // once per recursive call, for its own name — cost a `stop(pc)`, a
10562                        // return out of the loop, a `step` re-dispatch and a re-entry, before
10563                        // `get_global` even started its `scopes_are_plain` checks.
10564                        //
10565                        // Everything here is exactly `get_global`'s first branch: not lexical,
10566                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
10567                        // and lets the slow arm decide.
10568                        Opcode::GetVar => {
10569                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10570                                return Ok(self.stop(pc));
10571                            };
10572                            self.push(value);
10573                        }
10574                        Opcode::GetField | Opcode::GetField2 => {
10575                            let Some(value) =
10576                                self.fast_field_get(insn.a as usize, pc + insn.width())
10577                            else {
10578                                return Ok(self.stop(pc));
10579                            };
10580                            if insn.op == Opcode::GetField2 {
10581                                // `get_field2` keeps the receiver for the `call_method` that
10582                                // follows.
10583                                self.push(value);
10584                            } else {
10585                                // `get_field` replaces the receiver, so this is one store over
10586                                // the top slot rather than a `pop` and a `push`: the length
10587                                // never changes, so neither `Vec` arm has a capacity check or a
10588                                // drop to run beyond the one the overwrite itself does.
10589                                let frame = self.frame_mut();
10590                                match frame.stack.last_mut() {
10591                                    Some(slot) => *slot = value,
10592                                    None => return Ok(self.stop(pc)),
10593                                }
10594                            }
10595                        }
10596                        // -- constants ---------------------------------------------------
10597                        Opcode::PushMinus1
10598                        | Opcode::Push0
10599                        | Opcode::Push1
10600                        | Opcode::Push2
10601                        | Opcode::Push3
10602                        | Opcode::Push4
10603                        | Opcode::Push5
10604                        | Opcode::Push6
10605                        | Opcode::Push7
10606                        | Opcode::PushI8
10607                        | Opcode::PushI16
10608                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10609                        // -- stack shuffling ---------------------------------------------
10610                        Opcode::Drop => {
10611                            self.pop();
10612                        }
10613                        // -- arithmetic on two integers ----------------------------------
10614                        //
10615                        // The operands are *looked at* before they are popped, so a non-integer
10616                        // pair leaves the stack exactly as the slow path expects to find it.
10617                        Opcode::Add if self.numeric_pair() => {
10618                            let right = self.pop();
10619                            let left = self.pop();
10620                            // Exactly [`add_numbers`], which is what the slow arm reaches.
10621                            let answer = match (&left, &right) {
10622                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10623                                    Some(sum) => Value::Int(sum),
10624                                    None => Value::Float(*a as f64 + *b as f64),
10625                                },
10626                                _ => Value::Float(left.to_number() + right.to_number()),
10627                            };
10628                            self.push(answer);
10629                        }
10630                        Opcode::Sub
10631                        | Opcode::And
10632                        | Opcode::Or
10633                        | Opcode::Xor
10634                        | Opcode::Shl
10635                        | Opcode::Sar
10636                        | Opcode::Shr
10637                            if self.numeric_pair() =>
10638                        {
10639                            let right = self.pop();
10640                            let left = self.pop();
10641                            let answer =
10642                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
10643                            self.push(answer);
10644                        }
10645                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10646                            if self.numeric_pair() =>
10647                        {
10648                            let right = self.pop();
10649                            let left = self.pop();
10650                            let answer = self
10651                                .relational(insn.op, left, right)
10652                                .expect("numbers cannot throw");
10653                            self.push(answer);
10654                        }
10655                        // -- calls -------------------------------------------------------
10656                        //
10657                        // A plain call: `callee(arg0, …, argN) -> result`.
10658                        //
10659                        // This arm exists because of one measurement. `call:recursion` had
10660                        // **20.4% of its profile in `execute_instruction`** — the *slow*
10661                        // executor — and `fib`'s recursive call is the only thing in that
10662                        // function which is not a fast arm. Every call therefore left this
10663                        // loop via `stop()`, went through `step()`'s dispatch and
10664                        // `execute_instruction`'s match over every opcode, and came back here
10665                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10666                        //
10667                        // Two things make it safe to do here rather than only in the slow path:
10668                        //
10669                        // * the caller's `pc` is stored *before* the call, which is what
10670                        //   `step` does too — so when the callee returns, the caller resumes
10671                        //   after the call and not at it;
10672                        // * `check_memory` runs, because `step` calls it once per instruction
10673                        //   and a call allocates a frame, its locals and its cells. Skipping
10674                        //   the checkpoint here would let a `--memory-limit` script overshoot
10675                        //   by one call per instruction.
10676                        Opcode::Call
10677                        | Opcode::Call0
10678                        | Opcode::Call1
10679                        | Opcode::Call2
10680                        | Opcode::Call3 => {
10681                            let argc = self.argc_operand(insn.op, insn.a);
10682                            let next = pc + insn.width();
10683                            {
10684                                let frame = self
10685                                    .frames
10686                                    .last_mut()
10687                                    .expect("run_fast() is only called with a live frame");
10688                                // `at` is what a stack trace reports for this frame, so a throw
10689                                // inside the callee has to see the call site and not whatever
10690                                // the last `stop()` left there.
10691                                frame.at = insn.offset as usize;
10692                                frame.pc = next;
10693                            }
10694                            self.check_memory()?;
10695                            self.check_interrupt()?;
10696                            let args = self.pop_n(argc);
10697                            let callee = self.pop();
10698                            // A plain call has no receiver; the callee decides what to do with
10699                            // `undefined` (a sloppy function substitutes the global object).
10700                            if let Some(result) =
10701                                self.call_or_push(callee, Value::Undefined, args)?
10702                            {
10703                                // Native, host, generator, async, bound — no frame was pushed,
10704                                // so this loop is still describing the right function. `pc`
10705                                // is advanced by the loop tail like every other arm; only the
10706                                // frame's copy had to be written here, and it already was.
10707                                self.push(result);
10708                            } else {
10709                                // A bytecode callee: its frame is on top now, and `insns` and
10710                                // `pc` both belong to the caller. Start over on the new frame.
10711                                continue 'outer;
10712                            }
10713                        }
10714                        // -- return ------------------------------------------------------
10715                        Opcode::Return => {
10716                            let value = self.pop();
10717                            self.frame_mut().pc = pc + insn.width();
10718                            return Ok(Some(value));
10719                        }
10720                        Opcode::ReturnUndef => {
10721                            self.frame_mut().pc = pc + insn.width();
10722                            return Ok(Some(Value::Undefined));
10723                        }
10724                        // Everything else needs the slow path.
10725                        _ => return Ok(self.stop(pc)),
10726                    },
10727                }
10728                pc += insn.width();
10729            }
10730        }
10731    }
10732
10733    /// Whether the top two operand-stack values are both numbers.
10734    ///
10735    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10736    /// cannot run script, so the arm may not throw and may not change frames.
10737    fn numeric_pair(&self) -> bool {
10738        is_number(&self.peek(0)) && is_number(&self.peek(1))
10739    }
10740
10741    /// `a[i]` for a dense array and an integer index, without the string round trip.
10742    ///
10743    /// The slow path answers this by turning `i` into a string (`propkey` →
10744    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10745    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10746    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10747    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10748    /// without even the cheap `Int` formatting.
10749    ///
10750    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10751    /// unambiguously the one the slow path would give:
10752    ///
10753    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10754    ///   `2^32-1` is the length, not an index),
10755    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10756    ///   typed array or an ordinary object, all of which have their own rules),
10757    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10758    ///   starts walking the prototype chain, and `a[i]` on a hole must find
10759    ///   `Array.prototype[i]` if it exists rather than `undefined`.
10760    ///
10761    /// The last condition is the one that makes this safe rather than merely fast: an own
10762    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10763    /// `get_var` answered from the global-variable cache, or `None`.
10764    ///
10765    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10766    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10767    /// records nothing — the slow arm is about to walk the chain and record it.
10768    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10769        let frame = self.frame();
10770        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10771        // "Lexical" is presence in the realm's table, not the closure var's flag: a
10772        // `GlobalRef` forwarded through a nested function has its flags cleared.
10773        if self.realm.globals.contains_key(name) {
10774            return None;
10775        }
10776        if !self.scopes_are_plain() {
10777            return None;
10778        }
10779        let object = &self.realm.global;
10780        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10781        let cached = self.global_cache[site].as_ref()?;
10782        if !object.upgrades_to(&cached.object) {
10783            return None;
10784        }
10785        object.data_property_at(cached.index, name)
10786    }
10787
10788    /// `o.x` answered entirely from the inline cache, or `None`.
10789    ///
10790    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10791    /// about to do exactly that and recording it twice would rebuild the chain for every
10792    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10793    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10794    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10795        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10796        // an object receiver is a reference-count bump that the answer never needs.
10797        let frame = self.frame();
10798        let object = frame.stack.last()?;
10799        let Value::Object(target) = object else {
10800            return None;
10801        };
10802        // A proxy traps the lookup, so no cache entry ever describes it.
10803        if target.proxy_state().is_some() {
10804            return None;
10805        }
10806        let key = frame.code.atom_keys.get(atom)?;
10807        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10808        if cached.key != *key {
10809            return None;
10810        }
10811        Self::cached_hit(target, cached)
10812    }
10813
10814    fn fast_array_get(&self) -> Option<Value> {
10815        let Value::Int(index) = self.peek(0) else {
10816            return None;
10817        };
10818        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10819        // set for an `i32`.
10820        if index < 0 {
10821            return None;
10822        }
10823        let Value::Object(object) = self.peek(1) else {
10824            return None;
10825        };
10826        match object.array_get(index as usize) {
10827            Some(value) if !matches!(value, Value::Hole) => Some(value),
10828            _ => None,
10829        }
10830    }
10831
10832    /// `a[i] = v` on a dense array with an integer index, as one store.
10833    ///
10834    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10835    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10836    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10837    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10838    /// reference at the time it was measured (14.7x).
10839    ///
10840    /// Every condition here is one the slow path would also have to satisfy before
10841    /// storing into the element vector:
10842    ///
10843    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10844    ///   accepts as an index;
10845    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10846    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10847    ///   one inside a recorded descriptor, reports `false` and the caller stops.
10848    ///
10849    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10850    /// writes the own element too once `array_set` says it did.
10851    fn fast_array_set(&mut self) -> bool {
10852        // Every test runs *before* anything is popped: a refusal has to leave the stack
10853        // exactly as the slow path expects to find it. Popping first and reporting the
10854        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10855        // then ran the slow path with nothing to write.
10856        let Value::Int(index) = self.peek(1) else {
10857            return false;
10858        };
10859        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10860        if index < 0 {
10861            return false;
10862        }
10863        // Only a real array: a typed array's elements live in its buffer, a string-like
10864        // object has no element vector, and `array_set` on either does nothing.
10865        let Value::Object(object) = self.peek(2) else {
10866            return false;
10867        };
10868        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10869            return false;
10870        }
10871        // A non-extensible array reports `false` here, but the *slow* path has to decide
10872        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10873        // that with the key and the stack still intact.
10874        if !object.is_extensible() {
10875            return false;
10876        }
10877        // Inside the logical length, so the store cannot change `length`. Combined with
10878        // extensibility above, the only growth left for `array_set` is filling a hole in
10879        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10880        // shape this fast path exists for. A store past the length would grow the array,
10881        // and whether that is allowed is the slow path's question.
10882        if index as usize >= object.array_length().unwrap_or(0) {
10883            return false;
10884        }
10885        // Only an *own element* can take the inline store. A hole is not an own property,
10886        // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10887        // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10888        // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10889        // the one case this path used to swallow.
10890        //
10891        // The cost is small: `array:indexed` only reads after a 64-element fill, and
10892        // `array:push` appends past the length, which this path already refused.
10893        if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10894        {
10895            return false;
10896        }
10897        // The bound `array_set` refuses past. Checking it here keeps that arm from having
10898        // to report a failure after the operands are gone.
10899        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10900            return false;
10901        }
10902        let value = self.pop();
10903        self.pop();
10904        self.pop();
10905        object.array_store(self.heap, index as usize, value)
10906    }
10907
10908    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10909    fn stop(&mut self, pc: usize) -> Option<Value> {
10910        self.frame_mut().pc = pc;
10911        None
10912    }
10913
10914    fn push(&mut self, value: Value) {
10915        self.frame_mut().stack.push(value);
10916    }
10917
10918    fn pop(&mut self) -> Value {
10919        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10920    }
10921
10922    fn pop_n(&mut self, count: usize) -> Vec<Value> {
10923        let frame = self.frame_mut();
10924        let start = frame.stack.len().saturating_sub(count);
10925        frame.stack.split_off(start)
10926    }
10927
10928    fn peek(&self, back: usize) -> Value {
10929        let frame = self.frame();
10930        frame
10931            .stack
10932            .get(frame.stack.len().wrapping_sub(1 + back))
10933            .cloned()
10934            .unwrap_or(Value::Undefined)
10935    }
10936
10937    #[allow(clippy::too_many_lines)]
10938    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10939        use Opcode::*;
10940        match op {
10941            // -- constants and stack shuffling -----------------------------
10942            Nop => {}
10943            PushMinus1 => self.push(Value::Int(-1)),
10944            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10945                let value = match op {
10946                    Push0 => 0,
10947                    Push1 => 1,
10948                    Push2 => 2,
10949                    Push3 => 3,
10950                    Push4 => 4,
10951                    Push5 => 5,
10952                    Push6 => 6,
10953                    _ => 7,
10954                };
10955                self.push(Value::Int(value));
10956            }
10957            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10958            PushBigintI32 => {
10959                // The immediate form of a `BigInt` literal; the reference has the same
10960                // split between this and a constant-pool entry.
10961                let value = crate::bigint::BigInt::from_i64(a as i64);
10962                self.push(self.bigint(value));
10963            }
10964            PushTrue => self.push(Value::Bool(true)),
10965            PushFalse => self.push(Value::Bool(false)),
10966            PushEmptyString => self.push(self.string("")),
10967            Undefined => self.push(Value::Undefined),
10968            Null => self.push(Value::Null),
10969            Object => {
10970                let proto = self.realm.object_proto.clone();
10971                self.push(Value::Object(self.new_object(Some(proto))));
10972            }
10973            PushThis => {
10974                let this = self.frame().this.clone();
10975                self.push(this);
10976            }
10977            PushConst | PushConst8 => {
10978                let value = self.constant(a as usize)?;
10979                self.push(value);
10980            }
10981            PushAtomValue => {
10982                let text = self.atom_wtf8(a as usize);
10983                self.push(self.string_wtf8(text));
10984            }
10985            Dup => {
10986                let value = self.peek(0);
10987                self.push(value);
10988            }
10989            Dup2 => {
10990                // `a b -> a b a b`
10991                let b = self.peek(0);
10992                let a = self.peek(1);
10993                self.push(a);
10994                self.push(b);
10995            }
10996            Dup3 => {
10997                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10998                // prototype and key while reading the current value through them.
10999                let c = self.peek(0);
11000                let b = self.peek(1);
11001                let a = self.peek(2);
11002                self.push(a);
11003                self.push(b);
11004                self.push(c);
11005            }
11006            Swap => {
11007                // `a b -> b a`
11008                let bottom = self.pop();
11009                let top = self.pop();
11010                self.push(bottom);
11011                self.push(top);
11012            }
11013            Perm3 => {
11014                // `a b c -> b a c`, the reference's reordering for a spread method
11015                // call: `obj func array` becomes the `func this array` that `apply`
11016                // takes.
11017                let c = self.pop();
11018                let b = self.pop();
11019                let a = self.pop();
11020                self.push(b);
11021                self.push(a);
11022                self.push(c);
11023            }
11024            Dup1 => {
11025                let value = self.peek(1);
11026                self.push(value);
11027            }
11028            Drop => {
11029                self.pop();
11030            }
11031            Nip => {
11032                // `a b -> b`
11033                let top = self.pop();
11034                self.pop();
11035                self.push(top);
11036            }
11037            Perm4 => {
11038                // `obj prop a b -> a obj prop b`, the reference's reordering for a
11039                // postfix update of a computed element: it puts the *old* value
11040                // underneath the receiver and key so `put_array_el` can consume them
11041                // and leave the old value as the expression's result.
11042                let d = self.pop();
11043                let c = self.pop();
11044                let b = self.pop();
11045                let a = self.pop();
11046                self.push(c);
11047                self.push(a);
11048                self.push(b);
11049                self.push(d);
11050            }
11051            Insert2 => {
11052                // `obj a -> a obj a`
11053                let value = self.pop();
11054                let object = self.pop();
11055                self.push(value.clone());
11056                self.push(object);
11057                self.push(value);
11058            }
11059            Insert3 => {
11060                // `obj prop a -> a obj prop a`
11061                let value = self.pop();
11062                let key = self.pop();
11063                let object = self.pop();
11064                self.push(value.clone());
11065                self.push(object);
11066                self.push(key);
11067                self.push(value);
11068            }
11069            Insert4 => {
11070                // `this obj prop a -> a this obj prop a`
11071                //
11072                // `put_super_value` consumes all four and yields nothing, so the copy
11073                // underneath is what leaves the assignment an expression value.
11074                let value = self.pop();
11075                let key = self.pop();
11076                let object = self.pop();
11077                let receiver = self.pop();
11078                self.push(value.clone());
11079                self.push(receiver);
11080                self.push(object);
11081                self.push(key);
11082                self.push(value);
11083            }
11084            Swap2 => {
11085                // `a b c d -> c d a b`
11086                let d = self.pop();
11087                let c = self.pop();
11088                let b = self.pop();
11089                let a = self.pop();
11090                self.push(c);
11091                self.push(d);
11092                self.push(a);
11093                self.push(b);
11094            }
11095            Rot3l => {
11096                // `x a b -> a b x`
11097                let b = self.pop();
11098                let a = self.pop();
11099                let x = self.pop();
11100                self.push(a);
11101                self.push(b);
11102                self.push(x);
11103            }
11104            Rot3r => {
11105                // `a b c -> c a b`
11106                let c = self.pop();
11107                let b = self.pop();
11108                let a_value = self.pop();
11109                self.push(c);
11110                self.push(a_value);
11111                self.push(b);
11112            }
11113
11114            Rest => {
11115                // `...rest` in a parameter list: the arguments from index `a` on, as a
11116                // real array. It takes nothing off the stack — the arguments are in the
11117                // frame, not on it.
11118                let frame = self.frame();
11119                let from = a as usize;
11120                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11121                let array = self.new_array(collected);
11122                self.push(Value::Object(array));
11123            }
11124
11125            // -- slots ------------------------------------------------------
11126            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11127                let slot = self.slot_operand(op, a);
11128                let value = self.get_loc(slot);
11129                self.push(value);
11130            }
11131            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11132                let slot = self.slot_operand(op, a);
11133                let value = self.pop();
11134                self.put_loc(slot, value);
11135            }
11136            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11137                let slot = self.slot_operand(op, a);
11138                let value = self.pop();
11139                self.put_loc(slot, value.clone());
11140                self.push(value);
11141            }
11142            // The `_check` forms are the temporal dead zone: they throw when the
11143            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11144            // *reads*, so only the two writes may pop — mishandling that quietly
11145            // consumes the value the caller pushed just before.
11146            GetLocCheck => {
11147                let slot = self.slot_operand(op, a);
11148                let value = self.get_loc(slot);
11149                if matches!(value, Value::Uninitialized) {
11150                    return Err(self.dead_zone(slot, VarSlot::Loc));
11151                }
11152                self.push(value);
11153            }
11154            PutLocCheck | SetLocCheck => {
11155                let slot = self.slot_operand(op, a);
11156                let value = self.pop();
11157                // The dead zone is a property of the **slot**, not of the value being
11158                // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11159                // initialised yet. Testing the value instead — which is never
11160                // `Uninitialized` in practice — let every such store through, so the check
11161                // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11162                // (`get_loc_check`) were already asking the slot, which is why
11163                // `print(x); let x` threw while `x = 1; let x` did not.
11164                if matches!(self.get_loc(slot), Value::Uninitialized) {
11165                    return Err(self.dead_zone(slot, VarSlot::Loc));
11166                }
11167                // The initialiser goes through `put_loc`, not this, so any store that
11168                // reaches here is a later assignment — which a `const` refuses.
11169                if self.is_read_only(slot, VarSlot::Loc) {
11170                    return Err(self.read_only(slot, VarSlot::Loc));
11171                }
11172                if op == SetLocCheck {
11173                    self.put_loc(slot, value.clone());
11174                    self.push(value);
11175                } else {
11176                    self.put_loc(slot, value);
11177                }
11178            }
11179            PutLocCheckInit => {
11180                // The one store that *initialises* a lexical slot: `this` in a derived
11181                // constructor, which only exists after `super()` has run. A second
11182                // initialisation is the error the reference reports as
11183                // "'this' can be initialized only once".
11184                let slot = self.slot_operand(op, a);
11185                let value = self.pop();
11186                if !matches!(self.get_loc(slot), Value::Uninitialized) {
11187                    return Err(Signal::Throw(self.make_error(
11188                        "ReferenceError",
11189                        "'this' can be initialized only once",
11190                    )));
11191                }
11192                self.put_loc(slot, value);
11193            }
11194            CheckCtor => {
11195                // A class constructor may only run under `new`, which is what makes
11196                // `class A {}; A()` a TypeError.
11197                if matches!(self.frame().new_target, Value::Undefined) {
11198                    return Err(Signal::Throw(self.make_error(
11199                        "TypeError",
11200                        "class constructors must be invoked with 'new'",
11201                    )));
11202                }
11203            }
11204            InitCtor => {
11205                // The body a derived class gets when it declares no constructor:
11206                // forward every argument to the parent constructor, keeping `new.target`.
11207                if matches!(self.frame().new_target, Value::Undefined) {
11208                    return Err(Signal::Throw(self.make_error(
11209                        "TypeError",
11210                        "class constructors must be invoked with 'new'",
11211                    )));
11212                }
11213                let Some(callee) = self.current_callee() else {
11214                    return Err(Signal::Throw(
11215                        self.make_error("TypeError", "no constructor to inherit from"),
11216                    ));
11217                };
11218                let parent = callee.proto().map_or(Value::Null, Value::Object);
11219                let new_target = self.frame().new_target.clone();
11220                let args = self.frame().passed().to_vec();
11221                let result = self.construct(parent, new_target, args)?;
11222                self.push(result);
11223            }
11224            SetLocUninitialized => {
11225                let slot = self.slot_operand(op, a);
11226                self.put_loc(slot, Value::Uninitialized);
11227            }
11228            CloseLoc => {
11229                // "Close" a binding: give it a *fresh* cell holding the current
11230                // value. Closures created before this point keep the old cell and the
11231                // ones created after see the new one, which is what makes every
11232                // iteration of `for (let i ...)` capture its own `i`, and what freezes
11233                // a block-scoped binding when the block ends.
11234                //
11235                // Clearing the slot instead (which this used to do) broke both: a
11236                // closure over a captured block variable read `undefined`, and a loop
11237                // terminated after one iteration.
11238                let slot = self.slot_operand(op, a);
11239                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11240                if index >= 0 {
11241                    let current = self.frame().cells[index as usize].get();
11242                    let fresh = self.new_cell(current);
11243                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11244                        *cell = fresh;
11245                    }
11246                }
11247            }
11248            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11249                let slot = self.slot_operand(op, a);
11250                let value = self.get_arg(slot);
11251                self.push(value);
11252            }
11253            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11254                let slot = self.slot_operand(op, a);
11255                let value = self.pop();
11256                self.put_arg(slot, value);
11257            }
11258            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11259                let slot = self.slot_operand(op, a);
11260                let value = self.pop();
11261                self.put_arg(slot, value.clone());
11262                self.push(value);
11263            }
11264
11265            // -- closure variables ------------------------------------------
11266            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11267                let slot = self.slot_operand(op, a);
11268                // A name a direct `eval` created shadows the binding the compiler chose.
11269                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11270                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11271                // and only a runtime lookup can know that.
11272                if let Some(cell) = self.eval_created_local(slot) {
11273                    self.push(cell.get());
11274                    return self.step();
11275                }
11276                let value = self.cell_value(slot)?;
11277                self.push(value);
11278            }
11279            GetVarRefCheck => {
11280                let slot = self.slot_operand(op, a);
11281                let value = self.cell_value(slot)?;
11282                if matches!(value, Value::Uninitialized) {
11283                    return Err(self.dead_zone(slot, VarSlot::Closure));
11284                }
11285                self.push(value);
11286            }
11287            PutVarRefCheckInit => {
11288                // The captured-form twin of `PutLocCheckInit`. Both exist because `super()`
11289                // may be written inside an arrow, and there `this` is a var-ref rather than
11290                // a local.
11291                let slot = self.slot_operand(op, a);
11292                let value = self.pop();
11293                // The wording differs from the local form because the reference reaches
11294                // this case through `get_var_ref_checkthis`, which reports the dead zone
11295                // rather than the double initialisation.
11296                if !matches!(self.cell_value(slot)?, Value::Uninitialized) {
11297                    return Err(Signal::Throw(
11298                        self.make_error("ReferenceError", "this is not initialized"),
11299                    ));
11300                }
11301                self.set_cell(slot, value)?;
11302            }
11303            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11304                let slot = self.slot_operand(op, a);
11305                let value = self.pop();
11306                if let Some(cell) = self.eval_created_local(slot) {
11307                    cell.set(value);
11308                    return self.step();
11309                }
11310                // Same two rules as `PutLocCheck`: a checked store to a captured binding
11311                // asks the cell about the dead zone, then refuses a `const` whose
11312                // initialiser has already run.
11313                if op == PutVarRefCheck {
11314                    let current = self.cell_value(slot)?;
11315                    if matches!(current, Value::Uninitialized) {
11316                        return Err(self.dead_zone(slot, VarSlot::Closure));
11317                    }
11318                    if self.is_read_only(slot, VarSlot::Closure) {
11319                        return Err(self.read_only(slot, VarSlot::Closure));
11320                    }
11321                }
11322                self.set_cell(slot, value)?;
11323            }
11324            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11325                let slot = self.slot_operand(op, a);
11326                let value = self.pop();
11327                if let Some(cell) = self.eval_created_local(slot) {
11328                    cell.set(value.clone());
11329                    self.push(value);
11330                    return self.step();
11331                }
11332                self.set_cell(slot, value.clone())?;
11333                self.push(value);
11334            }
11335
11336            // -- globals ----------------------------------------------------
11337            GetVar => {
11338                let value = self.get_global(a as usize)?;
11339                self.push(value);
11340            }
11341            GetVarUndef => {
11342                let slot = a as usize;
11343                // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11344                // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11345                // and `GetValue`s it, and only the unresolvable case is forgiven).
11346                //
11347                // The distinction is made by asking whether a binding exists at all: a name
11348                // in the realm's lexical table is declared, so a `ReferenceError` from
11349                // reading it is the dead zone talking. Swallowing every error made
11350                // `eval("typeof x; let x;")` print `"undefined"`.
11351                let declared = self.realm.globals.contains_key(&self.global_name(slot));
11352                let value = if declared {
11353                    self.get_global(slot)?
11354                } else {
11355                    match self.get_global(slot) {
11356                        Ok(value) => value,
11357                        Err(Signal::Throw(_)) => Value::Undefined,
11358                        Err(other) => return Err(other),
11359                    }
11360                };
11361                self.push(value);
11362            }
11363            DeleteVar => {
11364                // `delete name` for a name that is not a declared binding. A lexical
11365                // global lives in the reference table and cannot be deleted; anything
11366                // reachable only as a property of the global object is *implicit* —
11367                // `x = 1` with no declaration — and goes away if it is configurable,
11368                // which is what `delete` on an implicit global answers.
11369                let name = self.atom_text(a as usize);
11370                let global = self.realm.global.clone();
11371                let deleted = if self.realm.globals.contains_key(&name) {
11372                    false
11373                } else if global.own_property(&name).is_some() {
11374                    self.delete_property(&global, &name)?
11375                } else {
11376                    true
11377                };
11378                self.push(Value::Bool(deleted));
11379            }
11380            PutVar => {
11381                let value = self.pop();
11382                self.put_global(a as usize, value)?;
11383            }
11384            PutVarInit => {
11385                let slot = a as usize;
11386                let value = self.pop();
11387                self.init_global(slot, value)?;
11388            }
11389
11390            // -- arithmetic -------------------------------------------------
11391            Add => self.binary_add()?,
11392            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11393                let raw_right = self.pop();
11394                let raw_left = self.pop();
11395                // Two numbers need no `ToPrimitive` at all, which is every `x - y` and
11396                // `flags | mask` in real code.
11397                if is_number(&raw_left) && is_number(&raw_right) {
11398                    self.push(arithmetic(op, raw_left, raw_right)?);
11399                } else {
11400                    // §13.15.3 steps 1–3: **both** operands are made primitive before the
11401                    // disjointness check, left first. Getting the order wrong was observable
11402                    // — `ToPrimitive` on the right ran first, so a `valueOf` log read `b,a`
11403                    // and a throw from the *left* operand never happened
11404                    // (`S11.10.1_A2.3_T1`, `order-of-evaluation`).
11405                    //
11406                    // Doing the check on the *primitives* rather than on the raw values is
11407                    // the second half: `Object(5n) & Object(3n)` has a bigint on neither
11408                    // side of the stack yet, so the old check sent it down the `ToNumber`
11409                    // path and raised "cannot convert bigint to number"
11410                    // (`bigint-non-primitive`).
11411                    let left = self.primitive_of(raw_left)?;
11412                    let right = self.primitive_of(raw_right)?;
11413                    // BigInt arithmetic is a separate path, and not only for the type of
11414                    // the result: `ToNumber` of a bigint throws, so mixing the two must be
11415                    // an error rather than a silent conversion.
11416                    if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11417                        let value = self.bigint_arithmetic(op, left, right)?;
11418                        self.push(value);
11419                    } else {
11420                        let right = self.numeric(right)?;
11421                        let left = self.numeric(left)?;
11422                        self.push(arithmetic(op, left, right)?);
11423                    }
11424                }
11425            }
11426            Neg => {
11427                let raw = self.pop();
11428                match raw {
11429                    // A bigint negates exactly, however wide it is.
11430                    Value::BigInt(big) => {
11431                        let negated = big.negate();
11432                        self.push(self.bigint(negated));
11433                    }
11434                    other => {
11435                        let value = self.numeric_operand(other)?;
11436                        if let Value::BigInt(big) = &value {
11437                            let negated = big.negate();
11438                            self.push(self.bigint(negated));
11439                        } else {
11440                            self.push(negate(value));
11441                        }
11442                    }
11443                }
11444            }
11445            Plus => {
11446                let value = self.pop();
11447                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11448                // unary plus is defined to produce a *number*, which a bigint cannot
11449                // become without loss. It used to fall through to `NaN`.
11450                if matches!(value, Value::BigInt(_)) {
11451                    return Err(self.type_error("cannot convert bigint to number"));
11452                }
11453                let numeric = self.numeric_of(value)?;
11454                self.push(numeric);
11455            }
11456            Inc => {
11457                let raw = self.pop();
11458                let (_, updated) = self.advance_numeric(raw, true)?;
11459                self.push(updated);
11460            }
11461            Dec => {
11462                let raw = self.pop();
11463                let (_, updated) = self.advance_numeric(raw, false)?;
11464                self.push(updated);
11465            }
11466            PostInc | PostDec => {
11467                // `x -> x x+1`: the *new* value ends up on top, so the store the
11468                // compiler emits right after (`put_var`) writes the incremented
11469                // one, while the old value stays underneath for the expression's
11470                // own result. Getting this backwards makes `i++` a no-op, which
11471                // turns `while (i < 3)` into an infinite loop.
11472                let raw = self.pop();
11473                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11474                self.push(old);
11475                self.push(updated);
11476            }
11477            Not => {
11478                let raw = self.pop();
11479                match raw {
11480                    // `~x` on a bigint is `-x - 1`, exact at any width.
11481                    Value::BigInt(big) => {
11482                        let inverted = big.bitnot();
11483                        self.push(self.bigint(inverted));
11484                    }
11485                    other => {
11486                        let value = self.numeric_operand(other)?;
11487                        if let Value::BigInt(big) = &value {
11488                            let inverted = big.bitnot();
11489                            self.push(self.bigint(inverted));
11490                        } else {
11491                            self.push(Value::Int(!value.to_int32()));
11492                        }
11493                    }
11494                }
11495            }
11496            Lnot => {
11497                let value = self.pop();
11498                self.push(Value::Bool(!value.to_boolean()));
11499            }
11500
11501            // -- comparison -------------------------------------------------
11502            Lt | Lte | Gt | Gte => {
11503                let right = self.pop();
11504                let left = self.pop();
11505                let answer = self.relational(op, left, right)?;
11506                self.push(answer);
11507            }
11508            Eq | Neq => {
11509                let right = self.pop();
11510                let left = self.pop();
11511                let equal = self.abstract_equals(left, right)?;
11512                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11513            }
11514            StrictEq => {
11515                let right = self.pop();
11516                let left = self.pop();
11517                self.push(Value::Bool(left.strict_equals(&right)));
11518            }
11519            StrictNeq => {
11520                let right = self.pop();
11521                let left = self.pop();
11522                self.push(Value::Bool(!left.strict_equals(&right)));
11523            }
11524            IsUndefined => {
11525                // `=== undefined`, which is what a destructuring default tests. It is
11526                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11527                let value = self.pop();
11528                self.push(Value::Bool(matches!(value, Value::Undefined)));
11529            }
11530            IsUndefinedOrNull => {
11531                let value = self.pop();
11532                self.push(Value::Bool(value.is_nullish()));
11533            }
11534            Typeof => {
11535                let value = self.pop();
11536                self.push(self.string(value.type_of()));
11537            }
11538            ToObject => {
11539                // A destructuring *object* pattern starts here, which is why
11540                // `var {} = null` throws. Only `undefined` and `null` are refused; a
11541                // primitive is boxed.
11542                let value = self.pop();
11543                let object = self.object_from(&value)?;
11544                self.push(Value::Object(object));
11545            }
11546            Instanceof => {
11547                let constructor = self.pop();
11548                let object = self.pop();
11549                // `InstanceofOperator`, not `OrdinaryHasInstance`: the operator consults
11550                // `Symbol.hasInstance` first and throws for a right-hand side that is not an
11551                // object (step 1) or not callable (step 4). Calling `instance_of` directly
11552                // skipped both the protocol and the two `TypeError`s.
11553                let answer = self.instance_of_operator(&object, &constructor)?;
11554                self.push(Value::Bool(answer));
11555            }
11556            In => {
11557                let object = self.pop();
11558                let key = self.pop();
11559                let answer = self.has_property(&key, &object)?;
11560                self.push(Value::Bool(answer));
11561            }
11562            WithHasVar => {
11563                // `obj -> bool`: does this `with` object bind the name?
11564                //
11565                // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11566                // `HasProperty`: step 2 skips the property entirely when the object's
11567                // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11568                // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11569                // the thirty-odd `unscopables-with` cases assert.
11570                //
11571                // One instruction rather than a hand-expanded sequence of `in`, a
11572                // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11573                // by both the read/write guard and `delete`, and a compiler-side expansion
11574                // would be about ten instructions per name per `with` object.
11575                let object = self.pop();
11576                let name = self.atom_text(a as usize);
11577                let bound = self.with_has_binding(&object, &name)?;
11578                self.push(Value::Bool(bound));
11579            }
11580            WithGetVar => {
11581                // `obj -> value`: the second half of `GetBindingValue`.
11582                let object = self.pop();
11583                let name = self.atom_text(a as usize);
11584                let value = self.with_get_binding(&object, &name)?;
11585                self.push(value);
11586            }
11587            WithPutVar => {
11588                // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11589                // is `put_field`'s (value on top), not the reference's, so that the
11590                // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11591                // member-expression forms.
11592                let value = self.pop();
11593                let object = self.pop();
11594                let name = self.atom_text(a as usize);
11595                self.with_put_binding(&object, &name, value)?;
11596            }
11597
11598            // -- control flow -----------------------------------------------
11599            Goto | Goto8 | Goto16 => {
11600                self.frame_mut().pc = a as usize;
11601            }
11602            IfTrue | IfTrue8 => {
11603                let value = self.pop();
11604                if value.to_boolean() {
11605                    self.frame_mut().pc = a as usize;
11606                }
11607            }
11608            IfFalse | IfFalse8 => {
11609                let value = self.pop();
11610                if !value.to_boolean() {
11611                    self.frame_mut().pc = a as usize;
11612                }
11613            }
11614            Catch => {
11615                // Pushes the handler target onto the value stack; `unwind` finds it.
11616                self.push(Value::CatchOffset(a));
11617            }
11618            Gosub => {
11619                self.push(Value::ReturnAddress(next as u32));
11620                self.frame_mut().pc = a as usize;
11621            }
11622            Ret => {
11623                let value = self.pop();
11624                match value {
11625                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11626                    _ => {
11627                        return Err(Signal::Throw(
11628                            self.make_error("InternalError", "invalid return address"),
11629                        ));
11630                    }
11631                }
11632            }
11633            NipCatch => {
11634                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11635                // including the marker, keeping the top value.
11636                let top = self.pop();
11637                loop {
11638                    match self.pop() {
11639                        Value::CatchOffset(_) | Value::Undefined => break,
11640                        _ => {}
11641                    }
11642                    if self.frame().stack.is_empty() {
11643                        break;
11644                    }
11645                }
11646                self.push(top);
11647            }
11648            Throw => {
11649                let value = self.pop();
11650                return Err(Signal::Throw(value));
11651            }
11652            ThrowError => {
11653                let name = self.atom_text(a as usize);
11654                let (class, message) = match b {
11655                    0 => ("TypeError", format!("'{name}' is read-only")),
11656                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11657                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
11658                    // `delete super.x` is a syntax-level mistake the reference reports
11659                    // with this wording, not a property-access failure.
11660                    3 => (
11661                        "ReferenceError",
11662                        "unsupported reference to 'super'".to_string(),
11663                    ),
11664                    4 => (
11665                        "TypeError",
11666                        "iterator does not have a throw method".to_string(),
11667                    ),
11668                    5 => (
11669                        "ReferenceError",
11670                        "invalid assignment left-hand side".to_string(),
11671                    ),
11672                    _ => ("TypeError", format!("invalid operation on '{name}'")),
11673                };
11674                return Err(Signal::Throw(self.make_error(class, &message)));
11675            }
11676            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11677            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11678            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11679            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11680            Await => return Ok(Step::Suspend(SuspendKind::Await)),
11681            ReturnAsync => {
11682                // The reference's `return_async` returns `undefined` and lets the resume
11683                // machinery pick the real value off `sp[-1]`, which is how it tells a
11684                // completion from a suspension. Carrying the value explicitly says the
11685                // same thing without the implicit stack slot.
11686                let value = self.pop();
11687                return Ok(Step::Return(value));
11688            }
11689            Return => {
11690                let value = self.pop();
11691                return Ok(Step::Return(value));
11692            }
11693            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11694
11695            // -- calls ------------------------------------------------------
11696            Call | Call0 | Call1 | Call2 | Call3 => {
11697                let argc = self.argc_operand(op, a);
11698                let args = self.pop_n(argc);
11699                let callee = self.pop();
11700                // A plain call has no receiver; the callee decides what to do with
11701                // `undefined` (a sloppy function substitutes the global object).
11702                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11703                    self.push(result);
11704                }
11705            }
11706            CallConstructor => {
11707                // `constructor this_obj args… -> object`. The duplicated
11708                // constructor is `new.target`; this milestone does not expose it,
11709                // so the extra copy is simply consumed here.
11710                let argc = a as usize;
11711                let args = self.pop_n(argc);
11712                let new_target = self.pop();
11713                let callee = self.pop();
11714                let result = self.construct(callee, new_target, args)?;
11715                self.push(result);
11716            }
11717            CallMethod => {
11718                let argc = a as usize;
11719                let args = self.pop_n(argc);
11720                let callee = self.pop();
11721                let this = self.pop();
11722                if let Some(result) = self.call_or_push(callee, this, args)? {
11723                    self.push(result);
11724                }
11725            }
11726            Apply => {
11727                // `func this array -> result`, the spread-call form: the compiler
11728                // builds one array of arguments, and all that is left here is to
11729                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11730                let array = self.pop();
11731                let this = self.pop();
11732                let callee = self.pop();
11733                let args = self.array_like_to_args(&array)?;
11734                if a & 1 != 0 {
11735                    let result = self.construct(callee, this, args)?;
11736                    self.push(result);
11737                } else if let Some(result) = self.call_or_push(callee, this, args)? {
11738                    self.push(result);
11739                }
11740            }
11741            TailCall | TailCallMethod => {
11742                // `tail_call` is `call` whose result is returned immediately — the
11743                // reference jumps straight to `done` instead of storing the value and
11744                // running on. The callee still gets its own frame, so deep tail
11745                // recursion hits the stack limit exactly like plain recursion does;
11746                // marking this frame lets the return path unwind without needing
11747                // instructions after the call.
11748                let argc = if op == TailCallMethod {
11749                    a as usize
11750                } else {
11751                    self.argc_operand(op, a)
11752                };
11753                let args = self.pop_n(argc);
11754                let callee = self.pop();
11755                let this = if op == TailCallMethod {
11756                    self.pop()
11757                } else {
11758                    Value::Undefined
11759                };
11760                if let Value::Object(function) = &callee
11761                    && let Some((code, env)) = bytecode_of(function)
11762                {
11763                    // A generator or async body is not run here at all: calling it only
11764                    // *creates* the generator/coroutine, so it must not inherit this
11765                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
11766                    // onto `f`'s frame, and the first `yield`/`await` then reported
11767                    // "a generator body ran as an ordinary call".
11768                    if code.code.kind.is_generator() || code.code.kind.is_async() {
11769                        let value = self.call_value(callee, this, args)?;
11770                        return Ok(Step::Return(value));
11771                    }
11772                    self.frame_mut().tail = true;
11773                    self.push_frame(code, env, this, args, callee)?;
11774                    return Ok(Step::Continue);
11775                }
11776                // A native callee has no frame to reuse, so its value is simply
11777                // returned.
11778                let value = self.call_value(callee, this, args)?;
11779                return Ok(Step::Return(value));
11780            }
11781
11782            // -- objects ----------------------------------------------------
11783            SpecialObject => {
11784                let value = self.special_object(a)?;
11785                self.push(value);
11786            }
11787            PrivateSymbol => {
11788                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11789                // symbol each time it is evaluated, which is why the compiler evaluates it
11790                // once (at class definition) and stores it in a class-scope binding.
11791                let name = self.atom_text(a as usize);
11792                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11793                self.push(Value::Symbol(symbol));
11794            }
11795            GetPrivateField => {
11796                // `obj symbol -> value`. A missing private field is a TypeError, which is what
11797                // makes `#x` inaccessible on any object not built by this class.
11798                let symbol = self.pop();
11799                let object = self.pop();
11800                let value = self.read_private_field(&object, &symbol)?;
11801                self.push(value);
11802            }
11803            PutPrivateField => {
11804                // `obj value symbol ->`, and the store is a plain assignment to a property the
11805                // class already created, so there is no setter to consult.
11806                let symbol = self.pop();
11807                let value = self.pop();
11808                let object = self.pop();
11809                self.write_private_field(&object, &symbol, value)?;
11810            }
11811            DefinePrivateField => {
11812                // `obj symbol value -> obj`: a field initialiser creates the property, and
11813                // redefining one is a TypeError ("already exists").
11814                let value = self.pop();
11815                let symbol = self.pop();
11816                let object = self.pop();
11817                self.define_private_field(&object, &symbol, value)?;
11818                self.push(object);
11819            }
11820            PrivateIn => {
11821                // `obj key -> bool`: `#x in o`. The second operand decides which question is
11822                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11823                // is a field, so this is an own-property test; a *function* is a method or
11824                // accessor, so this is a brand check.
11825                let key = self.pop();
11826                let object = self.pop();
11827                let Some(target) = object.as_object() else {
11828                    return Err(Signal::Throw(
11829                        self.make_error("TypeError", "invalid 'in' operand"),
11830                    ));
11831                };
11832                let present = match &key {
11833                    Value::Object(_) => self.check_brand(target, &key)?,
11834                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11835                };
11836                self.push(Value::Bool(present));
11837            }
11838            AddBrand => {
11839                // `obj home ->`: create the class brand on `home` if it has none, then give
11840                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11841                // class definition: only the prototype's copy of the symbol is wanted.
11842                let home = self.pop();
11843                let object = self.pop();
11844                self.add_brand(&object, &home)?;
11845            }
11846            CheckBrand => {
11847                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11848                // Both stay, because the caller needs them — `nip` halves a read into its
11849                // value and `call_method` uses the pair as receiver and callee.
11850                let function = self.peek(0);
11851                let object = self.peek(1);
11852                let Some(target) = object.as_object() else {
11853                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11854                };
11855                if !self.check_brand(target, &function)? {
11856                    return Err(Signal::Throw(
11857                        self.make_error("TypeError", "invalid brand on object"),
11858                    ));
11859                }
11860            }
11861            GetLength => {
11862                // `get_length` is the `.length` read; an array and a string answer
11863                // from their own length, anything else from the property.
11864                let target = self.pop();
11865                let value = match &target {
11866                    Value::Object(object) => match object.array_length() {
11867                        Some(length) => crate::object::length_value(length),
11868                        None => self.read_field(&target, "length")?,
11869                    },
11870                    Value::String(text) => Value::Int(text.utf16_len() as i32),
11871                    _ => self.read_field(&target, "length")?,
11872                };
11873                self.push(value);
11874            }
11875            GetField | GetField2 => {
11876                let object = self.pop();
11877                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11878                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11879                // just below is what lets the borrow outlive the `&mut self` the lookup
11880                // needs — one refcount bump instead of a key clone plus its drop, on the
11881                // hottest property path there is: every `o.x` and every `o.m()` receiver.
11882                let code = self.frame().code.clone();
11883                let key = &code.atom_keys[a as usize];
11884                let value = self.read_field_cached(&object, key, next)?;
11885                if op == GetField2 {
11886                    self.push(object);
11887                }
11888                self.push(value);
11889            }
11890            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11891                let key = self.pop();
11892                let object = self.pop();
11893                // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
11894                // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
11895                // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
11896                // throws the TypeError, not the key's exception
11897                // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
11898                // `PutArrayEl` deliberately does not do this.
11899                //
11900                // Only nullish is checked here, and the full boxing is still left to
11901                // `read_field_key`: a string base has an index fast path that turning it
11902                // into a `String` object up front would throw away.
11903                if object.is_nullish() {
11904                    return Err(Signal::Throw(self.make_error(
11905                        "TypeError",
11906                        &format!("cannot read property of {}", object.to_js_string()),
11907                    )));
11908                }
11909                let key = self.propkey(&key)?;
11910                let value = self.read_field_key(&object, &key)?;
11911                if matches!(op, GetArrayEl2 | GetArrayEl3) {
11912                    self.push(object);
11913                }
11914                if op == GetArrayEl3 {
11915                    // The key goes back in its *value* form, which the compiler stores
11916                    // into the target of a destructuring assignment.
11917                    self.push(match &key {
11918                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11919                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
11920                    });
11921                }
11922                self.push(value);
11923            }
11924            PutField => {
11925                let value = self.pop();
11926                let object = self.pop();
11927                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11928                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11929                // only reads. `this.value = …` is the write half of the hottest loop in
11930                // `property:method-call`, and `own_property_key` was 4.8% of the case.
11931                let code = self.frame().code.clone();
11932                let key = &code.atom_keys[a as usize];
11933                self.write_field_key(&object, key, value)?;
11934            }
11935            PutArrayEl => {
11936                let value = self.pop();
11937                let key = self.pop();
11938                let object = self.pop();
11939                let key = self.propkey(&key)?;
11940                self.write_field_key(&object, &key, value)?;
11941            }
11942            DefineField => {
11943                let value = self.pop();
11944                let object = self.pop();
11945                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11946                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11947                // three U+FFFD — a property under a different name from the one
11948                // `o["\uD800"]` reads.
11949                let code = self.frame().code.clone();
11950                let key = code.atom_keys[a as usize].clone();
11951                // No naming here. `{m: function(){}}` is named by the *compiler*, which
11952                // emits `set_name` — and only where `NamedEvaluation` applies, so
11953                // `{m: (0, function(){})}` stays anonymous. Naming every function that
11954                // reaches a property definition got that case wrong, and the compiler is
11955                // the only place that can tell the two apart.
11956                if let Some(target) = object.as_object() {
11957                    // Only an *array* stores into the element vector. A numeric key
11958                    // on an ordinary object is an ordinary property, which is what
11959                    // makes `{1: 'a'}` iterate as a key rather than disappear.
11960                    let stored = target.is_array()
11961                        && key.as_str().and_then(array_index).is_some_and(|index| {
11962                            target.array_set(self.heap, index as usize, value.clone())
11963                        });
11964                    if !stored {
11965                        // `CreateDataPropertyOrThrow`, not a raw table insert: a class
11966                        // field is defined with `[[DefineOwnProperty]]`, so a frozen
11967                        // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
11968                        // must fail on `g`) and a **proxy** receiver runs its
11969                        // `defineProperty` trap (`class-field-is-observable-by-proxy`
11970                        // counts the trap's calls). `define_data_key` writes straight into
11971                        // the table, which did neither.
11972                        // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
11973                        // may *throw*, and that exception is the answer
11974                        // (`public-class-field-initialization-is-visible-to-proxy` throws
11975                        // a `Test262Error` from the trap and expects it, not a `TypeError`).
11976                        let defined =
11977                            self.object_define_own_property(target, &key, Property::data(value))?;
11978                        if !defined {
11979                            let target = Value::Object(target.clone());
11980                            return Err(Signal::Throw(self.make_error(
11981                                "TypeError",
11982                                &format!(
11983                                    "cannot define property '{key}' of {}",
11984                                    target.to_js_string()
11985                                ),
11986                            )));
11987                        }
11988                    }
11989                }
11990                self.push(object);
11991            }
11992            DefineArrayEl => {
11993                // `obj key value -> obj key`. The *value* form of the key is what goes
11994                // back on the stack — the compiler stores it into the pattern's binding —
11995                // so the symbol is not stringified on the way through.
11996                let value = self.pop();
11997                let key_value = self.pop();
11998                let object = self.peek(0);
11999                let key = self.propkey(&key_value)?;
12000                self.write_field_key(&object, &key, value)?;
12001                self.push(key_value);
12002            }
12003            SetHomeObject => {
12004                // `obj func -> obj func`: records the object a method was defined on so
12005                // `super` inside it resolves against that object's prototype.
12006                let function = self.peek(0);
12007                let home = self.peek(1);
12008                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
12009                    function.set_home_object(Some(home.clone()));
12010                }
12011            }
12012            Regexp => {
12013                // `pattern flags -> regexp`. A literal compiles here rather than through the
12014                // constructor, which is both what the reference's dedicated opcode is for
12015                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
12016                let flags = self.pop();
12017                let pattern = self.pop();
12018                let pattern = self.checked_to_wtf8(&pattern)?;
12019                let flags = self.to_js_string(&flags)?;
12020                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
12021                self.push(Value::Object(object));
12022            }
12023            UsingDisposeInit => {
12024                // The error state a disposal accumulates into. Uninitialised means "no
12025                // failure yet"; anything else is the exception being propagated.
12026                self.push(Value::Uninitialized);
12027            }
12028            UsingCheck => {
12029                // `value -> value, method`: validate and snapshot the disposer now, so a
12030                // later change to `Symbol.dispose` cannot change what gets called, and so a
12031                // value that is not disposable fails before the body runs.
12032                let value = self.pop();
12033                let method = self.using_method_for(&value, a as u8 == 1)?;
12034                self.push(value);
12035                self.push(method);
12036            }
12037            UsingDispose => {
12038                // `error_state -> error_state'`: dispose the variable at `slot` — its value
12039                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
12040                // the pending error.
12041                let slot = self.slot_operand(op, a);
12042                let error_state = self.pop();
12043                let merged = self.using_dispose_once(slot, error_state)?;
12044                self.push(merged);
12045            }
12046            UsingDisposeMerge => {
12047                let new_error = self.pop();
12048                let error_state = self.pop();
12049                let merged = self.merge_dispose_error(new_error, error_state);
12050                self.push(merged);
12051            }
12052            UsingDisposeEnd => {
12053                // A disposal that failed replaces the block's normal completion, so the
12054                // error state becomes a real throw here rather than at the call site.
12055                let error_state = self.pop();
12056                if !matches!(error_state, Value::Uninitialized) {
12057                    return Err(Signal::Throw(error_state));
12058                }
12059            }
12060            UsingDisposeAsync => {
12061                // `await using` needs a promise to await and this runtime has no
12062                // `Promise` builtin, so the disposer is called synchronously and its result
12063                // discarded. That is correct for a disposer that returns nothing and is
12064                // reported as a gap rather than silently skipped.
12065                let slot = self.slot_operand(op, a);
12066                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
12067                self.push(error_state);
12068            }
12069            GetSuper => {
12070                // `obj -> obj's prototype`: the starting point of a `super` lookup.
12071                let object = self.pop();
12072                let proto = match &object {
12073                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12074                    _ => Value::Null,
12075                };
12076                self.push(proto);
12077            }
12078            GetSuperValue => {
12079                // `receiver proto key -> value`, searching from `proto` but reporting to
12080                // `receiver`, which is what `super.g` must do for a getter to see `this`.
12081                //
12082                // Three values in, one out: the receiver is *consumed*, not left under the
12083                // result. Leaving it there was invisible for `super.x` in `return` or
12084                // statement position (the result is what gets popped) and corrupted the
12085                // frame everywhere else — `print(super.x)` left the class where the call
12086                // opcode looks for the receiver and called the class itself.
12087                let key = self.pop();
12088                let proto = self.pop();
12089                let receiver = self.pop();
12090                let value = self.super_read(&receiver, &proto, &key)?;
12091                self.push(value);
12092            }
12093            PutSuperValue => {
12094                // `receiver proto key value ->`: a store that starts at `proto` but
12095                // assigns to `receiver`.
12096                let value = self.pop();
12097                let key = self.pop();
12098                let proto = self.pop();
12099                let receiver = self.pop();
12100                self.super_write(&receiver, &proto, &key, value)?;
12101            }
12102            DefineClass => {
12103                // `parent ctor -> ctor proto`: the constructor becomes the class and a
12104                // fresh prototype object lands on top for the methods to go on.
12105                let name = self.atom_text(a as usize);
12106                let (ctor, proto) = self.define_class(&name, b)?;
12107                self.push(ctor);
12108                self.push(Value::Object(proto));
12109            }
12110            DefineClassComputed => {
12111                // `parent ctor key -> ctor proto key`: the computed name stays put so
12112                // `define_field`-style consumers can still read it.
12113                let key = self.pop();
12114                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12115                let (ctor, proto) = self.define_class(&name, b)?;
12116                self.push(ctor);
12117                self.push(Value::Object(proto));
12118                self.push(key);
12119            }
12120            DefineMethod => {
12121                let function = self.pop();
12122                let object = self.pop();
12123                // The exact key, like `define_field`: a quoted method key may hold an
12124                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12125                // that `o["\uD800"]` finds.
12126                let code = self.frame().code.clone();
12127                let key = code.atom_keys[a as usize].clone();
12128                // A method's `[[HomeObject]]` is the object it was defined on, which is
12129                // what `super` inside it resolves against.
12130                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12131                    function.set_home_object(Some(object.clone()));
12132                }
12133                let name = match key.as_wtf8() {
12134                    Some(text) => text.clone(),
12135                    // A symbol atom — one of the well-known symbols, which the lexer keeps
12136                    // as an atom rather than a runtime value. Its name is the bracketed
12137                    // description, like any other symbol key.
12138                    None => symbol_key_name(&key),
12139                };
12140                self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12141                if let Some(array) = object.as_object()
12142                    && !define_function_property(array, &key, function, b)
12143                {
12144                    return Err(self.type_error("property is not configurable"));
12145                }
12146                self.push(object);
12147            }
12148            DefineMethodComputed => {
12149                let function = self.pop();
12150                let key = self.pop();
12151                let object = self.pop();
12152                let key = self.propkey(&key)?;
12153                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12154                // the name: `super` inside a computed method resolves through it. Without
12155                // this, `class B extends A { [k]() { return super.m() } }` read the
12156                // home object as null and threw.
12157                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12158                    function.set_home_object(Some(object.clone()));
12159                }
12160                // A symbol key names the method `[description]`, or `""` without one —
12161                // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12162                // `set_name_computed`. Falling back to `to_string` here named every
12163                // `{ [sym](){} }` method `Symbol()` instead.
12164                match &key {
12165                    PropertyKey::Symbol(_) => {
12166                        // The accessor prefix still applies: `get [Symbol.iterator](){}`
12167                        // is named `"get [Symbol.iterator]"`.
12168                        let name = accessor_prefixed(&symbol_key_name(&key), a);
12169                        self.set_function_name_wtf8(&function, &name);
12170                    }
12171                    PropertyKey::String(text) => {
12172                        let name = accessor_prefixed(text, a);
12173                        self.set_function_name_wtf8(&function, &name);
12174                    }
12175                }
12176                if let Some(array) = object.as_object()
12177                    && !define_function_property(array, &key, function, a)
12178                {
12179                    return Err(self.type_error("property is not configurable"));
12180                }
12181                self.push(object);
12182            }
12183            SetProto => {
12184                let proto = self.pop();
12185                let object = self.pop();
12186                if let Some(target) = object.as_object() {
12187                    target.set_proto(proto.as_object().cloned());
12188                }
12189                self.push(object);
12190            }
12191            CopyDataProperties => {
12192                let exclusion = self.pop();
12193                let source = self.pop();
12194                let target = self.peek(0);
12195                self.copy_properties(&target, &source, &exclusion)?;
12196                self.push(source);
12197                self.push(exclusion);
12198            }
12199            ToPropkey => {
12200                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12201                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12202                // ordinary `"Symbol(b)"` property.
12203                let value = self.pop();
12204                let key = match self.propkey(&value)? {
12205                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12206                    PropertyKey::String(text) => self.string_wtf8(text),
12207                };
12208                self.push(key);
12209            }
12210            SetName => {
12211                let function = self.peek(0);
12212                let name = self.atom_wtf8(a as usize);
12213                self.set_function_name_wtf8(&function, &name);
12214            }
12215            SetNameComputed => {
12216                let key = self.peek(1);
12217                let function = self.peek(0);
12218                let name = self.function_name_from_key(&key)?;
12219                self.set_function_name_wtf8(&function, &name);
12220            }
12221
12222            // -- arrays -----------------------------------------------------
12223            ArrayFrom => {
12224                let count = a as usize;
12225                let elements = self.pop_n(count);
12226                let array = self.new_array(elements);
12227                self.push(Value::Object(array));
12228            }
12229            Append => {
12230                // `array index iterable -> array new_index`
12231                let iterable = self.pop();
12232                self.pop();
12233                let array = self.peek(0);
12234                let added = self.append_enumerate(&array, &iterable)?;
12235                self.push(Value::Int(added));
12236            }
12237
12238            // -- iteration --------------------------------------------------
12239            ForInStart => {
12240                let value = self.pop();
12241                let record = self.for_in_record(&value)?;
12242                self.push(Value::Object(record));
12243            }
12244            ForInNext => {
12245                // `record -> record key done`. The flag is *done*, not "found":
12246                // the compiler tests it with `if_false` to jump back into the body,
12247                // so reporting `true` while keys remain would end the loop at once.
12248                let record = self.peek(0);
12249                match self.for_in_advance(&record)? {
12250                    Some(key) => {
12251                        let text = self.string(key);
12252                        self.push(text);
12253                        self.push(Value::Bool(false));
12254                    }
12255                    None => {
12256                        self.push(Value::Undefined);
12257                        self.push(Value::Bool(true));
12258                    }
12259                }
12260            }
12261            ForOfStart => {
12262                let value = self.pop();
12263                let iterator = self.get_iterator(&value)?;
12264                self.push(iterator.object);
12265                self.push(iterator.next);
12266                self.push(Value::CatchOffset(0));
12267            }
12268            ForOfNext => {
12269                // `iter next catch_offset -> iter next catch_offset value done`.
12270                //
12271                // The operand is how many values sit *above* the iterator triple: a
12272                // destructuring rest element keeps its target array and running index
12273                // there while draining the iterator, so the triple is not at the top.
12274                let extra = a as usize;
12275                let iterator_slot = 2 + extra;
12276                // An exhausted iterator is replaced by `undefined` (see below), so a
12277                // second step must not call `next` again — `Array.from` and a
12278                // destructuring pattern both keep stepping past the end.
12279                let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12280                    Ok((Value::Undefined, true))
12281                } else {
12282                    let iterator = Iterator {
12283                        object: self.peek(iterator_slot),
12284                        next: self.peek(1 + extra),
12285                    };
12286                    self.iterator_step(&iterator)
12287                };
12288                let (value, done) = match stepped {
12289                    Ok(stepped) => stepped,
12290                    Err(signal) => {
12291                        // An exception from `next()` is not an abrupt completion of the
12292                        // *body*, so §7.4.6 does not apply and the iterator must not be
12293                        // closed: `[ , ] = iterable` with a throwing `next` expects
12294                        // `returnCount === 0`. Clearing the slot is how the reference says
12295                        // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12296                        // returns -1), and it is also what makes the destructor below — the
12297                        // exception path's `catch_offset 0` close — a no-op here.
12298                        self.clear_iterator_slot(iterator_slot);
12299                        return Err(signal);
12300                    }
12301                };
12302                if done {
12303                    // The result's `value` is meaningless once the iterator is done:
12304                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12305                    // rather than binding the generator's return value.
12306                    let top = self.frame().stack.len() - 1 - iterator_slot;
12307                    self.frame_mut().stack[top] = Value::Undefined;
12308                    self.push(Value::Undefined);
12309                    self.push(Value::Bool(true));
12310                } else {
12311                    self.push(value);
12312                    self.push(Value::Bool(false));
12313                }
12314            }
12315            IteratorNext => {
12316                // `iter next catch val -> iter next catch val'`: replace the argument with
12317                // the result of `next(val)`. The triple below stays put, which is why the
12318                // three instructions of the `yield*` loop all address the stack the same way.
12319                let value = self.pop();
12320                let object = self.peek(2);
12321                let next = self.peek(1);
12322                let result = self.call_value(next, object, vec![value])?;
12323                self.push(result);
12324            }
12325            IteratorCall => {
12326                // `iter next catch val -> iter next catch val' flag`.
12327                //
12328                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12329                // The flag is `true` when the method was missing, which is how the
12330                // caller learns that the inner iterator cannot take part in the
12331                // unwinding.
12332                let value = self.pop();
12333                let object = self.peek(2);
12334                let key = if a & 1 != 0 { "throw" } else { "return" };
12335                let method = self.read_field(&object, key)?;
12336                if matches!(method, Value::Undefined | Value::Null) {
12337                    self.push(value);
12338                    self.push(Value::Bool(true));
12339                } else {
12340                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12341                    let result = self.call_value(method, object, argument)?;
12342                    self.push(result);
12343                    self.push(Value::Bool(false));
12344                }
12345            }
12346            IteratorCheckObject => {
12347                if !matches!(self.peek(0), Value::Object(_)) {
12348                    return Err(Signal::Throw(
12349                        self.make_error("TypeError", "iterator must return an object"),
12350                    ));
12351                }
12352            }
12353            IteratorClose => {
12354                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12355                // calling the iterator's `return` so it can release whatever it holds.
12356                //
12357                // The catch offset goes first, so an exception from `return` is not caught
12358                // by the loop being abandoned. This used to pop the three operands and call
12359                // nothing at all, which made `break` out of a `for of` invisible to an
12360                // iterator with a `return` method.
12361                self.pop();
12362                self.pop();
12363                let iterator = self.pop();
12364                if !matches!(iterator, Value::Undefined) {
12365                    let method = self.read_field(&iterator, "return")?;
12366                    if !matches!(method, Value::Undefined | Value::Null) {
12367                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
12368                        // §7.4.6: a `return` that answers a non-object is a TypeError.
12369                        if !matches!(result, Value::Object(_)) {
12370                            return Err(Signal::Throw(
12371                                self.make_error("TypeError", "iterator must return an object"),
12372                            ));
12373                        }
12374                    }
12375                }
12376            }
12377            Import => {
12378                // `import(specifier, options)`: the options slot is on top. Both are
12379                // `GetValue`-ed by the compiler, which is why this pops values rather than
12380                // references — and why the validation of `options` (§13.3.10.1 step 10)
12381                // happens inside `dynamic_import`, where its failures can be turned into a
12382                // rejection instead of a throw.
12383                let options = self.pop();
12384                let specifier = self.pop();
12385                let promise = self.dynamic_import(specifier, options)?;
12386                self.push(promise);
12387            }
12388            ForAwaitOfStart => {
12389                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12390                // `Symbol.iterator` fallback.
12391                let value = self.pop();
12392                let iterator = self.get_async_iterator(&value)?;
12393                self.push(iterator.object);
12394                self.push(iterator.next);
12395                self.push(Value::CatchOffset(0));
12396            }
12397            ForAwaitOfNext => {
12398                // `for await` steps the iterator and leaves the *result* wrapped in a
12399                // promise, so the `await` the compiler emits right after this can suspend
12400                // on it. Unwrapping happens in `iterator_get_value_done`.
12401                let extra = a as usize;
12402                let iterator_slot = 2 + extra;
12403                // The enumerator marker is **disabled for the step**, and
12404                // `iterator_get_value_done` puts it back once the result has survived the
12405                // awaiting. Both halves are load-bearing for the async case:
12406                //
12407                // * a rejection is not "the body threw", so the loop must not close the
12408                //   iterator *again* — the wrapper already did;
12409                // * but until the result arrives the record is live, so a later failure
12410                //   still has to close it.
12411                //
12412                // The reference says the same in one line each
12413                // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12414                // offset so that exceptions do not close the iterator */`).
12415                self.clear_iterator_slot(extra);
12416                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12417                    Value::Undefined
12418                } else {
12419                    let iterator = Iterator {
12420                        object: self.peek(iterator_slot),
12421                        next: self.peek(1 + extra),
12422                    };
12423                    let next = iterator.next.clone();
12424                    self.call_value(next, iterator.object, Vec::new())?
12425                };
12426                let promise = self.promise_resolve_value(result)?;
12427                self.push(promise);
12428            }
12429            IteratorGetValueDone => {
12430                // `result -> value done`. A missing result object means the iterator was
12431                // already exhausted, which the loop treats as `done`.
12432                let result = self.pop();
12433                // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12434                // from here on the record is closeable again.
12435                {
12436                    let depth = self.frame().stack.len();
12437                    if depth >= 2 {
12438                        self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12439                    }
12440                }
12441                let done = match &result {
12442                    Value::Object(object) => self
12443                        .get_property(object, "done")?
12444                        .is_some_and(|value| value.to_boolean()),
12445                    _ => true,
12446                };
12447                if done {
12448                    // Clear the iterator object so the `iterator_close` the loop emits on
12449                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12450                    // on normal completion, and this is where a normal completion is
12451                    // recognised — the same trick `for_of_next` uses, which also replaces
12452                    // the slot with `undefined`.
12453                    //
12454                    // The layout is fixed because only `for await` emits this opcode:
12455                    // `iter next catch [result]`, so the iterator is three below the top.
12456                    let depth = self.frame().stack.len();
12457                    if depth >= 3 {
12458                        self.frame_mut().stack[depth - 3] = Value::Undefined;
12459                    }
12460                    self.push(Value::Undefined);
12461                    self.push(Value::Bool(true));
12462                } else {
12463                    let Value::Object(object) = &result else {
12464                        self.push(Value::Undefined);
12465                        self.push(Value::Bool(true));
12466                        return Ok(Step::Continue);
12467                    };
12468                    let value = self
12469                        .get_property(object, "value")?
12470                        .unwrap_or(Value::Undefined);
12471                    self.push(value);
12472                    self.push(Value::Bool(false));
12473                }
12474            }
12475
12476            Delete => {
12477                // `delete obj[key]`, where the key was just pushed. Deleting an array
12478                // index leaves a *hole* rather than closing the gap, and a
12479                // non-configurable property answers `false` and stays.
12480                let key = self.pop();
12481                let target = self.pop();
12482                let key = self.propkey(&key)?;
12483                let text_label = key.as_str().unwrap_or("").to_string();
12484                let deleted = match &target {
12485                    Value::Object(object) => {
12486                        let object = object.clone();
12487                        self.delete_property_key(&object, &key)?
12488                    }
12489                    // A string's `length` and its index properties are
12490                    // non-configurable, so deleting one answers `false`.
12491                    Value::String(text) => {
12492                        !(text_label == "length"
12493                            || array_index(&text_label)
12494                                .is_some_and(|index| (index as usize) < text.utf16_len()))
12495                    }
12496                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
12497                    // object to delete from, and only a *boxable* primitive has one.
12498                    Value::Undefined | Value::Null => {
12499                        return Err(Signal::Throw(
12500                            self.make_error("TypeError", "cannot convert to object"),
12501                        ));
12502                    }
12503                    // Any other primitive has no own properties; deleting nothing
12504                    // succeeds.
12505                    _ => true,
12506                };
12507                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12508                // `TypeError` rather than a `false` result. Sloppy mode silently reports
12509                // the refusal, which is why the same statement throws here but not there.
12510                if !deleted && self.current_strict() {
12511                    return Err(Signal::Throw(
12512                        self.make_error("TypeError", "cannot delete property"),
12513                    ));
12514                }
12515                self.push(Value::Bool(deleted));
12516            }
12517
12518            // -- exceptions and bookkeeping ---------------------------------
12519            Fclosure | Fclosure8 => {
12520                let value = self.closure(a as usize)?;
12521                self.push(value);
12522            }
12523
12524            other => {
12525                let name = other.info().name;
12526                return Err(Signal::Throw(self.make_error(
12527                    "InternalError",
12528                    &format!("{name} is not implemented yet"),
12529                )));
12530            }
12531        }
12532        Ok(Step::Continue)
12533    }
12534
12535    // -- operand helpers ----------------------------------------------------
12536
12537    /// The slot index an operand names, taking short forms into account.
12538    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12539        use Opcode::*;
12540        match op {
12541            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12542            | SetVarRef0 => 0,
12543            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12544            | SetVarRef1 => 1,
12545            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12546            | SetVarRef2 => 2,
12547            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12548            | SetVarRef3 => 3,
12549            _ => a as usize,
12550        }
12551    }
12552
12553    /// The argument count of a call, taking `call0`…`call3` into account.
12554    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12555        use Opcode::*;
12556        match op {
12557            Call0 => 0,
12558            Call1 => 1,
12559            Call2 => 2,
12560            Call3 => 3,
12561            _ => a as usize,
12562        }
12563    }
12564
12565    /// The atom's name as a property key.
12566    ///
12567    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12568    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12569    /// `String::clone` was a heap allocation and a copy — per property access.
12570    /// The atom at `index`, as a property key.
12571    ///
12572    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12573    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12574    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12575    /// 5.3% of `property:monomorphic`.
12576    /// The atom's text, exactly — including an unpaired surrogate.
12577    ///
12578    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12579    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12580    /// `atom_text` below is for the other kind of use, where the atom is a key in the
12581    /// engine's own tables.
12582    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12583        self.frame()
12584            .code
12585            .code
12586            .atoms
12587            .get(index)
12588            .map(|atom| match atom {
12589                Atom::Str(text) => text.clone(),
12590                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12591                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12592                Atom::Null => crate::value::Wtf8::new(String::new()),
12593            })
12594            .unwrap_or_default()
12595    }
12596
12597    fn atom_text(&self, index: usize) -> String {
12598        self.frame()
12599            .code
12600            .code
12601            .atoms
12602            .get(index)
12603            .map(|atom| match atom {
12604                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12605                // compare it to an identifier, and a surrogate-bearing name is reachable
12606                // through `atom_wtf8` where it matters.
12607                Atom::Str(text) => text.to_string_lossy().into_owned(),
12608                Atom::Index(value) => value.to_string(),
12609                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12610                // `throw_error`, `delete super.x`) never read it.
12611                Atom::Null => String::new(),
12612            })
12613            .unwrap_or_default()
12614    }
12615
12616    fn constant(&mut self, index: usize) -> JsResult<Value> {
12617        let constant = self.frame().code.code.cpool.get(index).cloned();
12618        Ok(match &constant {
12619            Some(Constant::Number(number)) => Value::Float(*number),
12620            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12621            Some(Constant::BigInt { digits, radix }) => {
12622                match crate::bigint::BigInt::from_radix(digits, *radix) {
12623                    Some(big) => self.bigint(big),
12624                    // A literal the parser accepted is always parseable; a failure here
12625                    // would be a compiler bug, so it reads as an `InternalError`.
12626                    None => {
12627                        return Err(Signal::Throw(
12628                            self.make_error("InternalError", "unparseable bigint literal"),
12629                        ));
12630                    }
12631                }
12632            }
12633            Some(Constant::Function(_)) => {
12634                return Err(Signal::Throw(
12635                    self.make_error("InternalError", "a bare function constant"),
12636                ));
12637            }
12638            // A tagged template's call site: a frozen array of the cooked chunks with a
12639            // frozen `raw` array beside it, which is what `String.raw` reads back.
12640            Some(Constant::Template { cooked, raw }) => {
12641                let cooked_values: Vec<Value> = cooked
12642                    .iter()
12643                    .map(|chunk| match chunk {
12644                        Some(text) => self.string_wtf8(text.clone()),
12645                        None => Value::Undefined,
12646                    })
12647                    .collect();
12648                let raw_values: Vec<Value> =
12649                    raw.iter().map(|text| self.string(text.clone())).collect();
12650                let raw_array = self.new_array(raw_values);
12651                raw_array.set_extensible(false);
12652                let template = self.new_array(cooked_values);
12653                template.define(
12654                    "raw",
12655                    Property::with_attributes(Value::Object(raw_array), false, false),
12656                );
12657                template.set_extensible(false);
12658                Value::Object(template)
12659            }
12660            _ => Value::Undefined,
12661        })
12662    }
12663
12664    /// The reference cell a closure-variable slot names.
12665    ///
12666    /// Two kinds of binding share this addressing: a genuine closure variable
12667    /// (captured from an enclosing function) lives in this frame's environment,
12668    /// while a *declared global* lives in the realm so that a script, a function
12669    /// declaration and their uses all see one binding. A plain `Global` — an
12670    /// undeclared name that may be satisfied by the global object — has no cell at
12671    /// all, which is how `typeof x` still works for a name that does not exist.
12672    /// The reference cell a closure-variable slot names.
12673    ///
12674    /// The environment is resolved once, when the closure is built, and this is
12675    /// just the lookup afterwards. A *declared global* is in there too, pointing at
12676    /// the realm's cell, so a script, a hoisted function declaration and their uses
12677    /// all share one binding. A plain `Global` — a name the script never declared —
12678    /// is read and written through `get_var`/`put_var` by name instead, which is
12679    /// what lets the global object satisfy it.
12680    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12681        self.frame().env.cells.get(slot).cloned()
12682    }
12683
12684    /// Whether `slot` refers to a global binding through the reference table.
12685    ///
12686    /// A global's cell in the closure environment only exists so the slot has
12687    /// something to point at; the binding itself lives on the global object (a `var`)
12688    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12689    /// be routed, not performed on the placeholder.
12690    fn is_global_slot(&self, slot: usize) -> bool {
12691        self.frame()
12692            .code
12693            .code
12694            .closure_vars
12695            .get(slot)
12696            .is_some_and(|c| {
12697                // A module's declarations and imports are *not* globals: their cells are
12698                // the module environment's, filled by the host, so the placeholder routing
12699                // must not apply to them.
12700                matches!(
12701                    c.closure_type,
12702                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12703                )
12704            })
12705    }
12706
12707    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12708        if self.is_global_slot(slot) {
12709            return self.get_global(slot);
12710        }
12711        Ok(self
12712            .var_ref_cell(slot)
12713            .map(|cell| cell.get())
12714            .unwrap_or(Value::Undefined))
12715    }
12716
12717    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12718        // A function declaration is hoisted by storing into a global reference before
12719        // the body runs, so this path is also what puts it on the global object.
12720        if self.is_global_slot(slot) {
12721            return self.put_global(slot, value);
12722        }
12723        if let Some(cell) = self.var_ref_cell(slot) {
12724            cell.set(value);
12725        }
12726        Ok(())
12727    }
12728
12729    // -- closures -----------------------------------------------------------
12730
12731    /// Build the closure for the function constant `index`.
12732    ///
12733    /// Every entry in the child's closure table names where its binding lives in
12734    /// *this* frame: a local or argument slot that was marked captured, or a cell
12735    /// this frame is itself holding. That is how a variable three functions deep
12736    /// stays one binding.
12737    fn closure(&mut self, index: usize) -> JsResult<Value> {
12738        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12739        else {
12740            return Err(Signal::Throw(
12741                self.make_error("InternalError", "fclosure of a non-function"),
12742            ));
12743        };
12744        let mut cells = Vec::with_capacity(function.closure_vars.len());
12745        for closure_var in &function.closure_vars {
12746            let cell = match closure_var.closure_type {
12747                ClosureType::Arg => {
12748                    let slot = closure_var.var_idx as usize;
12749                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12750                }
12751                ClosureType::Local => {
12752                    let slot = closure_var.var_idx as usize;
12753                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12754                }
12755                ClosureType::Ref | ClosureType::GlobalRef => {
12756                    // A `Ref` names a cell in this frame's own closure table; a
12757                    // `GlobalRef` also starts there, then resolves by name below.
12758                    let slot = closure_var.var_idx as usize;
12759                    if let Some(cell) = self.frame().env.cells.get(slot) {
12760                        cells.push(cell.clone());
12761                        continue;
12762                    }
12763                    -1
12764                }
12765                _ => -1,
12766            };
12767            if cell >= 0 {
12768                let cell = self.frame().cells[cell as usize].clone();
12769                cells.push(cell);
12770                continue;
12771            }
12772            // A global: the cell is created on demand and shared through the realm,
12773            // so every function sees one binding.
12774            let name = closure_var.name.clone();
12775            let cell = match self.realm.globals.get(&name) {
12776                Some(cell) => cell.clone(),
12777                None => {
12778                    let cell = self.new_cell(Value::Undefined);
12779                    self.realm.globals.insert(name.clone(), cell.clone());
12780                    cell
12781                }
12782            };
12783            cells.push(cell);
12784        }
12785        let name = function.name.clone();
12786        // `.length` is the arity before any default or rest parameter, not the number
12787        // of slots a pattern parameter needs.
12788        let length = function.defined_args;
12789        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12790        // function and an arrow function do not. A *method* also does not, but that is not
12791        // known here — the method is marked when the `[[HomeObject]]` is attached (see
12792        // `set_home_object`), which is the moment it becomes a method.
12793        let function_kind = function.kind;
12794        let constructible =
12795            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12796        let code = Gc::new(self.heap, CompiledCode::new(*function));
12797        // A closure built inside an `eval` inherits the eval's view of the enclosing
12798        // bindings, so it can still read them once the eval has returned.
12799        let eval_scope = self
12800            .active_eval_scope
12801            .clone()
12802            .or_else(|| self.frame().env.eval_scope.clone());
12803        // A closure sees the variables a direct `eval` declared in the frame it was
12804        // created in — the ones declared before *and after* it, so the same object is
12805        // shared; only the phase bounds which of them are visible.
12806        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12807        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12808        let env = Gc::new(
12809            self.heap,
12810            ClosureEnv {
12811                cells,
12812                eval_scope,
12813                local_vars,
12814                local_phase,
12815            },
12816        );
12817        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12818        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12819        // the only thing that carries `Symbol.toStringTag`, so without it
12820        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12821        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12822        let proto = match function_kind {
12823            js_compile::bytecode::FunctionKind::AsyncGenerator => self
12824                .realm
12825                .async_generator_function_proto
12826                .clone()
12827                .or_else(|| self.realm.function_proto.clone().into()),
12828            js_compile::bytecode::FunctionKind::Generator => self
12829                .realm
12830                .generator_function_proto
12831                .clone()
12832                .or_else(|| self.realm.function_proto.clone().into()),
12833            js_compile::bytecode::FunctionKind::Async => self
12834                .realm
12835                .async_function_proto
12836                .clone()
12837                .or_else(|| self.realm.function_proto.clone().into()),
12838            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12839        };
12840        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12841        object.set_constructible(constructible);
12842        object.define(
12843            "length",
12844            Property::name_or_length(Value::Int(length as i32)),
12845        );
12846        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12847        // that checks the own-property descriptor fails if the property is missing.
12848        object.define("name", Property::name_or_length(self.string(name)));
12849        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12850        // when `[[Construct]]` is created, so an async function and an arrow function have
12851        // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12852        // function) an own `prototype` property, which `builtin.js` checks for absence.
12853        //
12854        // A **generator** function is the exception that is not constructible: it still
12855        // gets a `prototype` field, because that object is what a generator *instance*
12856        // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12857        // made `function* g(){}; g.prototype` `undefined` and every generator share
12858        // `%GeneratorPrototype%` as its direct prototype.
12859        if constructible {
12860            self.install_function_prototype(&object);
12861        } else if matches!(
12862            function_kind,
12863            js_compile::bytecode::FunctionKind::Generator
12864                | js_compile::bytecode::FunctionKind::AsyncGenerator
12865        ) {
12866            let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12867                self.realm.generator_proto.clone()
12868            } else {
12869                self.realm
12870                    .async_generator_proto
12871                    .clone()
12872                    .unwrap_or_else(|| self.realm.generator_proto.clone())
12873            };
12874            self.install_generator_prototype(&object, parent);
12875        }
12876        Ok(Value::Object(object))
12877    }
12878
12879    // -- conversions used by the operators ----------------------------------
12880
12881    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12882        // `+x` is `ToNumber`, which for a string parses it and for an object runs
12883        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12884        // string, which then behaves differently in every later comparison.
12885        match value {
12886            Value::Int(_) | Value::Float(_) => Ok(value),
12887            other => Ok(Value::Float(self.to_js_number(&other)?)),
12888        }
12889    }
12890
12891    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12892    ///
12893    /// Returns the *converted* old value and the new one, because the two callers need
12894    /// different halves: `++x` yields the new value, while `x++` yields the old one and
12895    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12896    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12897    /// boolean.
12898    ///
12899    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12900    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12901    /// a bigint algorithm then ran exactly once.
12902    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12903        if let Value::BigInt(big) = &value {
12904            let one = crate::bigint::BigInt::from_i64(1);
12905            let next = if up { big.add(&one) } else { big.sub(&one) };
12906            return Ok((value, self.bigint(next)));
12907        }
12908        let old = self.numeric_operand(value)?;
12909        if let Value::BigInt(big) = &old {
12910            let one = crate::bigint::BigInt::from_i64(1);
12911            let next = if up { big.add(&one) } else { big.sub(&one) };
12912            return Ok((old, self.bigint(next)));
12913        }
12914        let new = if up {
12915            increment(old.clone())
12916        } else {
12917            decrement(old.clone())
12918        };
12919        Ok((old, new))
12920    }
12921
12922    /// `ToNumeric` for a unary or update operand: `ToPrimitive(number)`, then either branch.
12923    ///
12924    /// The unary operators are defined on `Numeric`, not on `Number`: `-x` and `~x` are
12925    /// `Numeric::unaryMinus`/`bitwiseNOT`, which a bigint answers exactly. [`Interp::numeric`]
12926    /// is `ToNumber` and collapses a bigint to a float, so an operand that is a *wrapper
12927    /// object* — `-Object(5n)` — lost its bigint-ness before the operator ever saw it and
12928    /// raised "cannot convert bigint to number". A primitive bigint never took that path
12929    /// (`Neg`/`Not` matched `Value::BigInt` first), which is why only the boxed form broke.
12930    fn numeric_operand(&mut self, value: Value) -> JsResult<Value> {
12931        let primitive = match value {
12932            Value::Int(_) | Value::Float(_) | Value::BigInt(_) => value,
12933            other => self.to_primitive(other, Hint::Number)?,
12934        };
12935        match primitive {
12936            Value::BigInt(_) => Ok(primitive),
12937            other => self.numeric(other),
12938        }
12939    }
12940
12941    fn numeric(&mut self, value: Value) -> JsResult<Value> {
12942        // `ToNumber` on an object runs `ToPrimitive` first, which is how
12943        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12944        // heard at all. Reading the object's own tag instead (`other.to_number()`)
12945        // turned the whole operand into `NaN` and swallowed the exception.
12946        match value {
12947            Value::Int(_) | Value::Float(_) => Ok(value),
12948            other => Ok(Value::Float(self.to_js_number(&other)?)),
12949        }
12950    }
12951
12952    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12953    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12954        match value {
12955            Value::BigInt(big) => Ok((**big).clone()),
12956            // The reference words this the same way for every operator, so a failing
12957            // script reads identically; the operator itself adds nothing a caller can use.
12958            _ => Err(Signal::Throw(
12959                self.make_error("TypeError", "cannot convert bigint to number"),
12960            )),
12961        }
12962    }
12963
12964    /// Arithmetic where at least one operand is a `BigInt`.
12965    ///
12966    /// The two numeric types never mix, so a bigint paired with anything else is an error
12967    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12968    /// that the relational operators handle it separately.
12969    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12970        use Opcode::*;
12971        let a = self.bigint_operand(&left)?;
12972        let b = self.bigint_operand(&right)?;
12973        let result = match op {
12974            Add => a.add(&b),
12975            Sub => a.sub(&b),
12976            Mul => a.mul(&b),
12977            Div | Mod => {
12978                let Some((quotient, remainder)) = a.div_rem(&b) else {
12979                    return Err(Signal::Throw(
12980                        self.make_error("RangeError", "division by zero"),
12981                    ));
12982                };
12983                if op == Div { quotient } else { remainder }
12984            }
12985            Pow => {
12986                let Some(value) = a.pow(&b) else {
12987                    return Err(Signal::Throw(self.make_error(
12988                        "RangeError",
12989                        "BigInt exponent must be non-negative and not absurdly large",
12990                    )));
12991                };
12992                value
12993            }
12994            And => a.bitand(&b),
12995            Or => a.bitor(&b),
12996            Xor => a.bitxor(&b),
12997            Shl | Sar => {
12998                // A shift count is a `BigInt` here, and both directions are exact; a
12999                // negative count would be the other direction, which the spec forbids.
13000                let Some(count) = b.to_i64() else {
13001                    return Err(Signal::Throw(
13002                        self.make_error("RangeError", "BigInt shift count is too large"),
13003                    ));
13004                };
13005                if count < 0 {
13006                    return Err(Signal::Throw(self.make_error(
13007                        "RangeError",
13008                        "BigInt shift count must be non-negative",
13009                    )));
13010                }
13011                if op == Shl {
13012                    a.shl(count as u64)
13013                } else {
13014                    a.shr(count as u64)
13015                }
13016            }
13017            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
13018            _ => {
13019                return Err(Signal::Throw(self.make_error(
13020                    "TypeError",
13021                    "BigInts have no unsigned right shift, use >> instead",
13022                )));
13023            }
13024        };
13025        Ok(self.bigint(result))
13026    }
13027
13028    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
13029    ///
13030    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
13031    /// is on the mathematical values, and nothing is rounded first.
13032    /// `<`, `<=`, `>`, `>=`.
13033    ///
13034    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
13035    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
13036    /// It is a `?`-returning function for exactly that reason: an object operand can run
13037    /// script, and script can throw. The old version compared `to_number` of the raw
13038    /// values, which answered `false` for every object instead of calling `valueOf` —
13039    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
13040    /// never ran.
13041    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13042        // The hot arm first: `i < n` with both sides already integers. No conversion, no
13043        // call, nothing that can throw.
13044        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13045            let ordering = Some(left.cmp(right));
13046            return Ok(ordering_answer(op, ordering));
13047        }
13048        // Anything that can run script has to be converted first, in this order.
13049        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
13050        {
13051            (
13052                self.to_primitive(left, Hint::Number)?,
13053                self.to_primitive(right, Hint::Number)?,
13054            )
13055        } else {
13056            (left, right)
13057        };
13058        let ordering = match (&left, &right) {
13059            // The loop condition `i < n` is integer against integer, and it runs once
13060            // per iteration of every loop in every program. Without this arm it took the
13061            // `to_number` path twice, which is a `match` plus a conversion each.
13062            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
13063            // **Code unit** order, not code point order. They differ exactly where a
13064            // surrogate pair meets a BMP character above U+E000: `"\uDC00" > "\uD800"` is
13065            // true because 0xDC00 > 0xD800, while comparing code points would have turned
13066            // both lone surrogates into U+FFFD and called them equal
13067            // (`greater-than/S11.8.2_A4.12_T1`).
13068            (Value::String(a), Value::String(b)) => Some(compare_code_units(a, b)),
13069            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
13070            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
13071            // is true even though `2.5` has no bigint form.
13072            // §7.2.13 step 3.d-3.e: a bigint against a string goes through
13073            // `StringToBigInt`, **not** `ToNumber` — `"9007199254740993" > 9007199254740992n`
13074            // is true because both sides stay exact integers, which converting the string to
13075            // a double would destroy. A string that is not an integer literal makes the
13076            // whole comparison `undefined`, i.e. `false` for every relational operator.
13077            (Value::BigInt(a), Value::String(text)) => {
13078                string_to_bigint(&text.to_string_lossy()).map(|b| a.cmp(&b))
13079            }
13080            (Value::String(text), Value::BigInt(b)) => {
13081                string_to_bigint(&text.to_string_lossy()).map(|a| b.cmp(&a).reverse())
13082            }
13083            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
13084                let b = self.number_operand(other)?;
13085                if b.is_nan() {
13086                    None
13087                } else {
13088                    compare_bigint_and_f64(a, b)
13089                }
13090            }
13091            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
13092                let a = self.number_operand(other)?;
13093                if a.is_nan() {
13094                    None
13095                } else {
13096                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13097                }
13098            }
13099            // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13100            // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13101            // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13102            _ => self
13103                .to_js_number(&left)?
13104                .partial_cmp(&self.to_js_number(&right)?),
13105        };
13106        Ok(ordering_answer(op, ordering))
13107    }
13108
13109    /// `ToNumber(V)`, refusing a Symbol instead of answering `NaN`.
13110    ///
13111    /// §7.1.4 throws for a Symbol, and the relational operators inherit that: `3n < Symbol()`
13112    /// is a `TypeError`, not `false`. `Value::to_number` is a total function — it has to be,
13113    /// because it is also what `Number(x)` uses — so the check lives here.
13114    fn number_operand(&self, value: &Value) -> JsResult<f64> {
13115        if matches!(value, Value::Symbol(_)) {
13116            return Err(self.type_error("cannot convert symbol to number"));
13117        }
13118        Ok(value.to_number())
13119    }
13120
13121    fn binary_add(&mut self) -> JsResult<()> {
13122        let right = self.pop();
13123        let left = self.pop();
13124        // Two integers add without any of the machinery below: no `ToPrimitive` (an
13125        // `Int` is already primitive), no string check, no bigint check, no allocation.
13126        // `x += 1` in a loop is the single most common instruction sequence in real
13127        // script, and it used to walk every one of those checks before reaching the
13128        // same `checked_add`.
13129        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13130            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13131            return Ok(());
13132        }
13133        let left = self.primitive_of(left)?;
13134        let right = self.primitive_of(right)?;
13135        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13136        // that check comes before the bigint one: `"" + 1n` is a string, not a
13137        // mixed-type error.
13138        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13139            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13140            // `TypeError`, the one place a symbol and a string do not mix.
13141            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13142            // between a copy and a rope from their lengths, and a rope is what turns
13143            // `text += "abc"` in a loop from quadratic into linear.
13144            if let (Value::String(left), Value::String(right)) = (&left, &right) {
13145                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13146                // reports as `InternalError: string too long`.
13147                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13148                    return Err(Signal::Throw(
13149                        self.make_error("InternalError", "string too long"),
13150                    ));
13151                };
13152                self.push(Value::String(Gc::new(self.heap, joined)));
13153                return Ok(());
13154            }
13155            // At least one operand was not a string, so `ToString` it. This rejects a
13156            // symbol, which is the one place a symbol and a string do not mix.
13157            let left = self.checked_to_wtf8(&left)?;
13158            let right = self.checked_to_wtf8(&right)?;
13159            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13160            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13161            let text = left.concat(&right);
13162            self.push(self.string_wtf8(text));
13163            return Ok(());
13164        }
13165        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13166        // not a conversion.
13167        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13168            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13169            self.push(value);
13170            return Ok(());
13171        }
13172        let left = self.numeric(left)?;
13173        let right = self.numeric(right)?;
13174        self.push(add_numbers(left, right));
13175        Ok(())
13176    }
13177
13178    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13179        self.to_primitive(value, Hint::Default)
13180    }
13181
13182    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13183    ///
13184    /// The order depends on the hint: the "number" order tries `valueOf` first and
13185    /// `toString` second, the "string" order the other way round, and the default
13186    /// hint uses the number order. A result that is still an object is a `TypeError`,
13187    /// because no built-in `valueOf`/`toString` returns one.
13188    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13189        let Value::Object(object) = &value else {
13190            return Ok(value);
13191        };
13192        // A Date overrides the default hint to mean "string", which is what
13193        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13194        // this, `"" + new Date()` would print the milliseconds, not the date.
13195        let hint = if hint == Hint::Default && is_date_object(self, object) {
13196            Hint::String
13197        } else {
13198            hint
13199        };
13200        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13201        // handed the hint as a string. This is the hook a Date uses for its default hint
13202        // and a script uses to take over conversion entirely.
13203        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13204        // `GetMethod`, not "is it a callable object": the property has to be read and then
13205        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13206        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13207        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13208        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13209        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13210        // callable.
13211        match self.get_property_key(object, &key)? {
13212            None | Some(Value::Undefined) | Some(Value::Null) => {}
13213            Some(Value::Object(function)) if function.is_callable() => {
13214                let hint = match hint {
13215                    Hint::String => "string",
13216                    Hint::Number => "number",
13217                    Hint::Default => "default",
13218                };
13219                let hint = self.string(hint);
13220                let result = self.call_value(
13221                    Value::Object(function),
13222                    Value::Object(object.clone()),
13223                    vec![hint],
13224                )?;
13225                if !matches!(result, Value::Object(_)) {
13226                    return Ok(result);
13227                }
13228                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13229            }
13230            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13231        }
13232        let order: [&str; 2] = match hint {
13233            Hint::String => ["toString", "valueOf"],
13234            Hint::Number | Hint::Default => ["valueOf", "toString"],
13235        };
13236        let receiver = object.clone();
13237        for method in order {
13238            if let Some(function) = self.get_property(&receiver, method)?
13239                && matches!(&function, Value::Object(object) if object.is_callable())
13240            {
13241                let result =
13242                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13243                if !matches!(result, Value::Object(_)) {
13244                    return Ok(result);
13245                }
13246            }
13247        }
13248        Err(self.type_error("cannot convert object to primitive value"))
13249    }
13250
13251    /// `ToString` with the object case going through `ToPrimitive`.
13252    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13253        if matches!(value, Value::Object(_)) {
13254            let primitive = self.to_primitive(value.clone(), Hint::String)?;
13255            return Ok(primitive.to_js_string());
13256        }
13257        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13258        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13259        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13260        // check here broke `String(Symbol())` and 45 cases that print a symbol.
13261        Ok(value.to_js_string())
13262    }
13263
13264    /// `ToString(value)`, with §7.1.19's symbol refusal.
13265    ///
13266    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13267    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13268    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13269    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13270        if matches!(value, Value::Symbol(_)) {
13271            return Err(self.type_error("cannot convert a Symbol to a string"));
13272        }
13273        if matches!(value, Value::Object(_)) {
13274            let primitive = self.to_primitive(value.clone(), Hint::String)?;
13275            if matches!(primitive, Value::Symbol(_)) {
13276                return Err(self.type_error("cannot convert a Symbol to a string"));
13277            }
13278            return Ok(primitive.to_js_string());
13279        }
13280        Ok(value.to_js_string())
13281    }
13282
13283    /// `ToString` that keeps the string's code units instead of flattening them.
13284    ///
13285    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13286    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13287    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13288        if matches!(value, Value::Symbol(_)) {
13289            return Err(Signal::Throw(
13290                self.make_error("TypeError", "cannot convert symbol to string"),
13291            ));
13292        }
13293        // An object runs `ToPrimitive` first, which may itself produce a symbol.
13294        let value = self.to_primitive(value.clone(), Hint::String)?;
13295        match value {
13296            Value::Symbol(_) => Err(Signal::Throw(
13297                self.make_error("TypeError", "cannot convert symbol to string"),
13298            )),
13299            Value::String(text) => Ok(text.wtf8().clone()),
13300            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13301        }
13302    }
13303
13304    /// `ToNumber` with the object case going through `ToPrimitive`.
13305    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13306        let value = if matches!(value, Value::Object(_)) {
13307            self.to_primitive(value.clone(), Hint::Number)?
13308        } else {
13309            value.clone()
13310        };
13311        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13312        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13313        // `NaN` to stay total, and the operators check for the bigint themselves — but
13314        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13315        // refuse, and answering `NaN` made them silently wrong instead.
13316        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13317        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13318        match value {
13319            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13320            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13321            other => Ok(other.to_number()),
13322        }
13323    }
13324
13325    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13326    /// [`ElementType::write`].
13327    ///
13328    /// This is separated from the write because both conversions are observable script —
13329    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13330    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13331    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13332    /// setters, and a plain `a[i] = v`.
13333    pub(crate) fn element_value(
13334        &mut self,
13335        element: crate::builtins::typedarray::ElementType,
13336        value: Value,
13337    ) -> JsResult<Value> {
13338        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13339        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13340        let primitive = match &value {
13341            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13342            _ => value,
13343        };
13344        if element.is_bigint() {
13345            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13346            Ok(Value::BigInt(Gc::new(self.heap, big)))
13347        } else {
13348            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13349            Ok(Value::Float(self.to_js_number(&primitive)?))
13350        }
13351    }
13352
13353    /// `ToPropertyKey`: what a computed member access uses as its key.
13354    ///
13355    /// A symbol is returned as itself, never stringified — that is what keeps
13356    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13357    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13358        match value {
13359            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13360            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13361            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13362            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13363            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13364                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13365                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13366                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13367                    other.to_js_string(),
13368                ))),
13369            },
13370            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13371        }
13372    }
13373
13374    /// `ToPropertyKey` for the callers that can only use a string key.
13375    ///
13376    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13377    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13378    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13379    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13380    /// program continues with a value nobody asked for.
13381    /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13382    ///
13383    /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13384    /// — or the empty string when the symbol has no description. Going through
13385    /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13386    /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13387    /// relatives, in both `expressions/object` and `statements/class`).
13388    ///
13389    /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13390    /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13391    fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13392        if let Value::Symbol(symbol) = value {
13393            return Ok(match symbol.description() {
13394                Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13395                None => crate::value::Wtf8::default(),
13396            });
13397        }
13398        self.propkey_of(value)
13399    }
13400
13401    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13402        use crate::value::Wtf8;
13403        Ok(match value {
13404            // A string key keeps its code units. Going through a lossy `String` would make
13405            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13406            Value::String(text) => text.wtf8().clone(),
13407            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13408            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13409            // falling back to its `ToString` would print `[object Object]`.
13410            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13411                Value::String(text) => text.wtf8().clone(),
13412                other => Wtf8::new(other.to_js_string()),
13413            },
13414            other => Wtf8::new(other.to_js_string()),
13415        })
13416    }
13417
13418    // -- object operations used by instructions -----------------------------
13419
13420    /// Read `object[key]`, returning `undefined` when the property is missing.
13421    ///
13422    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13423    /// primitive (looking through its prototype) as well as an object — which is what
13424    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13425    /// argument needs too.
13426    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13427        self.read_field_key(object, &PropertyKey::from(key))
13428    }
13429
13430    /// [`Interp::read_field`] with a key that may be a symbol.
13431    ///
13432    /// A symbol key never reaches the string shortcuts: a string's `length` and its
13433    /// indices are string properties, and a symbol named `length` is a different
13434    /// property that a string primitive cannot have.
13435    /// [`Interp::read_field_key`], with an inline cache in front of it.
13436    ///
13437    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13438    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13439    /// without this the engine walked the chain and compared ~40 property names on each
13440    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13441    ///
13442    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13443    /// missing property. Those answers depend on running code or on state the guard below
13444    /// does not cover, and a wrong answer here is far more expensive than a lookup.
13445    ///
13446    /// A hit is re-validated against the *whole* walked chain, not just the level that
13447    /// answered: the receiver and every prototype down to that level must still be the same
13448    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13449    /// property-table *lengths* — which is what catches a property appearing on an
13450    /// intermediate prototype and shadowing the cached one.
13451    pub fn read_field_cached(
13452        &mut self,
13453        object: &Value,
13454        key: &PropertyKey,
13455        slot: usize,
13456    ) -> JsResult<Value> {
13457        let index = Self::field_cache_slot(object, key, slot);
13458        let Value::Object(target) = object else {
13459            return self.read_field_key(object, key);
13460        };
13461        if target.proxy_state().is_some() {
13462            return self.read_field_key(object, key);
13463        }
13464        if let Some(cached) = &self.field_cache[index]
13465            && cached.key == *key
13466            && let Some(value) = Self::cached_hit(target, cached)
13467        {
13468            return Ok(value);
13469        }
13470        let value = self.read_field_key(object, key)?;
13471        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13472        Ok(value)
13473    }
13474
13475    /// Whether a cache entry still describes this lookup, and if so the value.
13476    ///
13477    /// The guard is the whole point of the entry: identity plus property-table length for
13478    /// every level walked. Re-checked per level rather than once at the receiving end,
13479    /// because a shadowing property can appear anywhere along the chain.
13480    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13481        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13482        // starts with: a clone is a reference-count bump and a drop, and for
13483        // `property:monomorphic` every single hit takes only this arm.
13484        let (weak, len) = cached.chain[0].as_ref()?;
13485        if !target.upgrades_to(weak) {
13486            return None;
13487        }
13488        if cached.level == 0 {
13489            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13490            return target.cached_property_at(cached.index, &cached.key, *len);
13491        }
13492        if target.props_len() != *len {
13493            return None;
13494        }
13495        let mut level = 1;
13496        let mut current = target.proto()?;
13497        loop {
13498            let (weak, len) = cached.chain[level].as_ref()?;
13499            if !current.upgrades_to(weak) || current.props_len() != *len {
13500                return None;
13501            }
13502            if level == cached.level as usize {
13503                // The level that answered: the value is only reusable while the key is
13504                // still there and still a plain data property.
13505                return current.cached_data_property(cached.index, &cached.key);
13506            }
13507            current = current.proto()?;
13508            level += 1;
13509        }
13510    }
13511
13512    /// Build a cache entry for a lookup that just went through the slow path.
13513    ///
13514    /// Records the chain only when the answer came from a plain data property at a level
13515    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13516    /// costs the next lookup the walk it would have cost anyway.
13517    fn record_field_lookup(
13518        target: &Gc<JsObject>,
13519        key: &PropertyKey,
13520        _value: Value,
13521    ) -> Option<FieldCache> {
13522        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13523            [None, None, None];
13524        let mut current = target.clone();
13525        for level in 0..MAX_CACHED_CHAIN {
13526            chain[level] = Some((current.downgrade(), current.props_len()));
13527            if let Some((found, _)) = current.own_property_index(key) {
13528                // `own_property_index` declines an accessor and a hole, which is exactly
13529                // the set that must not be cached.
13530                return Some(FieldCache {
13531                    key: key.clone(),
13532                    index: found,
13533                    level: level as u8,
13534                    chain,
13535                });
13536            }
13537            current = current.proto()?;
13538        }
13539        None
13540    }
13541
13542    /// Which cache slot a lookup uses.
13543    ///
13544    /// Mixes the object's address, the name and the site, so that two properties of one
13545    /// object, and one property of two objects, land in different slots — which is what lets
13546    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13547    /// other iteration.
13548    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13549        let mut hash = match object {
13550            Value::Object(object) => object.address(),
13551            _ => 0,
13552        };
13553        hash = hash
13554            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13555            .rotate_left(17)
13556            .wrapping_add(key.hash_code());
13557        hash = hash.wrapping_add(site.wrapping_mul(31));
13558        // The table is a power of two, so the low bits are the slot.
13559        hash & (FIELD_CACHE_SLOTS - 1)
13560    }
13561
13562    /// Read `key` from `object`, without the inline cache.
13563    ///
13564    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13565    /// prototype chain, while the cached form answers an own data property from memory.
13566    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13567        let text = key.as_str().unwrap_or("");
13568        let Value::Object(object) = object else {
13569            // Reading a property of `undefined`/`null` is the classic TypeError.
13570            if object.is_nullish() {
13571                return Err(Signal::Throw(self.make_error(
13572                    "TypeError",
13573                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
13574                )));
13575            }
13576            // A string has `length` and index access without being boxed.
13577            if let Value::String(value) = object {
13578                if text == "length" {
13579                    return Ok(Value::Int(value.utf16_len() as i32));
13580                }
13581                if let Some(index) = array_index(text) {
13582                    return Ok(match value.wtf8().unit_at(index as usize) {
13583                        Some(unit) => self.string_wtf8(unit),
13584                        None => Value::Undefined,
13585                    });
13586                }
13587            }
13588            // A property of a primitive is looked up on its prototype: this is what
13589            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13590            let prototype = match object {
13591                Value::String(_) => self.realm.string_proto.clone(),
13592                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13593                Value::Bool(_) => self.realm.boolean_proto.clone(),
13594                // A symbol's methods live on `Symbol.prototype`, reached the same way —
13595                // `sym.description` reads through the prototype, not off the symbol.
13596                Value::Symbol(_) => self.realm.symbol_proto.clone(),
13597                // …and a bigint's on `BigInt.prototype`, which is how
13598                // `(255n).toString(16)` reaches its method.
13599                Value::BigInt(_) => self.realm.bigint_proto.clone(),
13600                _ => None,
13601            };
13602            if let Some(prototype) = prototype
13603                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13604            {
13605                return Ok(value);
13606            }
13607            return Ok(Value::Undefined);
13608        };
13609        Ok(self
13610            .get_property_key(object, key)?
13611            .unwrap_or(Value::Undefined))
13612    }
13613
13614    /// The `#name` a private symbol stands for, for error messages.
13615    ///
13616    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13617    /// was made from.
13618    fn private_name(symbol: &Value) -> Option<String> {
13619        match symbol {
13620            Value::Symbol(symbol) if symbol.is_private() => Some(
13621                symbol
13622                    .description()
13623                    .map(|text| text.to_string())
13624                    .unwrap_or_default(),
13625            ),
13626            _ => None,
13627        }
13628    }
13629
13630    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13631    ///
13632    /// Every private-field opcode takes the symbol the class stored in its own scope; a
13633    /// non-symbol here would be a compiler bug, and the reference guards it with
13634    /// `JS_ThrowTypeErrorNotASymbol`.
13635    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13636        match symbol {
13637            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13638            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13639        }
13640    }
13641
13642    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13643    ///
13644    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13645    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13646    /// would hit if the parser did not reject it first.
13647    fn define_private_field(
13648        &mut self,
13649        object: &Value,
13650        symbol: &Value,
13651        value: Value,
13652    ) -> JsResult<()> {
13653        let key = self.private_key(symbol)?;
13654        let Some(target) = object.as_object() else {
13655            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13656        };
13657        if !target.is_extensible() {
13658            return Err(Signal::Throw(
13659                self.make_error("TypeError", "object is not extensible"),
13660            ));
13661        }
13662        if target.own_property_key(&key).is_some() {
13663            let name = Self::private_name(symbol).unwrap_or_default();
13664            return Err(Signal::Throw(self.make_error(
13665                "TypeError",
13666                &format!("private class field '{name}' already exists"),
13667            )));
13668        }
13669        target.define_data_key(&key, value);
13670        Ok(())
13671    }
13672
13673    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13674    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13675        let key = self.private_key(symbol)?;
13676        let Some(target) = object.as_object() else {
13677            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13678        };
13679        match target.own_property_key(&key) {
13680            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13681            None => {
13682                let name = Self::private_name(symbol).unwrap_or_default();
13683                Err(Signal::Throw(self.make_error(
13684                    "TypeError",
13685                    &format!("private class field '{name}' does not exist"),
13686                )))
13687            }
13688        }
13689    }
13690
13691    /// `JS_SetPrivateField`: the store half of the same rule.
13692    fn write_private_field(
13693        &mut self,
13694        object: &Value,
13695        symbol: &Value,
13696        value: Value,
13697    ) -> JsResult<()> {
13698        let key = self.private_key(symbol)?;
13699        let Some(target) = object.as_object() else {
13700            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13701        };
13702        if target.write_value_key(&key, value) {
13703            return Ok(());
13704        }
13705        let name = Self::private_name(symbol).unwrap_or_default();
13706        Err(Signal::Throw(self.make_error(
13707            "TypeError",
13708            &format!("private class field '{name}' does not exist"),
13709        )))
13710    }
13711
13712    /// The `in` half: does `object` have this private field?
13713    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13714    ///
13715    /// The symbol is created once per class — the first `add_brand` on a given home object
13716    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13717    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13718    /// emit for the *instance* brand passes null because all it wants is the symbol.
13719    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13720        let Some(home_object) = home.as_object() else {
13721            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13722        };
13723        let symbol = match home_object.private_brand() {
13724            Some(symbol) => symbol,
13725            None => {
13726                let symbol = Gc::new(
13727                    self.heap,
13728                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13729                );
13730                home_object.set_private_brand(symbol.clone());
13731                symbol
13732            }
13733        };
13734        let Some(target) = object.as_object() else {
13735            // Not an object: nothing to brand. The reference does the same, and `undefined`
13736            // here would otherwise turn a field initialiser into a TypeError.
13737            return Ok(());
13738        };
13739        if !target.is_extensible() {
13740            return Err(Signal::Throw(
13741                self.make_error("TypeError", "object is not extensible"),
13742            ));
13743        }
13744        if target.carries_brand(&symbol) {
13745            return Err(Signal::Throw(
13746                self.make_error("TypeError", "private method is already present"),
13747            ));
13748        }
13749        target.add_brand(symbol);
13750        Ok(())
13751    }
13752
13753    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13754    ///
13755    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13756    /// decides whether to throw.
13757    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13758        let Some(function) = function.as_object() else {
13759            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13760        };
13761        let Some(home) = function.home_object() else {
13762            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13763        };
13764        let Some(brand) = home.private_brand() else {
13765            return Err(Signal::Throw(
13766                self.make_error("TypeError", "expecting <brand> private field"),
13767            ));
13768        };
13769        Ok(object.carries_brand(&brand))
13770    }
13771
13772    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13773        let Value::Object(object) = object else {
13774            // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13775            // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13776            // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13777            // `undefined` still throw, with their own message.
13778            if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13779                return Ok(());
13780            }
13781            return Err(Signal::Throw(self.make_error(
13782                "TypeError",
13783                &format!("cannot set property '{key}' of {}", object.to_js_string()),
13784            )));
13785        };
13786        // The write half of the property inline cache, in effect: an own, writable,
13787        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13788        // decide — no prototype walk (an own property shadows the chain before a setter
13789        // there could matter), no extensibility check (the object already has the key),
13790        // and no `[[DefineOwnProperty]]`.
13791        //
13792        // `this.value = …` inside a method is the whole write side of
13793        // `property:method-call`, and it was reaching `set_property_with_key` with its
13794        // proxy test, its typed-array test, its array-index test and finally a linear
13795        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13796        //
13797        // Every disqualifier is checked here: a proxy traps the set, an array index and
13798        // `length` live outside the property table, and a typed array's element is stored
13799        // through its view's element type.
13800        if object.proxy_state().is_none()
13801            && !object.is_array()
13802            && object.typed_array_element_type().is_none()
13803            && object.write_value_key(key, value.clone())
13804        {
13805            return Ok(());
13806        }
13807        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13808        let on_failure = if self.frame().code.code.strict {
13809            DeleteFailure::Throw
13810        } else {
13811            DeleteFailure::Ignore
13812        };
13813        self.set_property_with_key(object, key, value, on_failure)
13814    }
13815
13816    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13817    ///
13818    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13819    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13820    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13821    /// `Number.parseInt(sym)` — so those callers use this instead.
13822    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13823        if matches!(value, Value::Symbol(_)) {
13824            return Err(Signal::Throw(
13825                self.make_error("TypeError", "cannot convert symbol to string"),
13826            ));
13827        }
13828        // An object runs `ToPrimitive` first, which may itself produce a symbol —
13829        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13830        let value = self.to_primitive(value.clone(), Hint::String)?;
13831        if matches!(value, Value::Symbol(_)) {
13832            return Err(Signal::Throw(
13833                self.make_error("TypeError", "cannot convert symbol to string"),
13834            ));
13835        }
13836        Ok(value.to_js_string())
13837    }
13838
13839    /// `ToPropertyKey` for a builtin that takes a key argument.
13840    ///
13841    /// Fallible: a key whose `toString` throws has to propagate that error, both for
13842    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13843    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13844    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13845    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13846        self.propkey(value)
13847    }
13848
13849    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13850    ///
13851    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13852    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13853    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13854    /// `RangeError` — and why this cannot be a plain `ToNumber`.
13855    /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13856    ///
13857    /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13858    /// then a `RangeError` when they disagree. Two conversions rather than one is
13859    /// observable: a `valueOf` that runs the first time can make `length` non-writable
13860    /// before the second, which turns the store into a refused write
13861    /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13862    pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13863        let first = self.array_length_of(value)?;
13864        let second = self.array_length_of(value)?;
13865        debug_assert_eq!(first, second);
13866        Ok(first)
13867    }
13868
13869    /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13870    ///
13871    /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13872    /// conversion can say so; a caller that needs the spec's two uses that instead.
13873    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13874        let number = match value {
13875            Value::Int(number) => *number as f64,
13876            Value::Float(number) => *number,
13877            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13878            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13879            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13880            // reference answers 0.
13881            Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13882            // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13883            // `"  5  "` is 5, which is exactly what `string_to_number` implements.
13884            Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13885            _ => {
13886                // The primitive comes back through this same conversion, so a wrapper of a
13887                // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13888                // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13889                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13890                return self.array_length_of(&primitive);
13891            }
13892        };
13893        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13894        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13895        // is a `RangeError`, not `0`.
13896        if !number.is_finite()
13897            || number.fract() != 0.0
13898            || !(0.0..=u32::MAX as f64).contains(&number)
13899        {
13900            return Err(self.range_error("invalid array length"));
13901        }
13902        Ok(number as u32)
13903    }
13904
13905    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13906    /// `Object.getOwnPropertySymbols` put in their result array.
13907    pub fn key_value(&self, key: &PropertyKey) -> Value {
13908        match key {
13909            PropertyKey::String(text) => self.string_wtf8(text.clone()),
13910            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13911        }
13912    }
13913
13914    /// Fill in a String exotic object: `_value`, `length` and the index properties.
13915    ///
13916    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13917    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13918    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13919    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13920    /// the two paths had drifted; this is the one both now use.
13921    ///
13922    /// The indices are *code units*, so an astral character occupies two of them — the
13923    /// same rule `s.length` and `s[i]` follow.
13924    /// Give an already-created object the internal slot that makes it a wrapper of
13925    /// `value`, so the primitive's prototype methods work on it.
13926    ///
13927    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13928    /// which are wrappers of their own type holding the empty value.
13929    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13930        self.internal_set(object, "_value", value);
13931    }
13932
13933    pub(crate) fn init_string_wrapper(
13934        &mut self,
13935        object: &Gc<JsObject>,
13936        text: &Gc<crate::value::JsString>,
13937    ) {
13938        object.define(
13939            "length",
13940            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13941        );
13942        for index in 0..text.utf16_len() {
13943            if let Some(unit) = text.wtf8().unit_at(index) {
13944                object.define(
13945                    &index.to_string(),
13946                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13947                    Property::with_attributes(self.string_wtf8(unit), false, true),
13948                );
13949            }
13950        }
13951        object.define_key(
13952            &self.internal_slot("_value"),
13953            Property::with_attributes(Value::String(text.clone()), false, false),
13954        );
13955    }
13956
13957    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13958    ///
13959    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13960    /// throws. The wrapper carries its primitive in `_value` — the same slot
13961    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13962    /// on a boxed value no constructor ever built.
13963    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13964        let (prototype, primitive) = match value {
13965            Value::Object(object) => return Ok(object.clone()),
13966            Value::String(text) => {
13967                let object = self.new_object(self.realm.string_proto.clone());
13968                self.init_string_wrapper(&object, text);
13969                return Ok(object);
13970            }
13971            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13972            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13973            // A symbol and a bigint box into wrappers whose methods live on
13974            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13975            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13976            // branch below instead produced an object with *no* prototype, so those
13977            // methods were unreachable on a box.
13978            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13979            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13980            Value::Undefined | Value::Null => {
13981                return Err(Signal::Throw(self.make_error(
13982                    "TypeError",
13983                    &format!("cannot convert {} to object", value.to_js_string()),
13984                )));
13985            }
13986            _ => (None, value.clone()),
13987        };
13988        let object = self.new_object(prototype);
13989        self.internal_set(&object, "_value", primitive);
13990        Ok(object)
13991    }
13992
13993    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13994    ///
13995    /// Split out for a reader that has to create the object *before* it knows what it wraps:
13996    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13997    /// written before its primitive, so the placeholder has to exist first and be filled in
13998    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13999    /// than a second in the deserialiser.
14000    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
14001        let prototype = match value {
14002            Value::String(_) => self.realm.string_proto.clone(),
14003            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14004            Value::Bool(_) => self.realm.boolean_proto.clone(),
14005            Value::Symbol(_) => self.realm.symbol_proto.clone(),
14006            Value::BigInt(_) => self.realm.bigint_proto.clone(),
14007            _ => {
14008                return Err(Signal::Throw(self.make_error(
14009                    "TypeError",
14010                    &format!("cannot box {}", value.to_js_string()),
14011                )));
14012            }
14013        };
14014        object.set_proto(prototype);
14015        if let Value::String(text) = value {
14016            self.init_string_wrapper(object, text);
14017            return Ok(());
14018        }
14019        self.internal_set(object, "_value", value.clone());
14020        Ok(())
14021    }
14022
14023    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
14024    ///
14025    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
14026    /// through the `Symbol` function object, so the registry is reachable as a method rather
14027    /// than only from `builtins::symbol`.
14028    pub fn symbol_for(&mut self, key: &str) -> Value {
14029        if let Some(existing) = self.realm.symbol_registry.get(key) {
14030            return existing.clone();
14031        }
14032        let symbol = crate::builtins::symbol::symbol_value(
14033            self,
14034            crate::value::JsSymbol::registered(key.to_string()),
14035        );
14036        self.realm
14037            .symbol_registry
14038            .insert(key.to_string(), symbol.clone());
14039        symbol
14040    }
14041
14042    /// `a == b`, the coercing comparison.
14043    ///
14044    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
14045    /// which is what makes `[] == ""` true: `[]` becomes `""` via
14046    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
14047    /// because the conversion is allowed to call script code, so the two primitive
14048    /// operands are handed back to it.
14049    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
14050        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
14051            return Ok(left.loose_equals(&right));
14052        }
14053        // `null == undefined` holds even though neither is an object.
14054        if matches!(left, Value::Undefined | Value::Null)
14055            && matches!(right, Value::Undefined | Value::Null)
14056        {
14057            return Ok(true);
14058        }
14059        if matches!(left, Value::Undefined | Value::Null)
14060            || matches!(right, Value::Undefined | Value::Null)
14061        {
14062            return Ok(false);
14063        }
14064        // Two objects compare by identity. Only an object *against a primitive* is
14065        // converted, which is why `{} == {}` is false while `[] == ""` is true.
14066        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
14067            return Ok(a.ptr_eq(b));
14068        }
14069        let left = self.to_primitive(left, Hint::Default)?;
14070        let right = self.to_primitive(right, Hint::Default)?;
14071        Ok(left.loose_equals(&right))
14072    }
14073
14074    /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
14075    ///
14076    /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
14077    /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
14078    /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
14079    /// the calls.
14080    fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
14081        let key = PropertyKey::from(name);
14082        if !self.has_property_value(object, &key)? {
14083            return Ok(false);
14084        }
14085        let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
14086        let unscopables = self.read_field_key(object, &unscopables_key)?;
14087        let Value::Object(_) = unscopables else {
14088            // `undefined` (the usual case) or a primitive: nothing is excluded.
14089            return Ok(true);
14090        };
14091        let excluded = self.read_field_key(&unscopables, &key)?;
14092        Ok(!excluded.to_boolean())
14093    }
14094
14095    /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
14096    ///
14097    /// `HasProperty` is asked a **second** time — the guard already asked it — because the
14098    /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
14099    /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
14100    /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
14101    ///
14102    /// When the property has gone, strict code throws and sloppy code reads `undefined`
14103    /// from the environment (step 2's `S` is the strictness of the *running* code, not of
14104    /// the declaration).
14105    fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
14106        let key = PropertyKey::from(name);
14107        if !self.has_property_value(object, &key)? {
14108            if self.frame().code.code.strict {
14109                return Err(self.throw_reference(name));
14110            }
14111            return Ok(Value::Undefined);
14112        }
14113        self.read_field_key(object, &key)
14114    }
14115
14116    /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14117    ///
14118    /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14119    /// property is gone — before the store, which is what makes
14120    /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14121    /// a `ReferenceError` rather than whatever the failed store would have thrown.
14122    fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14123        let key = PropertyKey::from(name);
14124        if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14125            return Err(self.throw_reference(name));
14126        }
14127        self.write_field_key(object, &key, value)
14128    }
14129
14130    /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14131    fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14132        match object {
14133            Value::Object(target) => self.has_property_key(target, key),
14134            // `with` boxes its object when the statement is entered (`to_object`), so a
14135            // primitive cannot arrive here; `false` is the honest answer rather than a
14136            // panic if it ever does.
14137            _ => Ok(false),
14138        }
14139    }
14140
14141    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14142        let Value::Object(object) = object else {
14143            return Err(Signal::Throw(
14144                self.make_error("TypeError", "cannot use 'in' on a non-object"),
14145            ));
14146        };
14147        let key = self.propkey(key)?;
14148        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14149        // trap. One implementation, so an array's derived `length` and its inherited holes
14150        // cannot be right in one caller and wrong in another.
14151        self.has_own_or_inherited(object, &key)
14152    }
14153
14154    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14155    ///
14156    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14157    /// whole reason the operator is a hook rather than a prototype walk.
14158    ///
14159    /// §13.10.2 `InstanceofOperator(O, C)`, which is stricter than
14160    /// [`Interp::ordinary_instance_of`]: step 1 throws when `C` is not an object at all
14161    /// (`true instanceof true`) and step 4 throws when it is an object but not callable
14162    /// (`1 instanceof Math`). Both used to answer `false`, which is `OrdinaryHasInstance`'s
14163    /// rule (its step 2) and not this operator's — so nine `expressions/instanceof` cases
14164    /// expected a `TypeError` and got a value.
14165    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14166        // Step 1, before any method lookup.
14167        if constructor.as_object().is_none() {
14168            return Err(Signal::Throw(self.make_error(
14169                "TypeError",
14170                "right-hand side of 'instanceof' is not an object",
14171            )));
14172        }
14173        let Value::Object(function) = constructor else {
14174            unreachable!("just checked");
14175        };
14176        // Step 2. A primitive `C` cannot reach here, so `get_property_key` on the object is
14177        // the whole of it.
14178        let key = self.realm.well_known_key(WellKnown::HasInstance);
14179        let method = self.get_property_key(function, &key)?;
14180        if let Some(method) = method
14181            && !matches!(method, Value::Undefined)
14182        {
14183            let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14184            return Ok(answer.to_boolean());
14185        }
14186        // Step 4.
14187        if !function.is_callable() {
14188            return Err(Signal::Throw(self.make_error(
14189                "TypeError",
14190                "right-hand side of 'instanceof' is not callable",
14191            )));
14192        }
14193        // Step 5.
14194        self.instance_of(object, constructor)
14195    }
14196
14197    /// `OrdinaryHasInstance`: the prototype walk on its own.
14198    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14199        self.instance_of(object, constructor)
14200    }
14201
14202    /// `IsArray`: an array, or a proxy whose target is one.
14203    ///
14204    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14205    /// makes `Array.isArray(new Proxy([], {}))` true.
14206    pub fn is_array_value(&self, value: &Value) -> bool {
14207        match value {
14208            Value::Object(object) => {
14209                if let Some(state) = object.proxy_state() {
14210                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14211                }
14212                object.is_array()
14213            }
14214            _ => false,
14215        }
14216    }
14217
14218    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14219    ///
14220    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14221    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14222    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14223    /// see [`Interp::enqueue_job_function`].
14224    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14225        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14226        // the handler is reported rather than lost — the same reason a `then` reaction needs a
14227        // promise to settle.
14228        let promise = self.new_promise();
14229        self.fulfill_promise(&promise, Value::Undefined);
14230        self.jobs.push_back(Job::Reaction {
14231            handler: Some(function),
14232            argument: Value::Undefined,
14233            rejected: false,
14234            promise,
14235        });
14236        Ok(())
14237    }
14238
14239    /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14240    ///
14241    /// Four of its steps were missing or wrong, and each one is a test262 case in
14242    /// `Function/prototype/Symbol.hasInstance/`:
14243    ///
14244    /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14245    /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14246    ///   `[[BoundThis]]` standing in for the object when that is an object), which is why
14247    ///   `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14248    ///   `prototype` of its own, so without this step the walk below gives `false`;
14249    /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14250    /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14251    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14252        let Value::Object(function) = constructor else {
14253            return Ok(false);
14254        };
14255        if !function.is_callable() {
14256            return Ok(false);
14257        }
14258        // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14259        // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14260        // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14261        if let Some((target, this)) = function.bound_target_and_this() {
14262            let object = if this.as_object().is_some() {
14263                this
14264            } else {
14265                object.clone()
14266            };
14267            return self.instance_of(&object, &target);
14268        }
14269        let Value::Object(target) = object else {
14270            return Ok(false);
14271        };
14272        let prototype = self.get_property(function, "prototype")?;
14273        let Some(Value::Object(prototype)) = prototype else {
14274            return Err(Signal::Throw(self.make_error(
14275                "TypeError",
14276                "function has non-object prototype in instanceof check",
14277            )));
14278        };
14279        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14280        // which is also what makes `proxyOfInstance instanceof C` work.
14281        let mut current = Some(target.clone());
14282        while let Some(object) = current {
14283            if object.ptr_eq(&prototype) {
14284                return Ok(true);
14285            }
14286            current = self.object_prototype_of(&object)?;
14287        }
14288        Ok(false)
14289    }
14290
14291    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14292    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14293        if let Some(proto) = self.proxy_get_prototype_of(object)? {
14294            return Ok(proto);
14295        }
14296        if let Some(exotic) = object.exotic()
14297            && let Some(proto) = exotic.get_prototype(self, object)?
14298        {
14299            return Ok(proto);
14300        }
14301        Ok(object.proto())
14302    }
14303
14304    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14305    pub fn object_set_prototype_of(
14306        &mut self,
14307        object: &Gc<JsObject>,
14308        proto: Option<Gc<JsObject>>,
14309    ) -> JsResult<bool> {
14310        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14311            return Ok(answer);
14312        }
14313        if let Some(exotic) = object.exotic()
14314            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14315        {
14316            return Ok(answer);
14317        }
14318        // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14319        // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14320        // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14321        // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14322        if self
14323            .internal_get(object, "_immutable_proto")
14324            .is_some_and(|flag| flag.to_boolean())
14325            && !same_proto(object.proto().as_ref(), proto.as_ref())
14326        {
14327            return Ok(false);
14328        }
14329        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14330        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14331        // inheriting from itself, which every later prototype walk then had to defend
14332        // against — and `Reflect.setPrototypeOf` reported success for an operation the
14333        // language says is impossible.
14334        if let Some(proto) = &proto {
14335            let mut current = Some(proto.clone());
14336            let mut guard = 0;
14337            while let Some(node) = current {
14338                if node.ptr_eq(object) {
14339                    // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14340                    // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14341                    // while `Reflect.setPrototypeOf` reports it
14342                    // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14343                    return Ok(false);
14344                }
14345                guard += 1;
14346                if guard > 1000 {
14347                    break;
14348                }
14349                current = node.proto();
14350            }
14351        }
14352        // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14353        // re-setting it to the *same* one is a no-op `true`. Missing this made
14354        // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14355        // actually reparent the object — and it is what
14356        // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14357        // forwarding path has nothing else left to refuse it.
14358        if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14359            return Ok(false);
14360        }
14361        object.set_proto(proto);
14362        Ok(true)
14363    }
14364
14365    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14366    ///
14367    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14368    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14369    /// already one.
14370    /// `HasProperty(O, P)`.
14371    ///
14372    /// One implementation, shared with the `in` operator. It used to be a second copy that
14373    /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14374    /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14375    /// proxy ran the wrong hook and could even disagree with `in`. The
14376    /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14377    /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14378    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14379        self.has_own_or_inherited(object, key)
14380    }
14381
14382    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14383    ///
14384    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14385    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14386    /// boolean as well, and it needs the receiver to be the one the caller named.
14387    pub fn set_property_with_key_receiver(
14388        &mut self,
14389        object: &Gc<JsObject>,
14390        key: &PropertyKey,
14391        value: Value,
14392        receiver: Option<&Value>,
14393        on_failure: DeleteFailure,
14394    ) -> JsResult<bool> {
14395        let receiver = receiver
14396            .cloned()
14397            .unwrap_or_else(|| Value::Object(object.clone()));
14398        if object.proxy_state().is_some() {
14399            return match self.proxy_set(object, key, value, &receiver)? {
14400                Some(accepted) => Ok(accepted),
14401                None => Ok(true),
14402            };
14403        }
14404        // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14405        // receiver. This has to be answered here as well as in the storing path below,
14406        // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14407        if object.module_namespace_marker() {
14408            return Ok(false);
14409        }
14410        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14411        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14412        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14413        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14414        //
14415        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14416        //
14417        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14418        // * an *invalid* index with a different receiver answers `true` and does nothing,
14419        //   not even converting `V` (`valueOfCalls` stays 0);
14420        // * a valid index with a different receiver falls through to
14421        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14422        //   value lands on the **receiver**, unconverted, and can be refused by a
14423        //   non-extensible receiver, an accessor, or a read-only index there.
14424        //
14425        // The last one used to write into the view itself, which left `target[0]` changed
14426        // and `receiver[0]` untouched — backwards.
14427        if object.typed_array_element_type().is_some()
14428            && let Some(numeric) = canonical_numeric_index(key)
14429        {
14430            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14431            if same {
14432                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14433                return Ok(true);
14434            }
14435            if !typed_array_index_is_valid(object, numeric) {
14436                return Ok(true);
14437            }
14438            let Some(receiver) = receiver.as_object().cloned() else {
14439                return Ok(false);
14440            };
14441            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14442                if existing.is_accessor() || !existing.writable {
14443                    return Ok(false);
14444                }
14445                let property = Property {
14446                    value: Some(value),
14447                    ..existing
14448                };
14449                return self.object_define_own_property(&receiver, key, property);
14450            }
14451            return self.object_define_own_property(&receiver, key, Property::data(value));
14452        }
14453        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14454        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14455        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14456        // `Reflect.set` to *report* the refusal instead of raising.
14457        //
14458        // A receiver that is not the object turns the whole operation into
14459        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14460        // `[[Set]]` rather than a lookup — that is what makes
14461        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14462        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14463        // writes to `object`, so it cannot express that and is only used when the two are
14464        // the same.
14465        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14466        if !same {
14467            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14468        }
14469        // Same receiver: the plain path below writes into `object`, which is right, but it
14470        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14471        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14472        if let Some(existing) = self.object_get_own_property(object, key)? {
14473            if existing.is_accessor() {
14474                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14475                    Some(setter) => {
14476                        self.call_value(setter, receiver, vec![value])?;
14477                        Ok(true)
14478                    }
14479                    None => Ok(false),
14480                };
14481            }
14482            if !existing.writable {
14483                return Ok(false);
14484            }
14485        }
14486        // Otherwise it is an ordinary create-or-write into `object` itself.
14487        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14488        Ok(true)
14489    }
14490
14491    /// `[[IsExtensible]]`, with the proxy trap when there is one.
14492    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14493        if let Some(answer) = self.proxy_is_extensible(object)? {
14494            return Ok(answer);
14495        }
14496        if let Some(exotic) = object.exotic()
14497            && let Some(answer) = exotic.is_extensible(self, object)?
14498        {
14499            return Ok(answer);
14500        }
14501        Ok(object.is_extensible())
14502    }
14503
14504    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14505    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14506        if let Some(answer) = self.proxy_prevent_extensions(object)? {
14507            return Ok(answer);
14508        }
14509        // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14510        //
14511        // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14512        //
14513        // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14514        // created with an explicit length, because the buffer can still move it. That is
14515        // what makes `Object.freeze` refuse every such view, including a zero-length one
14516        // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14517        // plain buffer is allowed.
14518        if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14519            && buffer
14520                .array_buffer_storage()
14521                .is_some_and(|storage| storage.borrow().is_resizable())
14522        {
14523            return Err(
14524                self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14525            );
14526        }
14527        if let Some(exotic) = object.exotic()
14528            && let Some(answer) = exotic.prevent_extensions(self, object)?
14529        {
14530            return Ok(answer);
14531        }
14532        object.set_extensible(false);
14533        Ok(true)
14534    }
14535
14536    fn copy_properties(
14537        &mut self,
14538        target: &Value,
14539        source: &Value,
14540        exclusion: &Value,
14541    ) -> JsResult<()> {
14542        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14543        // does contribute: its index properties are own, enumerable and writable, which
14544        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14545        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14546        // is a no-op.
14547        let Some(target) = target.as_object() else {
14548            return Ok(());
14549        };
14550        let source_object = match source {
14551            Value::Object(object) => object.clone(),
14552            Value::String(text) => {
14553                // Untaken keys are the string's indices, which are code units.
14554                for index in 0..text.utf16_len() {
14555                    if let Some(unit) = text.wtf8().unit_at(index) {
14556                        target.define_data(&index.to_string(), self.string_wtf8(unit));
14557                    }
14558                }
14559                return Ok(());
14560            }
14561            _ => return Ok(()),
14562        };
14563        // An object *rest* element passes the keys already taken by the literal part as
14564        // an array of **key values**; a spread passes `null`, which excludes nothing. The
14565        // array is read by its elements rather than by its own property names, and the
14566        // values stay `PropertyKey`s: a computed key can be a symbol, and
14567        // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
14568        // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
14569        // strings made a symbol exclusion a no-op.
14570        let mut excluded: Vec<PropertyKey> = Vec::new();
14571        if let Value::Object(list) = exclusion
14572            && let Some(length) = list.array_length()
14573        {
14574            for index in 0..length {
14575                if let Some(value) = list.array_get(index) {
14576                    excluded.push(self.propkey(&value)?);
14577                }
14578            }
14579        }
14580        let source = &source_object;
14581        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14582        // Reading the property table directly made every spread of a proxy empty.
14583        let keys = self.object_own_property_keys(source)?;
14584        for as_key in keys {
14585            // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
14586            // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
14587            // Skipping them silently lost every symbol on every spread and every object
14588            // rest element (`obj-rest-order`).
14589            //
14590            if excluded.contains(&as_key) {
14591                continue;
14592            }
14593            let enumerable = self
14594                .object_get_own_property(source, &as_key)?
14595                .is_some_and(|property| property.enumerable);
14596            if !enumerable {
14597                continue;
14598            }
14599            let value = self
14600                .get_property_key(source, &as_key)?
14601                .unwrap_or(Value::Undefined);
14602            target.define_data_key(&as_key, value);
14603        }
14604        Ok(())
14605    }
14606
14607    // -- iteration ---------------------------------------------------------
14608
14609    /// One object's own keys in enumeration order: array indices ascending, then the
14610    /// rest in insertion order.
14611    ///
14612    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14613    /// whether the key is enumerable, which the caller resolves per key because an
14614    /// array's elements are not in the same store as its named properties.
14615    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14616        // An index can arrive twice, once from the array's element store and once from
14617        // its property map, so the numeric keys go through a map that keeps the
14618        // enumerable answer if either source gave one.
14619        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14620        for (key, enumerable) in &own {
14621            if let Some(index) = key.as_str().and_then(array_index) {
14622                let entry = numeric.entry(index).or_insert(false);
14623                *entry = *entry || *enumerable;
14624            }
14625        }
14626        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14627            .into_iter()
14628            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14629            .collect();
14630        ordered.extend(
14631            own.into_iter()
14632                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14633        );
14634        ordered
14635    }
14636
14637    /// Build the key list a `for-in` loop walks.
14638    ///
14639    /// The order is the specification's: own properties before inherited ones, and
14640    /// within one object the integer-like keys in ascending numeric order ahead of the
14641    /// string keys in insertion order. A shadowed key only appears once, and a key that
14642    /// is a non-enumerable own property anywhere nearer is skipped entirely.
14643    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14644        let record = self.new_object(None);
14645        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14646        // A proxy supplies its own key list, and — the reason this is not just another
14647        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14648        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14649        // descriptor there.
14650        if let Value::Object(object) = value
14651            && object.proxy_state().is_some()
14652        {
14653            let own = self
14654                .proxy_own_keys(object)?
14655                .unwrap_or_else(|| object.own_property_keys());
14656            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14657            let mut numeric: Vec<u32> = Vec::new();
14658            let mut rest: Vec<PropertyKey> = Vec::new();
14659            for key in own {
14660                match key.as_str().and_then(array_index) {
14661                    Some(index) => numeric.push(index),
14662                    None => rest.push(key),
14663                }
14664            }
14665            numeric.sort_unstable();
14666            ordered.extend(
14667                numeric
14668                    .into_iter()
14669                    .map(|index| PropertyKey::from(index.to_string())),
14670            );
14671            ordered.extend(rest);
14672            for (index, key) in ordered.into_iter().enumerate() {
14673                record.define_data(&index.to_string(), self.key_value(&key));
14674            }
14675            record.define_data("__index", Value::Int(0));
14676            // The mark that makes `for_in_advance` re-ask the proxy per key.
14677            record.define_data("__proxy", Value::Object(object.clone()));
14678            return Ok(record);
14679        }
14680        if let Value::Object(object) = value {
14681            let mut chain = vec![object.clone()];
14682            chain.extend(object.chain());
14683            // Every own string key the walk has seen, enumerable or not. A
14684            // non-enumerable own property still hides a same-named enumerable one
14685            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14686            // keeps `x` out of the loop even when the prototype has one.
14687            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14688            for object in chain {
14689                let mut own: Vec<(crate::value::Wtf8, bool)> = object
14690                    .own_property_keys()
14691                    .iter()
14692                    .filter_map(|key| key.as_wtf8().cloned())
14693                    .map(|key| {
14694                        let enumerable = object
14695                            .own_property(&key.to_string_lossy())
14696                            .map(|property| property.enumerable)
14697                            .unwrap_or(false);
14698                        (key, enumerable)
14699                    })
14700                    .collect();
14701                if let Some(length) = object.array_length() {
14702                    own.retain(|(key, _)| key.as_str() != Some("length"));
14703                    for index in 0..length {
14704                        // A dense element is enumerable; a **hole** is not there at all —
14705                        // and a hole is also what an index with a recorded descriptor
14706                        // leaves behind, in which case the table entry above already
14707                        // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14708                        // defines index 0 non-enumerable and `for…in` must skip it).
14709                        if let Some(value) = object.array_get(index)
14710                            && !matches!(value, Value::Hole)
14711                        {
14712                            own.push((crate::value::Wtf8::new(index.to_string()), true));
14713                        }
14714                    }
14715                }
14716                // Integer-like keys come first in ascending order, then the rest in
14717                // insertion order — and the ordering is *per object*, not for the chain
14718                // as a whole: one pass over every collected key lifted a prototype's
14719                // `"4"` above the target's own `x`/`y`, which is not the order
14720                // `for…in` reports.
14721                for (key, enumerable) in Self::order_own_keys(own) {
14722                    if visited.contains(&key) {
14723                        continue;
14724                    }
14725                    visited.push(key.clone());
14726                    if enumerable {
14727                        keys.push(key);
14728                    }
14729                }
14730            }
14731        }
14732        for (index, key) in keys.into_iter().enumerate() {
14733            record.define_data(&index.to_string(), self.string_wtf8(key));
14734        }
14735        record.define_data("__index", Value::Int(0));
14736        Ok(record)
14737    }
14738
14739    /// The next key of a `for…in` record, `None` when the loop is done.
14740    ///
14741    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14742    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14743    /// the loop reaches it, so a handler that stops reporting a key partway through drops
14744    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14745    /// key the handler had already withdrawn.
14746    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14747        let Value::Object(record) = record else {
14748            return Ok(None);
14749        };
14750        let proxy = record
14751            .own_property("__proxy")
14752            .and_then(|property| property.value);
14753        loop {
14754            let index = record
14755                .own_property("__index")
14756                .and_then(|property| property.value)
14757                .map(|value| value.to_int32())
14758                .unwrap_or(0);
14759            let Some(candidate) = record
14760                .own_property(&index.to_string())
14761                .and_then(|property| property.value)
14762            else {
14763                return Ok(None);
14764            };
14765            record.define_data("__index", Value::Int(index + 1));
14766            let text = candidate.to_js_string();
14767            let Some(Value::Object(proxy)) = &proxy else {
14768                return Ok(Some(text));
14769            };
14770            // The candidate is already a key string here, so the lookup does not need a
14771            // second `ToPropertyKey` conversion.
14772            let key = PropertyKey::from(text.as_str());
14773            let live = match self.proxy_get_own_property(proxy, &key)? {
14774                Some(descriptor) => descriptor,
14775                // Not a proxy after all, or it lost its state: fall back to the target.
14776                None => proxy.own_property_key(&key),
14777            };
14778            if live.is_some_and(|property| property.enumerable) {
14779                return Ok(Some(text));
14780            }
14781            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14782            // next one.
14783        }
14784    }
14785
14786    /// The iterator for `for-of`: the object and its `next` method.
14787    ///
14788    /// An object that already carries a `next` method is used as it is — that is what
14789    /// `arr.values()` returns — and only arrays and strings get the built-in
14790    /// sequence iterator.
14791    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14792    ///
14793    /// Callers that must choose between the iterable and the array-like protocol — the
14794    /// typed-array constructor is the main one — need to ask *before* committing to one.
14795    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14796        let key = self.realm.well_known_key(WellKnown::Iterator);
14797        let method = self.read_field_key(value, &key)?;
14798        if matches!(method, Value::Undefined | Value::Null) {
14799            return Ok(false);
14800        }
14801        if !matches!(&method, Value::Object(object) if object.is_callable()) {
14802            return Err(Signal::Throw(
14803                self.make_error("TypeError", "Symbol.iterator is not callable"),
14804            ));
14805        }
14806        Ok(true)
14807    }
14808
14809    /// Collect everything an iterable yields.
14810    ///
14811    /// The cap is a guard against a generator that never ends: an unbounded collect would
14812    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14813    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14814    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14815    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14816        const MAX_ITEMS: usize = 1 << 24;
14817        let iterator = self.get_iterator(value)?;
14818        let mut out = Vec::new();
14819        loop {
14820            let (element, done) = self.iterator_step(&iterator)?;
14821            if done {
14822                return Ok(out);
14823            }
14824            out.push(element);
14825            if out.len() > MAX_ITEMS {
14826                // Close before refusing: the walk is being abandoned, so the iterator's
14827                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14828                // unrun and a locked resource unreleased.
14829                self.close_iterator_after_throw(&iterator)?;
14830                return Err(self.range_error("iterable is too long to collect"));
14831            }
14832        }
14833    }
14834
14835    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14836    ///
14837    /// A native constructor calls this once it has validated its arguments, which is the
14838    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14839    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14840    /// never reached. The prototype comes from `new.target` when it is an object, and from
14841    /// `default_proto` otherwise.
14842    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14843        let proto = self.ctor_prototype(default_proto)?;
14844        Ok(self.new_object(Some(proto)))
14845    }
14846
14847    /// An **array** whose prototype comes from `new.target`.
14848    ///
14849    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14850    /// instance from `new.target.prototype`, and building a plain array instead made every
14851    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14852    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14853        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14854        Ok(JsObject::array(self.heap, Some(proto), 0))
14855    }
14856
14857    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14858    ///
14859    /// The `Option` form is for the constructors that build their instance in a helper which
14860    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14861    /// from `await`'s internal promise, and only the first has a `new.target`.
14862    fn ctor_prototype_opt(
14863        &mut self,
14864        default_proto: Option<Gc<JsObject>>,
14865    ) -> JsResult<Option<Gc<JsObject>>> {
14866        // `active_new_target`: by the time a native constructor runs, `call_value` has
14867        // already consumed the parked value.
14868        let Some(target) = self
14869            .active_new_target
14870            .as_object()
14871            .cloned()
14872            .map(Value::Object)
14873        else {
14874            return Ok(default_proto);
14875        };
14876        let Some(target) = target.as_object().cloned() else {
14877            return Ok(default_proto);
14878        };
14879        match self.get_property(&target, "prototype")? {
14880            Some(Value::Object(proto)) => Ok(Some(proto)),
14881            _ => Ok(default_proto),
14882        }
14883    }
14884
14885    /// `new.target.prototype`, or `default_proto` when this is a plain call.
14886    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14887        let Some(target) = self.active_new_target.as_object().cloned() else {
14888            return Ok(default_proto);
14889        };
14890        match self.get_property(&target, "prototype")? {
14891            Some(Value::Object(proto)) => Ok(proto),
14892            _ => Ok(default_proto),
14893        }
14894    }
14895
14896    /// `CreateDataPropertyOrThrow(O, key, value)`.
14897    ///
14898    /// A *definition*, not an assignment. The difference is visible the moment the target
14899    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14900    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14901    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14902    /// refused (`configurable: false`).
14903    ///
14904    /// The fast path exists because this is called once per element by `map`, `filter`,
14905    /// `slice` and friends: a plain array with no custom element descriptors and a writable
14906    /// `length` can store straight into its element vector.
14907    pub fn create_data_property_or_throw(
14908        &mut self,
14909        object: &Gc<JsObject>,
14910        index: usize,
14911        value: Value,
14912    ) -> JsResult<()> {
14913        // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
14914        // an array (that is what `Array.isArray` must say), so the element fast path would
14915        // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
14916        // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
14917        // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
14918        // records the exact trap sequence.
14919        if object.proxy_state().is_none()
14920            && object.is_array()
14921            && object.elements_writable()
14922            && !object.has_element_descriptors()
14923            && object.is_extensible()
14924            && object.array_set(self.heap, index, value.clone())
14925        {
14926            return Ok(());
14927        }
14928        let key = PropertyKey::from(index.to_string());
14929        let property = Property {
14930            value: Some(value),
14931            writable: true,
14932            enumerable: true,
14933            configurable: true,
14934            ..Property::default()
14935        };
14936        // `CreateDataProperty` always asks for the default attributes, so it can only ever
14937        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
14938        // the rest. Checking here rather than inside `object_define_own_property` is
14939        // deliberate: that function receives a fully-populated `Property` and cannot tell
14940        // an omitted attribute from an explicit `false`, so the generic check it would need
14941        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
14942        // writable property (that cost eight `Object/defineProperty` tests).
14943        if object.proxy_state().is_none()
14944            && let Some(existing) = self.object_get_own_property(object, &key)?
14945            && !existing.configurable
14946        {
14947            return Err(self.type_error("cannot create the property"));
14948        }
14949        if self.object_define_own_property(object, &key, property)? {
14950            return Ok(());
14951        }
14952        Err(self.type_error("cannot create the property"))
14953    }
14954
14955    /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
14956    ///
14957    /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
14958    /// its callers have; this is the same operation for the named properties a built-in
14959    /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
14960    /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
14961    /// `Array.prototype` cannot see it — while `Set` would run that accessor.
14962    pub fn create_named_data_property_or_throw(
14963        &mut self,
14964        object: &Gc<JsObject>,
14965        key: &str,
14966        value: Value,
14967    ) -> JsResult<()> {
14968        let key = PropertyKey::from(key);
14969        let property = Property {
14970            value: Some(value),
14971            writable: true,
14972            enumerable: true,
14973            configurable: true,
14974            ..Property::default()
14975        };
14976        if object.proxy_state().is_none()
14977            && let Some(existing) = self.object_get_own_property(object, &key)?
14978            && !existing.configurable
14979        {
14980            return Err(self.type_error("cannot create the property"));
14981        }
14982        if self.object_define_own_property(object, &key, property)? {
14983            return Ok(());
14984        }
14985        Err(self.type_error("cannot create the property"))
14986    }
14987
14988    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14989    ///
14990    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14991    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14992    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14993    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14994    /// run user code and both can throw.
14995    pub fn species_constructor(
14996        &mut self,
14997        object: &Gc<JsObject>,
14998        default: Value,
14999    ) -> JsResult<Value> {
15000        let Some(constructor) = self.get_property(object, "constructor")? else {
15001            return Ok(default);
15002        };
15003        let constructor = match constructor {
15004            Value::Undefined => return Ok(default),
15005            Value::Object(constructor) => constructor,
15006            _ => return Err(self.type_error("constructor is not an object")),
15007        };
15008        let key = self.realm.well_known_key(WellKnown::Species);
15009        let species = self.get_property_key(&constructor, &key)?;
15010        match species {
15011            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
15012            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
15013            Some(_) => Err(self.type_error("species is not a constructor")),
15014        }
15015    }
15016
15017    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
15018    ///
15019    /// The result is an array of `length` holes whose prototype comes from
15020    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
15021    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
15022    /// is why the `IsArray` check is the first step and not an optimisation.
15023    pub fn array_species_create(
15024        &mut self,
15025        original: &Value,
15026        length: usize,
15027    ) -> JsResult<Gc<JsObject>> {
15028        // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
15029        // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
15030        // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
15031        // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
15032        // `new_array_of_length` (`slice/create-non-array-invalid-len`).
15033        // `ArrayCreate(length)` is only reached when the result is a **plain array of this
15034        // realm** — the species may be a user function that ignores the length entirely, and
15035        // then `2**53 - 1` is not its problem
15036        // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
15037        // a short proxy and expects the copy loop to run).
15038        let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
15039            if length > ARRAY_CREATE_LIMIT {
15040                return Err(interp.range_error("invalid array length"));
15041            }
15042            Ok(interp.new_array_of_length(length))
15043        };
15044        let Some(object) = original.as_object().cloned() else {
15045            return default(self);
15046        };
15047        if !object.is_array() {
15048            return default(self);
15049        }
15050        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
15051        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
15052        let Some(constructor) = self.get_property(&object, "constructor")? else {
15053            return default(self);
15054        };
15055        let species = match constructor {
15056            Value::Undefined => return Ok(self.new_array_of_length(length)),
15057            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
15058                return default(self);
15059            }
15060            Value::Object(constructor) => {
15061                let key = self.realm.well_known_key(WellKnown::Species);
15062                match self.get_property_key(&constructor, &key)? {
15063                    None | Some(Value::Undefined) | Some(Value::Null) => {
15064                        return default(self);
15065                    }
15066                    Some(species) => species,
15067                }
15068            }
15069            // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
15070            // is a `TypeError`, not "the default". Treating it as the default made
15071            // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
15072            // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
15073            // `concat/create-ctor-non-object` are the same rule three times.
15074            _ => return Err(self.type_error("constructor is not an object")),
15075        };
15076        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
15077        // that is merely callable is the `create-species-non-ctor` case.
15078        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
15079            return Err(self.type_error("species is not a constructor"));
15080        }
15081        // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
15082        // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
15083        // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
15084        let created = self.construct(
15085            species.clone(),
15086            species,
15087            vec![crate::object::length_value(length)],
15088        )?;
15089        let Some(created) = created.as_object().cloned() else {
15090            return Err(self.type_error("species constructor did not answer an object"));
15091        };
15092        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
15093        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
15094        // object, and `create-species-with-non-writable-property` asserts exactly that.
15095        // The length is set for the array case; the generic case is the caller's
15096        // `Set(A, "length", …)`.
15097        if created.is_array() {
15098            created.array_set_length(self.heap, length);
15099        }
15100        Ok(created)
15101    }
15102
15103    /// Whether `object` is this realm's `%Array%`.
15104    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
15105        self.realm
15106            .array_constructor
15107            .as_ref()
15108            .is_some_and(|array| array.ptr_eq(object))
15109    }
15110
15111    /// A fresh `length`-hole array with the intrinsic prototype.
15112    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
15113        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
15114        array.array_set_length(self.heap, length);
15115        array
15116    }
15117
15118    /// Whether this call is a construction, i.e. `new.target` is defined.
15119    ///
15120    /// A native constructor receives `this = undefined` (it builds its own instance), so it
15121    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
15122    /// The native function currently executing, if any.
15123    pub fn current_native(&self) -> Option<Gc<JsObject>> {
15124        self.current_native.clone()
15125    }
15126
15127    /// Whether this call is a construction, i.e. `new.target` is defined.
15128    pub fn is_constructing(&self) -> bool {
15129        // `active_new_target`, not `pending_new_target`: the parked value is consumed by
15130        // `call_value` before a native runs, so by the time a constructor body asks, the
15131        // answer is only in the active slot.
15132        matches!(self.active_new_target, Value::Object(_))
15133    }
15134
15135    /// The `TypeError` a constructor too primitive to have a wrapper raises.
15136    ///
15137    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15138    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15139    /// happens inside the native function, which is why the trace carries an
15140    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15141    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15142    /// constructor`, and an unnamed one reports the leading space of `" is not a
15143    /// constructor"` because the reference formats the empty name as it is.
15144    ///
15145    /// It is also the answer for a `new.target` that cannot be named at all — not a
15146    /// function, or a throwing `name` getter — where the reference falls back to the bare
15147    /// `not a constructor`.
15148    pub fn not_a_constructor_error(&mut self) -> Signal {
15149        let target = self.active_new_target.clone();
15150        self.not_a_constructor_error_for(target)
15151    }
15152
15153    /// The same `TypeError` for an explicit target, for the callers that check
15154    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15155    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15156        let target = match target {
15157            Value::Object(target) if target.is_callable() => target,
15158            _ => return self.type_error("not a constructor"),
15159        };
15160        let name = match self.get_property(&target, "name") {
15161            Ok(Some(value)) => value.to_js_string(),
15162            _ => return self.type_error("not a constructor"),
15163        };
15164        self.type_error(format!("{name} is not a constructor"))
15165    }
15166
15167    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15168    ///
15169    /// True whenever `new.target` is not the callee itself, or when it has no usable
15170    /// `prototype` — the cases where reading the property is observable at all.
15171    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15172        match &self.active_new_target {
15173            Value::Object(target) => !target.ptr_eq(callee),
15174            Value::Undefined => false,
15175            _ => true,
15176        }
15177    }
15178
15179    /// The symbol key for one of the engine's own hidden slots.
15180    ///
15181    /// Cached on the realm, so every object of a kind shares one key and a slot can be
15182    /// read back by name.
15183    /// Whether any object on `object`'s **prototype chain** owns an array index.
15184    ///
15185    /// The one question the array methods' dense fast paths have to ask before touching the
15186    /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15187    /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15188    /// vector an unreliable answer. Walking the chain once per call is cheap because a
15189    /// prototype almost never holds an index.
15190    pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15191        let mut current = object.proto();
15192        // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15193        for _ in 0..10_000 {
15194            let Some(proto) = current else {
15195                return false;
15196            };
15197            if proto.has_indexed_own_property() {
15198                return true;
15199            }
15200            current = proto.proto();
15201        }
15202        false
15203    }
15204
15205    /// The hidden symbol a named internal slot is keyed by, created on first use.
15206    ///
15207    /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15208    /// either keeping a table of its own.
15209    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15210        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15211            return PropertyKey::Symbol(symbol.clone());
15212        }
15213        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15214        self.realm
15215            .internal_slots
15216            .borrow_mut()
15217            .insert(name, Value::Symbol(symbol.clone()));
15218        PropertyKey::Symbol(symbol)
15219    }
15220
15221    /// Read a hidden slot, or `None` when the object has none of that name.
15222    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15223        let slots = self.realm.internal_slots.borrow();
15224        let Value::Symbol(symbol) = slots.get(name)? else {
15225            return None;
15226        };
15227        object
15228            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15229            .and_then(|property| property.value)
15230    }
15231
15232    /// Define a hidden slot.
15233    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15234        let key = self.internal_slot(name);
15235        object.define_key(&key, Property::with_attributes(value, false, false));
15236    }
15237
15238    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15239    ///
15240    /// The method is looked up on the value (through its prototype), called with no
15241    /// arguments, and its result becomes the iterator. A generator gets here through
15242    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15243    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15244    ///
15245    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15246    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15247    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15248    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15249    /// does, and a user-defined iterable works without a special case.
15250    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15251    /// `Symbol.iterator`.
15252    ///
15253    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15254    /// iterable is legal there, and each value it produces is simply already settled by
15255    /// the time the `await` around it runs.
15256    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15257        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15258        let method = self.read_field_key(value, &async_key)?;
15259        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15260        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15261        // is *present but not callable* is a TypeError — it does not mean "try the other
15262        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15263        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15264        // guard is there to catch.
15265        let absent = matches!(method, Value::Undefined | Value::Null);
15266        if !absent {
15267            let Value::Object(object) = &method else {
15268                return Err(Signal::Throw(
15269                    self.make_error("TypeError", "value is not iterable"),
15270                ));
15271            };
15272            if !object.is_callable() {
15273                return Err(Signal::Throw(
15274                    self.make_error("TypeError", "value is not iterable"),
15275                ));
15276            }
15277        }
15278        if absent {
15279            // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15280            // generator's `yield*` both reach here, and the wrapper is what puts
15281            // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15282            // caller — a poisoned `constructor` on that value rejects instead of being
15283            // yielded, and a rejection closes the synchronous iterator first.
15284            let sync = self.get_iterator(value)?;
15285            return self.async_from_sync_iterator(sync);
15286        }
15287        let iterator = self.call_value(method, value.clone(), Vec::new())?;
15288        if !matches!(iterator, Value::Object(_)) {
15289            return Err(Signal::Throw(
15290                self.make_error("TypeError", "iterator is not an object"),
15291            ));
15292        }
15293        let next = self.read_field(&iterator, "next")?;
15294        Ok(Iterator {
15295            object: iterator,
15296            next,
15297        })
15298    }
15299
15300    /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15301    ///
15302    /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15303    /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15304    /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15305    fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15306        let Some(factory) = self.realm.async_from_sync.clone() else {
15307            // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15308            // raw synchronous iterator rather than refusing to iterate at all.
15309            return Ok(sync);
15310        };
15311        let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15312        let next = self.read_field(&wrapper, "next")?;
15313        Ok(Iterator {
15314            object: wrapper,
15315            next,
15316        })
15317    }
15318
15319    /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15320    /// read — `@@iterator` is **not** consulted.
15321    ///
15322    /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15323    /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15324    /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15325    /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15326    /// refused it with "[object Object] is not iterable".
15327    pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15328        if !matches!(value, Value::Object(_)) {
15329            return Err(self.type_error("iterator is not an object"));
15330        }
15331        let next = self.read_field(&value, "next")?;
15332        Ok(Iterator {
15333            object: value,
15334            next,
15335        })
15336    }
15337
15338    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15339        let key = self.realm.well_known_key(WellKnown::Iterator);
15340        let method = self.read_field_key(value, &key)?;
15341        let Value::Object(function) = &method else {
15342            return Err(Signal::Throw(self.make_error(
15343                "TypeError",
15344                &format!("{} is not iterable", value.to_js_string()),
15345            )));
15346        };
15347        if !function.is_callable() {
15348            return Err(Signal::Throw(self.make_error(
15349                "TypeError",
15350                &format!("{} is not iterable", value.to_js_string()),
15351            )));
15352        }
15353        let iterator = self.call_value(method, value.clone(), Vec::new())?;
15354        // The spec requires an object here; a primitive iterator has no `next` to call
15355        // and would fail one step later with a confusing message.
15356        if !matches!(iterator, Value::Object(_)) {
15357            return Err(Signal::Throw(
15358                self.make_error("TypeError", "iterator is not an object"),
15359            ));
15360        }
15361        let next = self.read_field(&iterator, "next")?;
15362        Ok(Iterator {
15363            object: iterator,
15364            next,
15365        })
15366    }
15367
15368    /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15369    /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15370    /// exception from `return` propagates normally instead of being swallowed. That is the
15371    /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15372    /// because confusing them is exactly the bug both exist to avoid.
15373    pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15374        let method = self.read_field(&iterator.object, "return")?;
15375        if matches!(method, Value::Undefined | Value::Null) {
15376            return Ok(());
15377        }
15378        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15379            return Err(self.type_error("iterator return is not a function"));
15380        }
15381        self.call_value(method, iterator.object.clone(), Vec::new())?;
15382        Ok(())
15383    }
15384
15385    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15386    /// cannot replace it.
15387    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15388        let method = self.read_field(&iterator.object, "return")?;
15389        if matches!(method, Value::Undefined | Value::Null) {
15390            return Ok(());
15391        }
15392        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15393            return Err(self.type_error("iterator return is not a function"));
15394        }
15395        self.call_value(method, iterator.object.clone(), Vec::new())?;
15396        Ok(())
15397    }
15398
15399    /// One step of an internal iterator: the value and whether it is exhausted.
15400    /// Replace the iterator slot of an iteration record with `undefined`.
15401    ///
15402    /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15403    /// `undefined` record is what every close path already treats as "nothing to close", so
15404    /// one store both records "this iterator must not be closed" and keeps
15405    /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15406    fn clear_iterator_slot(&mut self, slot: usize) {
15407        let frame = self.frame_mut();
15408        let depth = frame.stack.len();
15409        if depth > slot {
15410            frame.stack[depth - 1 - slot] = Value::Undefined;
15411        }
15412    }
15413
15414    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15415        // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15416        // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15417        // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15418        // before the first step, so an iterator with no `next` still gets its `return`
15419        // called by `it.return()` instead of failing up front
15420        // (`array-rest-iter-rtrn-close-err`).
15421        if let Value::Object(object) = &iterator.next
15422            && object.is_callable()
15423        {
15424            let result =
15425                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15426            let Some(result) = result.as_object().cloned() else {
15427                return Err(self.type_error("iterator result is not an object"));
15428            };
15429            let done = self
15430                .get_property(&result, "done")?
15431                .is_some_and(|value| value.to_boolean());
15432            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15433            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15434            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15435            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15436            // made an unrelated `value` getter observable after the loop was over.
15437            if done {
15438                return Ok((Value::Undefined, true));
15439            }
15440            let value = self
15441                .get_property(&result, "value")?
15442                .unwrap_or(Value::Undefined);
15443            return Ok((value, false));
15444        }
15445        // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15446        // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15447        // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15448        // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15449        Err(Signal::Throw(self.make_error(
15450            "TypeError",
15451            "iterator's next method is not callable",
15452        )))
15453    }
15454
15455    /// `[...iterable]`: append everything the iterator yields, and answer the next
15456    /// index.
15457    ///
15458    /// This goes through the same iterator machinery `for-of` uses rather than copying
15459    /// an array's elements, because a spread source is any iterable: a string spreads
15460    /// into its characters and an array iterator spreads into its results. Handling
15461    /// only arrays made `[..."ab"]` come out empty with no error at all.
15462    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
15463        let Some(target) = array.as_object().cloned() else {
15464            return Ok(0);
15465        };
15466        let start = target.array_length().unwrap_or(0);
15467        let mut added = 0;
15468        let iterator = self.get_iterator(iterable)?;
15469        loop {
15470            let (value, done) = self.iterator_step(&iterator)?;
15471            if done {
15472                break;
15473            }
15474            target.array_set(self.heap, start + added, value);
15475            added += 1;
15476        }
15477        Ok((start + added) as i32)
15478    }
15479
15480    /// How an uncaught exception is reported.
15481    ///
15482    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15483    /// with `ToString` — `js_std_dump_error` is three lines that end in
15484    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15485    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15486    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15487    ///
15488    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15489    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15490    /// `toString`"; it does call it, but only for objects of a class it does not know how
15491    /// to walk, and never for errors, arrays or plain objects.
15492    ///
15493    /// A printer that fails must not take the reporter down with it, so that case falls
15494    /// back to the `ToString` rendering.
15495    pub fn describe_exception(&mut self, value: &Value) -> String {
15496        match crate::print::sprint(self, value) {
15497            Ok(text) => text,
15498            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15499        }
15500    }
15501
15502    /// The file name of whatever is running, innermost frame first.
15503    ///
15504    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15505    /// innermost frame's file name, without distinguishing a module body from a plain
15506    /// script. `import()` uses it as the base for a relative specifier, which is why
15507    /// `import('./x.js')` inside a script resolves next to the script and not next to the
15508    /// process's working directory.
15509    pub fn script_or_module_name(&self) -> Option<String> {
15510        self.script_or_module_name_at(0)
15511    }
15512
15513    /// [`Interp::script_or_module_name`] `level` frames further out.
15514    ///
15515    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15516    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15517    /// frame without a file name is skipped rather than counted, because a native call
15518    /// pushes no frame of its own and so cannot be a level.
15519    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15520        self.frames
15521            .iter()
15522            .rev()
15523            .filter_map(|frame| frame.code.code.filename.clone())
15524            .nth(level)
15525    }
15526
15527    /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15528    ///
15529    /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15530    /// because that is what a stack trace should print, but §19.2.1.1's
15531    /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15532    /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15533    /// produced the bare specifier `x.js`, which the loader then looked for in the working
15534    /// directory instead of beside the file that called `eval`.
15535    pub fn script_or_module_file_name(&self) -> Option<String> {
15536        self.frames.iter().rev().find_map(|frame| {
15537            let name = frame.code.code.filename.as_deref()?;
15538            (!name.starts_with('<')).then(|| name.to_string())
15539        })
15540    }
15541
15542    /// The current call stack, formatted the way `qjs` prints `error.stack`.
15543    ///
15544    /// One `    at name (file:line:col)` line per active frame, innermost first. The
15545    /// position is the one recorded for the instruction each frame is stopped on, which
15546    /// is why the compiler builds a pc-to-position table per function: without it a
15547    /// trace could only name the function, not the line inside it.
15548    ///
15549    /// A frame whose code has no positions prints just `(file)`, matching the
15550    /// reference's output for stripped bytecode.
15551    pub fn stack_trace(&self) -> String {
15552        self.stack_trace_skipping(0)
15553    }
15554
15555    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15556    fn stack_trace_skipping(&self, skip: usize) -> String {
15557        // One ordered list, innermost first, so `skip` counts the same thing whether the
15558        // frames it leaves out are native or bytecode. Indices rather than references: a
15559        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15560        let depth = self.frames.len();
15561        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15562        // A native entered while `at` bytecode frames were live was called *from* the
15563        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15564        // entered at the current depth are therefore innermost of all.
15565        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15566            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15567                if *at == wanted {
15568                    order.push((true, index));
15569                }
15570            }
15571        };
15572        push_natives(&mut order, depth);
15573        for index in (0..depth).rev() {
15574            order.push((false, index));
15575            push_natives(&mut order, index);
15576        }
15577        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15578        // barrier. Natives entered at exactly the barrier depth are the eval entry point
15579        // itself (`evalScript (native)`), and the reference leaves those out too.
15580        if let Some(barrier) = self.trace_barriers.last().copied() {
15581            order.retain(|(is_native, index)| match is_native {
15582                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15583                false => *index >= barrier,
15584            });
15585        }
15586
15587        let mut out = String::new();
15588        for (is_native, index) in order.into_iter().skip(skip) {
15589            match is_native {
15590                true => {
15591                    out.push_str("    at ");
15592                    let (native, _) = &self.native_frames[index];
15593                    let name = native
15594                        .own_property("name")
15595                        .and_then(|property| property.value)
15596                        .map(|value| value.to_js_string())
15597                        .unwrap_or_default();
15598                    out.push_str(&name);
15599                    out.push_str(" (native)\n");
15600                }
15601                false => {
15602                    let frame = &self.frames[index];
15603                    let code = &frame.code.code;
15604                    let file = code.filename.as_deref().unwrap_or("<input>");
15605                    // The name comes from the function *object*, not from the compiled code:
15606                    // an anonymous function expression is named by the property it is stored
15607                    // in (`{valueOf: function(){}}`), which only the object knows.
15608                    let bound_name = match &frame.callee {
15609                        Value::Object(object) => {
15610                            object
15611                                .own_property("name")
15612                                .and_then(|property| match property.value {
15613                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
15614                                        Some(text.to_string_lossy().into_owned())
15615                                    }
15616                                    _ => None,
15617                                })
15618                        }
15619                        _ => None,
15620                    };
15621                    // No callee object means the body was entered by the host, so the
15622                    // name has to come from the compiled code. Two cases differ:
15623                    //
15624                    // * an *unnamed* function of any kind — the reference reads the
15625                    //   `name` property, finds it empty, and prints `<anonymous>`;
15626                    // * a *module* body, which has no `name` property at all: the
15627                    //   reference builds that function object with `js_closure2` and
15628                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15629                    //   so a trace reaching it also prints `<anonymous>` — while a
15630                    //   *script* body prints `<eval>`, its `name`.
15631                    let unnamed = code.name.is_empty() || code.module.is_some();
15632                    out.push_str("    at ");
15633                    match bound_name.as_deref() {
15634                        Some(name) => out.push_str(name),
15635                        None if unnamed => out.push_str("<anonymous>"),
15636                        None => out.push_str(&code.name),
15637                    }
15638                    match code.position_at(frame.at as u32) {
15639                        Some((line, column)) => {
15640                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
15641                        }
15642                        None => out.push_str(&format!(" ({file})\n")),
15643                    }
15644                }
15645            }
15646        }
15647        out
15648    }
15649
15650    /// Give an anonymous function the name of the property it is stored in.
15651    ///
15652    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15653    /// enumerable and not configurable, and a function that already has a real name
15654    /// keeps it.
15655    ///
15656    /// "Already named" means a *non-empty* name: every function object is created with
15657    /// a `name` of `""` so the property exists on all of them, and treating that empty
15658    /// string as a name left every anonymous function nameless — which is how a stack
15659    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
15660    /// `SetFunctionName`, for a name that came from source text.
15661    fn set_function_name(&mut self, function: &Value, name: &str) {
15662        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15663    }
15664
15665    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15666    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15667    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15668        let Value::Object(object) = function else {
15669            return;
15670        };
15671        // `SetFunctionName` applies to *functions* and classes only, and only when they are
15672        // anonymous. Without the callability guard, `{value: someObject}` renamed
15673        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15674        // on the right-hand side of a property. That is how a `zipKeyed` result object
15675        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15676        // has no `NamedEvaluation` at all.
15677        if !object.is_callable() {
15678            return;
15679        }
15680        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15681            && !existing.wtf8().is_empty()
15682        {
15683            return;
15684        }
15685        let text = self.string_wtf8(name.clone());
15686        object.define("name", Property::name_or_length(text));
15687    }
15688
15689    // -- global declarations -----------------------------------------------
15690
15691    /// Declare a global binding, creating its reference cell.
15692    /// Declare a `var` or function global, whose home is the global object.
15693    ///
15694    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15695    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15696    /// such as `print`, or a redeclaration — is left alone.
15697    pub fn declare_var_global(&mut self, name: &str) {
15698        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15699        // global object is exactly the leak `typeof my_var === "undefined"` after
15700        // `eval("var my_var=2")` rules out.
15701        if let Some(scope) = self.eval_scope.as_mut() {
15702            scope.entry(name.to_string()).or_insert(Value::Undefined);
15703            return;
15704        }
15705        // A sloppy direct eval declares into its *caller's* variable environment. Doing
15706        // this on the global object instead made `eval("var c = 1")` inside a parameter
15707        // list overwrite a global `c`, and made two calls to the same function share one
15708        // binding.
15709        if let Some(cell) = self.declare_eval_local(name) {
15710            cell.set(Value::Undefined);
15711            return;
15712        }
15713        let global = self.realm.global.clone();
15714        if global.own_property(name).is_some() {
15715            return;
15716        }
15717        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15718        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15719        // whole point of that trick and what lets `Object.defineProperty` reshape it
15720        // afterwards. `eval_scope` is `Some` while an eval is running.
15721        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15722        global.define(
15723            name,
15724            Property {
15725                value: Some(Value::Undefined),
15726                writable: true,
15727                enumerable: true,
15728                configurable: from_eval,
15729                ..Property::default()
15730            },
15731        );
15732    }
15733
15734    /// Declare a *lexical* global binding, which starts in its dead zone.
15735    ///
15736    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15737    /// global object and is created when its initialiser runs.
15738    pub fn declare_global(&mut self, name: &str, is_const: bool) {
15739        if is_const {
15740            self.realm.lexical_consts.insert(name.to_string());
15741        }
15742        if !self.realm.globals.contains_key(name) {
15743            // `Uninitialized` rather than `Undefined`: the binding exists but is not
15744            // readable until its initialiser runs, and that is what `let x` before
15745            // `x = 1` has to observe.
15746            let cell = self.new_cell(Value::Uninitialized);
15747            self.realm.globals.insert(name.to_string(), cell);
15748            self.realm.declared.push(name.to_string());
15749        }
15750    }
15751}
15752
15753/// The bytecode and environment of a function object, if it is a bytecode function.
15754///
15755/// Extracted before a call so no borrow of the object is held across it.
15756fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15757    function.with(|data| match &data.kind {
15758        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15759        _ => None,
15760    })
15761}
15762
15763/// A native call target, extracted before the call so no borrow is held.
15764enum NativeCall {
15765    Native(NativeFn),
15766    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15767    /// not hold that object's `RefCell` borrow.
15768    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15769    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15770    Bound {
15771        target: Value,
15772        this: Value,
15773        leading: Vec<Value>,
15774    },
15775    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15776    Revoker(crate::object::ProxyRef),
15777    /// A promise's `resolve`.
15778    PromiseResolve(Gc<JsObject>),
15779    /// A promise's `reject`.
15780    PromiseReject(Gc<JsObject>),
15781    /// The executor `NewPromiseCapability(C)` hands a user constructor.
15782    CapabilityExecutor {
15783        state: Gc<JsObject>,
15784    },
15785    /// One leg of a `then` that settles through a user capability.
15786    ThenShim {
15787        handler: Option<Value>,
15788        resolve: Value,
15789        reject: Value,
15790        fulfilled: bool,
15791    },
15792    /// One continuation of an `await`.
15793    AwaitResume {
15794        coroutine: Gc<JsObject>,
15795        promise: Gc<JsObject>,
15796        kind: ResumeKind,
15797    },
15798    /// One element of a `Promise` combinator settling.
15799    CombinatorSettle {
15800        state: Gc<JsObject>,
15801        index: usize,
15802        fulfilled: bool,
15803    },
15804    /// One of `Promise.prototype.finally`'s two shims.
15805    FinallyShim {
15806        callback: Option<Value>,
15807        fulfilled: bool,
15808        constructor: Value,
15809    },
15810    /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15811    ReturnValue(Value),
15812    /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15813    ThrowValue(Value),
15814    /// Settle a promise with a fixed outcome.
15815    SettlePromise {
15816        promise: Gc<JsObject>,
15817        value: Value,
15818        rejected: bool,
15819    },
15820    /// Continue an async generator after its `await` settled.
15821    GeneratorResume {
15822        generator: Gc<JsObject>,
15823        promise: Gc<JsObject>,
15824        kind: ResumeKind,
15825    },
15826    /// Read a module namespace's binding out of its cell.
15827    ModuleBinding(Gc<Cell>),
15828    /// Finish a completed async generator's `return(v)` once `v` has settled.
15829    CompletedReturn {
15830        generator: Gc<JsObject>,
15831        promise: Gc<JsObject>,
15832        rejected: bool,
15833    },
15834    /// Answer a pending async-generator method with `{value, done}`.
15835    YieldResult {
15836        generator: Gc<JsObject>,
15837        promise: Gc<JsObject>,
15838        done: bool,
15839    },
15840    /// One step of `AsyncDisposableStack.disposeAsync`.
15841    DisposeStep {
15842        remaining: Gc<JsObject>,
15843        promise: Gc<JsObject>,
15844        error: Value,
15845        rejected: bool,
15846        awaited: bool,
15847        needs_await: bool,
15848    },
15849}
15850
15851/// What a store does when the object refuses the write.
15852#[derive(Clone, Copy, PartialEq, Eq)]
15853pub enum DeleteFailure {
15854    /// Raise a `TypeError`, which is what strict mode and every built-in does.
15855    Throw,
15856    /// Ignore the write, which is what a sloppy-mode assignment does.
15857    Ignore,
15858}
15859
15860/// Whether `object` is a `Date` instance, by the class tag it carries.
15861///
15862/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15863/// builtins module depending on the interpreter's conversion order.
15864fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15865    interp
15866        .internal_get(object, "_class")
15867        .is_some_and(|value| value.to_js_string() == "Date")
15868}
15869
15870/// Which type `ToPrimitive` prefers when it converts an object.
15871#[derive(Clone, Copy, PartialEq, Eq)]
15872pub enum Hint {
15873    /// The default hint, which behaves like [`Hint::Number`].
15874    Default,
15875    /// `Number(obj)` and the arithmetic operators.
15876    Number,
15877    /// `String(obj)` and `ToPropertyKey`.
15878    String,
15879}
15880
15881/// Which table a binding slot indexes, for the messages that name it.
15882#[derive(Clone, Copy)]
15883enum VarSlot {
15884    Loc,
15885    Closure,
15886}
15887
15888/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15889fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15890    Ok(this)
15891}
15892
15893/// An internal iterator: the sequence plus a cursor.
15894pub(crate) struct Iterator {
15895    pub(crate) object: Value,
15896    pub(crate) next: Value,
15897}
15898
15899/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15900/// and plain `a` for a method.
15901///
15902/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
15903/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
15904/// reads `at get a (file:1:2)`.
15905/// The same prefixing, for a name that may hold an unpaired surrogate.
15906fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
15907    let prefix = match flags & 3 {
15908        1 => "get ",
15909        2 => "set ",
15910        _ => return key.clone(),
15911    };
15912    let mut units: Vec<u16> = prefix.encode_utf16().collect();
15913    units.extend_from_slice(&key.to_units());
15914    crate::value::Wtf8::from_units(&units)
15915}
15916
15917/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
15918///
15919/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
15920/// `Symbol()` — the two are different and test262 checks both.
15921fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
15922    let PropertyKey::Symbol(symbol) = key else {
15923        return crate::value::Wtf8::default();
15924    };
15925    match symbol.description() {
15926        Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
15927        None => crate::value::Wtf8::default(),
15928    }
15929}
15930
15931/// Define a method or accessor property, per the `define_method` flag byte.
15932///
15933/// The low two bits pick value/getter/setter and bit 2 marks the property
15934/// enumerable.
15935///
15936/// A getter and a setter arrive as two separate `define_method` instructions, and the
15937/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
15938/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
15939/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
15940/// `JS_DefineProperty`, which leaves the other half alone.
15941fn define_function_property(
15942    object: &Gc<JsObject>,
15943    key: &PropertyKey,
15944    function: Value,
15945    flags: u32,
15946) -> bool {
15947    let enumerable = flags & 4 != 0;
15948    let kind = flags & 3;
15949    let existing = object.own_property_key(key);
15950    let property = match kind {
15951        1 => Property {
15952            getter: Some(function),
15953            // The setter half, if this literal already defined one.
15954            setter: existing
15955                .filter(Property::is_accessor)
15956                .and_then(|p| p.setter),
15957            enumerable,
15958            configurable: true,
15959            ..Property::default()
15960        },
15961        2 => Property {
15962            getter: existing
15963                .filter(Property::is_accessor)
15964                .and_then(|p| p.getter),
15965            setter: Some(function),
15966            enumerable,
15967            configurable: true,
15968            ..Property::default()
15969        },
15970        _ => Property {
15971            value: Some(function),
15972            writable: true,
15973            enumerable,
15974            configurable: true,
15975            ..Property::default()
15976        },
15977    };
15978    object.create_data_property_key(key, property)
15979}
15980
15981// ---------------------------------------------------------------------------
15982// Operand decoding
15983// ---------------------------------------------------------------------------
15984
15985/// How `print` renders a value: the reference's `JS_PrintValue`.
15986///
15987/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
15988/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
15989/// The format is reproduced closely because the test suite compares output text:
15990///
15991/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
15992/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
15993/// * a cycle prints `[circular N]` with `N` the stack index of the object;
15994/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
15995///   end print as `<N empty item(s)>`;
15996/// * a string is quoted inside a container but raw at the top level, which is why
15997///   `print("x")` and `print(["x"])` differ.
15998pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
15999    // A string argument is printed raw: `js_print` converts it with `ToString`
16000    // instead of dumping it, and the quoting only appears inside a container.
16001    if let Value::String(text) = value {
16002        return text.to_string_lossy().into_owned();
16003    }
16004    let mut printer = Printer {
16005        interp,
16006        out: String::new(),
16007        stack: Vec::new(),
16008    };
16009    printer.value(value, 0);
16010    printer.out
16011}
16012
16013/// The internal class name an object carries, when it has one.
16014fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
16015    interp
16016        .internal_get(object, "_class")
16017        .map(|value| value.to_js_string())
16018}
16019
16020/// A string property, looked up the way `GetProperty` does: own first, then the
16021/// prototype chain. Needed because the print formatter holds the interpreter
16022/// immutably and so cannot run getters.
16023fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
16024    let mut current = Some(object.clone());
16025    // Bounded, because a prototype cycle would otherwise loop forever.
16026    for _ in 0..100 {
16027        let node = current?;
16028        if let Some(property) = node.own_property(name)
16029            && let Some(value) = property.value
16030        {
16031            return Some(value.to_js_string());
16032        }
16033        current = node.with(|data| data.proto.clone());
16034    }
16035    None
16036}
16037
16038/// The `JS_PrintValue` state: output, and the objects currently being printed.
16039struct Printer<'a, 'rt> {
16040    /// Kept for the class-name lookups that typed arrays and `Date` will need.
16041    #[allow(dead_code)]
16042    interp: &'a Interp<'rt>,
16043    out: String,
16044    stack: Vec<Gc<JsObject>>,
16045}
16046
16047impl Printer<'_, '_> {
16048    /// Depth past which a container is summarised by its class name.
16049    const MAX_DEPTH: usize = 2;
16050
16051    fn value(&mut self, value: &Value, level: usize) {
16052        match value {
16053            Value::Undefined
16054            | Value::Uninitialized
16055            | Value::Hole
16056            | Value::CatchOffset(_)
16057            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
16058            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
16059            // The printer writes a bigint the way the language spells one, so a dump is
16060            // unambiguous about which kind of number it is showing.
16061            Value::BigInt(big) => {
16062                self.out.push_str(&big.to_decimal_string());
16063                self.out.push('n');
16064            }
16065            Value::Null => self.out.push_str("null"),
16066            Value::Bool(true) => self.out.push_str("true"),
16067            Value::Bool(false) => self.out.push_str("false"),
16068            Value::Int(number) => self.out.push_str(&number.to_string()),
16069            Value::Float(number) => {
16070                self.out
16071                    .push_str(&crate::value::number_to_string_for_print(*number));
16072            }
16073            Value::String(text) => self.print_string(&text.to_string_lossy()),
16074            Value::Object(object) => self.object(object, level),
16075        }
16076    }
16077
16078    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
16079        // A cycle is reported rather than followed; the index is where the object
16080        // already sits in the print stack, which is what the reference shows.
16081        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
16082            self.out.push_str(&format!("[circular {index}]"));
16083            return;
16084        }
16085        if object.is_callable() {
16086            let name = object
16087                .own_property("name")
16088                .and_then(|property| property.value)
16089                .map(|value| value.to_js_string())
16090                .unwrap_or_default();
16091            if name.is_empty() {
16092                self.out.push_str("[Function (anonymous)]");
16093            } else {
16094                self.out.push_str(&format!("[Function {name}]"));
16095            }
16096            return;
16097        }
16098        if level >= Self::MAX_DEPTH {
16099            let class = if object.is_array() { "Array" } else { "Object" };
16100            self.out.push_str(&format!("[{class}]"));
16101            return;
16102        }
16103        // A `RegExp` prints as its own literal, `js_print_regexp`'s `/%s/%s`. Without this
16104        // it fell through to the plain-object form and `print(/x/)` answered `{  }` — no
16105        // properties, so nothing to show, and the value's identity lost.
16106        if let Some(data) = object.regexp() {
16107            let source = crate::builtins::regexp::escaped_source(&data.source);
16108            self.out.push('/');
16109            self.out.push_str(&source.to_string_lossy());
16110            self.out.push('/');
16111            self.out.push_str(&data.flags);
16112            return;
16113        }
16114        // `Date` and `Error` print as themselves rather than as bags of properties:
16115        // the ISO string, and `Name: message` followed by the trace.
16116        if let Some(class) = class_of(self.interp, object) {
16117            if class == "Date" {
16118                self.date(object);
16119                return;
16120            }
16121            if class == "Error" {
16122                self.error(object);
16123                return;
16124            }
16125        }
16126        self.stack.push(object.clone());
16127        if object.is_array() {
16128            self.array(object, level);
16129        } else {
16130            self.plain_object(object, level);
16131        }
16132        self.stack.pop();
16133    }
16134
16135    /// A Date prints as its ISO string; an invalid one falls through to the plain
16136    /// object form, the way the reference falls back when `toISOString` throws.
16137    fn date(&mut self, object: &Gc<JsObject>) {
16138        let value = self
16139            .interp
16140            .internal_get(object, "_date_value")
16141            .map(|value| value.to_number());
16142        match value.and_then(crate::builtins::date::iso_string) {
16143            Some(text) => self.out.push_str(&text),
16144            None => self.plain_object(object, 0),
16145        }
16146    }
16147
16148    /// `Name: message`, then the trace with its trailing newline removed.
16149    fn error(&mut self, object: &Gc<JsObject>) {
16150        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16151        self.out.push_str(&name);
16152        if let Some(message) = inherited(object, "message")
16153            && !message.is_empty()
16154        {
16155            self.out.push_str(": ");
16156            self.out.push_str(&message);
16157        }
16158        if let Some(stack) = inherited(object, "stack") {
16159            self.out.push('\n');
16160            self.out.push_str(stack.trim_end_matches('\n'));
16161        }
16162    }
16163
16164    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16165        let elements = object.array_elements().unwrap_or_default();
16166        self.out.push_str("[ ");
16167        // An interior hole means the array is "sparse": the reference prints those
16168        // as `index: value` pairs and says nothing about the holes themselves, while
16169        // a hole run at the end becomes a single `<N empty items>` note.
16170        let last_present = elements
16171            .iter()
16172            .rposition(|value| !matches!(value, Value::Hole));
16173        let has_interior_hole = match last_present {
16174            Some(last) => elements[..last]
16175                .iter()
16176                .any(|value| matches!(value, Value::Hole)),
16177            None => false,
16178        };
16179        let mut first = true;
16180        if has_interior_hole {
16181            let mut index = 0;
16182            while index < elements.len() {
16183                let value = &elements[index];
16184                if matches!(value, Value::Hole) {
16185                    index += 1;
16186                    continue;
16187                }
16188                if !first {
16189                    self.out.push_str(", ");
16190                }
16191                first = false;
16192                self.out.push_str(&format!("{index}: "));
16193                self.value(value, level + 1);
16194                index += 1;
16195            }
16196        } else {
16197            for (index, value) in elements.iter().enumerate() {
16198                if matches!(value, Value::Hole) {
16199                    continue;
16200                }
16201                if !first {
16202                    self.out.push_str(", ");
16203                }
16204                first = false;
16205                let _ = index;
16206                self.value(value, level + 1);
16207            }
16208            if let Some(last) = last_present {
16209                let trailing = elements.len() - last - 1;
16210                if trailing > 0 {
16211                    if !first {
16212                        self.out.push_str(", ");
16213                    }
16214                    self.out.push_str(&format!(
16215                        "<{trailing} empty item{}>",
16216                        if trailing > 1 { "s" } else { "" }
16217                    ));
16218                }
16219            } else if !elements.is_empty() {
16220                let count = elements.len();
16221                self.out.push_str(&format!(
16222                    "<{count} empty item{}>",
16223                    if count > 1 { "s" } else { "" }
16224                ));
16225            }
16226        }
16227        self.out.push_str(" ]");
16228    }
16229
16230    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16231        self.out.push_str("{ ");
16232        let mut first = true;
16233        for key in object.own_keys() {
16234            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16235                continue;
16236            };
16237            if !property.enumerable {
16238                continue;
16239            }
16240            if !first {
16241                self.out.push_str(", ");
16242            }
16243            first = false;
16244            self.out
16245                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16246                    &key.to_string_lossy(),
16247                )));
16248            self.out.push_str(": ");
16249            // An accessor has no value to dump; the reference names the half that
16250            // exists instead of calling it.
16251            if property.is_accessor() {
16252                let text = match (property.getter.is_some(), property.setter.is_some()) {
16253                    (true, true) => "[Getter/Setter]",
16254                    (false, true) => "[Setter]",
16255                    _ => "[Getter]",
16256                };
16257                self.out.push_str(text);
16258            } else {
16259                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16260            }
16261        }
16262        self.out.push_str(" }");
16263    }
16264
16265    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16266    fn print_string(&mut self, text: &str) {
16267        self.out.push('"');
16268        for character in text.chars() {
16269            match character {
16270                '"' => self.out.push_str("\\\""),
16271                '\\' => self.out.push_str("\\\\"),
16272                '\n' => self.out.push_str("\\n"),
16273                '\r' => self.out.push_str("\\r"),
16274                '\t' => self.out.push_str("\\t"),
16275                c if (c as u32) < 0x20 => {
16276                    self.out.push_str(&format!("\\u{:04x}", c as u32));
16277                }
16278                c => self.out.push(c),
16279            }
16280        }
16281        self.out.push('"');
16282    }
16283}
16284
16285/// How `print` renders a value.
16286///
16287/// `ToString`, except that negative zero keeps its sign — the reference's host
16288/// printer does that while `String(-0)` is `"0"`.
16289pub fn display(value: &Value) -> String {
16290    match value {
16291        Value::Float(number) => crate::value::number_to_string_for_print(*number),
16292        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16293            "undefined".to_string()
16294        }
16295        other => other.to_js_string(),
16296    }
16297}
16298
16299// ---------------------------------------------------------------------------
16300// Numeric operators
16301// ---------------------------------------------------------------------------
16302
16303/// `a + b` keeping the `Int` representation when it fits.
16304fn add_numbers(left: Value, right: Value) -> Value {
16305    match (&left, &right) {
16306        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16307            Some(sum) => Value::Int(sum),
16308            None => Value::Float(*a as f64 + *b as f64),
16309        },
16310        _ => Value::Float(left.to_number() + right.to_number()),
16311    }
16312}
16313
16314/// The arithmetic operators other than `+`, which needs string concatenation.
16315fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16316    use Opcode::*;
16317    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16318    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16319    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16320    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16321        return Ok(match op {
16322            And => Value::Int(x & y),
16323            Or => Value::Int(x | y),
16324            Xor => Value::Int(x ^ y),
16325            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16326            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16327            Shr => match (*x as u32) >> ((*y as u32) & 31) {
16328                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16329                shifted => Value::Float(shifted as f64),
16330            },
16331            Sub => match x.checked_sub(*y) {
16332                Some(value) => Value::Int(value),
16333                None => Value::Float(*x as f64 - *y as f64),
16334            },
16335            _ => return arithmetic_slow(op, left, right),
16336        });
16337    }
16338    arithmetic_slow(op, left, right)
16339}
16340
16341/// [`arithmetic`] for everything the integer fast path above does not take.
16342fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16343    use Opcode::*;
16344    let (a, b) = (left.to_number(), right.to_number());
16345    Ok(match op {
16346        Sub => match (&left, &right) {
16347            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16348                Some(value) => Value::Int(value),
16349                None => Value::Float(a - b),
16350            },
16351            _ => Value::Float(a - b),
16352        },
16353        Mul => Value::Float(a * b),
16354        Div => Value::Float(a / b),
16355        Mod => Value::Float(js_mod(a, b)),
16356        Pow => Value::Float(a.powf(b)),
16357        And => Value::Int(left.to_int32() & right.to_int32()),
16358        Or => Value::Int(left.to_int32() | right.to_int32()),
16359        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16360        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16361        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16362        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16363        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16364        // fits the small-integer representation stays an `Int`; the rest become a
16365        // float, which is how the reference keeps `n >>> 0` non-negative.
16366        Shr => {
16367            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16368            match i32::try_from(shifted) {
16369                Ok(value) => Value::Int(value),
16370                Err(_) => Value::Float(shifted as f64),
16371            }
16372        }
16373        _ => Value::Float(a),
16374    })
16375}
16376
16377/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16378///
16379/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16380/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16381/// slow path where the rules live.
16382fn is_number(value: &Value) -> bool {
16383    matches!(value, Value::Int(_) | Value::Float(_))
16384}
16385
16386/// The `Value::Bool` a comparison operator answers for `ordering`.
16387///
16388/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16389/// false for it, including `<=` and `>=`.
16390fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16391    use Opcode::*;
16392    let answer = match (op, ordering) {
16393        (_, None) => false,
16394        (Lt, Some(ordering)) => ordering.is_lt(),
16395        (Lte, Some(ordering)) => ordering.is_le(),
16396        (Gt, Some(ordering)) => ordering.is_gt(),
16397        (Gte, Some(ordering)) => ordering.is_ge(),
16398        _ => false,
16399    };
16400    Value::Bool(answer)
16401}
16402
16403/// `%`, which follows the sign of the dividend rather than Rust's.
16404fn js_mod(left: f64, right: f64) -> f64 {
16405    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16406        return f64::NAN;
16407    }
16408    if right.is_infinite() {
16409        return left;
16410    }
16411    let remainder = left % right;
16412    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16413    // the spec makes the sign match the dividend.
16414    if remainder == 0.0 {
16415        0.0f64.copysign(left)
16416    } else {
16417        remainder
16418    }
16419}
16420
16421fn negate(value: Value) -> Value {
16422    match value {
16423        Value::Int(0) => Value::Float(-0.0),
16424        Value::Int(i) => Value::Int(-i),
16425        other => Value::Float(-other.to_number()),
16426    }
16427}
16428
16429fn increment(value: Value) -> Value {
16430    match value {
16431        Value::Int(i) => match i.checked_add(1) {
16432            Some(next) => Value::Int(next),
16433            None => Value::Float(i as f64 + 1.0),
16434        },
16435        other => Value::Float(other.to_number() + 1.0),
16436    }
16437}
16438
16439fn decrement(value: Value) -> Value {
16440    match value {
16441        Value::Int(i) => match i.checked_sub(1) {
16442            Some(next) => Value::Int(next),
16443            None => Value::Float(i as f64 - 1.0),
16444        },
16445        other => Value::Float(other.to_number() - 1.0),
16446    }
16447}
16448
16449/// Compare a `BigInt` with an `f64` on their mathematical values.
16450///
16451/// Neither side is rounded to the other's precision: the number is split into its integer
16452/// part (compared as an exact bigint) and its fraction, which is what decides the answer
16453/// when the integer parts are equal. An infinite value is larger than every bigint.
16454fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
16455    use std::cmp::Ordering;
16456    if number.is_nan() {
16457        return None;
16458    }
16459    if number.is_infinite() {
16460        return Some(if number > 0.0 {
16461            Ordering::Less
16462        } else {
16463            Ordering::Greater
16464        });
16465    }
16466    // The comparison is **exact**, because rounding it is observable: an f64 is
16467    // `m * 2^e` with `m` a 53-bit integer, so scaling the bigint by the same power of two
16468    // turns this into an integer comparison at any width. Converting the *bigint* to f64
16469    // instead — which is what this used to do once the number was wider than `i128` —
16470    // rounds it to the nearest double, and `0xfffffffffffff7ff…n < Number.MAX_VALUE` is
16471    // decided by a difference of one bit at 2^971, which rounding erases
16472    // (`less-than/bigint-and-number-extremes`).
16473    // Both branches answer `big.cmp(number)`; which side gets scaled depends on the sign of
16474    // the exponent, because scaling the smaller one keeps the shift bounded by the f64's own
16475    // range (at most 1074 bits) instead of by the bigint's width.
16476    let (mantissa, exponent) = decompose_f64(number);
16477    let product = crate::bigint::BigInt::from_i64(mantissa);
16478    Some(if exponent >= 0 {
16479        // `number = mantissa * 2^exponent`, and that product is the exact f64 value.
16480        big.cmp(&product.shl(exponent as u64))
16481    } else {
16482        // `number = mantissa / 2^-exponent`; scale the *bigint* up instead so both sides stay
16483        // integers.
16484        big.shl((-exponent) as u64).cmp(&product)
16485    })
16486}
16487
16488/// `value` as `(mantissa, exponent)` with `value == mantissa * 2^exponent` exactly.
16489///
16490/// `mantissa` carries the sign and is the f64's significand with its implicit bit made
16491/// explicit, so `|mantissa| <= 2^53` and the `i64` conversion is exact. `value` must be
16492/// finite.
16493fn decompose_f64(value: f64) -> (i64, i32) {
16494    let bits = value.abs().to_bits();
16495    let raw_exponent = ((bits >> 52) & 0x7ff) as i32;
16496    let fraction = bits & ((1u64 << 52) - 1);
16497    // A subnormal has no implicit bit and an exponent of `1 - 1023`; a normal one carries a
16498    // leading 1 at bit 52, and the `-1075` folds in the bias and the 52 fraction bits.
16499    let (significand, exponent) = if raw_exponent == 0 {
16500        (fraction, -1074)
16501    } else {
16502        (fraction | (1u64 << 52), raw_exponent - 1075)
16503    };
16504    let significand = significand as i64;
16505    let mantissa = if value < 0.0 {
16506        -significand
16507    } else {
16508        significand
16509    };
16510    (mantissa, exponent)
16511}
16512
16513/// The UTF-16 code unit ordering of two strings, which is what `<` compares.
16514///
16515/// `JsString` caches its code units on first access, so the first `code_unit_at` builds the
16516/// cache and the rest are O(1) — no allocation here, and no decoding in the loop.
16517fn compare_code_units(
16518    a: &crate::value::JsString,
16519    b: &crate::value::JsString,
16520) -> std::cmp::Ordering {
16521    let (left, right) = (a.utf16_len(), b.utf16_len());
16522    for index in 0..left.min(right) {
16523        let (x, y) = (
16524            a.code_unit_at(index).unwrap_or(0),
16525            b.code_unit_at(index).unwrap_or(0),
16526        );
16527        if x != y {
16528            return x.cmp(&y);
16529        }
16530    }
16531    // A proper prefix sorts first, which is what the length comparison gives.
16532    left.cmp(&right)
16533}
16534
16535/// `StringToBigInt(argument)` (§7.1.14): the string read as an **integer** literal.
16536///
16537/// `undefined` — `None` here — for anything that is only a *number* literal: `"0."`,
16538/// `".0"`, `"0e0"` and `"Infinity"` all fail, which is why `1n > "0."` is `false` rather
16539/// than `true` (`greater-than/bigint-and-incomparable-string`). Leading zeros are outside
16540/// the grammar too (`"007"`), and so is whitespace between the sign and the digits.
16541///
16542/// The empty string *is* `0n`: §7.1.14 turns a whitespace-only literal into `0`.
16543fn string_to_bigint(text: &str) -> Option<crate::bigint::BigInt> {
16544    let trimmed = text.trim();
16545    let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
16546    let signed = body.len() != trimmed.len();
16547    // A radix prefix admits no sign, and the digits must follow immediately.
16548    let (radix, digits) = if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
16549        (16, rest)
16550    } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
16551        (8, rest)
16552    } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
16553        (2, rest)
16554    } else {
16555        (10, body)
16556    };
16557    if signed && radix != 10 && signed {
16558        // `StrNonDecimalIntegerLiteral` has no sign.
16559        return None;
16560    }
16561    if radix == 10 && digits.len() > 1 && digits.starts_with('0') {
16562        // `StrUnsignedDecimalLiteral : 0 | NonZeroDigit DecimalDigits?`.
16563        return None;
16564    }
16565    crate::bigint::BigInt::from_string(trimmed)
16566}
16567
16568/// `CanonicalNumericIndexString(argument)` (§7.1.21).
16569///
16570/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
16571/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
16572/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
16573/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
16574/// rather than treating it as `0`.
16575fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
16576    let PropertyKey::String(text) = key else {
16577        // A symbol is never an index.
16578        return None;
16579    };
16580    let text = text.to_string_lossy();
16581    if text == "-0" {
16582        return Some(-0.0);
16583    }
16584    let number: f64 = text.parse().ok()?;
16585    // The round-trip test *is* the definition: only the canonical spelling qualifies.
16586    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
16587    // `"0.10"` does not.
16588    let rendered = Value::Float(number).to_js_string();
16589    (rendered == text).then_some(number)
16590}
16591
16592/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
16593///
16594/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
16595/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
16596/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
16597/// numeric and invalid, which is why they stop the prototype chain instead of falling
16598/// through it.
16599///
16600/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
16601/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
16602/// `in`, `delete` and `defineProperty` separately to make sure it does not.
16603fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
16604    numeric.is_finite()
16605        && numeric.fract() == 0.0
16606        && !(numeric == 0.0 && numeric.is_sign_negative())
16607        && numeric >= 0.0
16608        && object
16609            .typed_array_length()
16610            .is_some_and(|length| (numeric as usize) < length)
16611}
16612
16613/// `ArrayCreate`'s length bound, `2**32 - 1`.
16614///
16615/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
16616/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
16617/// through — can enforce it without depending on a builtin module.
16618const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;