Skip to main content

quickjs/
interp.rs

1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25    Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26    NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27    lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34    /// A JavaScript exception carrying the thrown value.
35    Throw(Value),
36    /// The runtime ran out of memory.
37    OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45    /// Keep executing the current frame.
46    Continue,
47    /// The current frame returned this value.
48    Return(Value),
49    /// The frame parked at a suspension point, with the yielded value on its stack.
50    ///
51    /// Only a generator or an async function can produce this, and only its own frame —
52    /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53    /// detached and handed to the generator object, which is what lets it resume later
54    /// with its locals and operand stack intact.
55    Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61    /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62    /// without passing a value, because there is no `yield` expression to receive one.
63    Initial,
64    /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65    Yield,
66    /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67    /// `{value, done}` object from the inner iterator and is handed straight back.
68    YieldStar,
69    /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70    /// what was yielded is the plain value and still has to be awaited and wrapped —
71    /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72    /// made it pass a bare value through as if it were an iterator result, so
73    /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74    AsyncYieldStar,
75    /// `await expr`: the value is a promise the async machinery has to settle first.
76    Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84    /// The global object.
85    pub global: Gc<JsObject>,
86    /// `Object.prototype`.
87    pub object_proto: Gc<JsObject>,
88    /// `Function.prototype`, which is itself callable.
89    pub function_proto: Gc<JsObject>,
90    /// `Array.prototype`.
91    pub array_proto: Gc<JsObject>,
92    /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
93    pub array_constructor: Option<Gc<JsObject>>,
94    /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
95    pub promise_constructor: Option<Gc<JsObject>>,
96    /// Reference cells for globals declared by the script.
97    ///
98    /// A declared global is read with `get_var` (by name) but written with
99    /// `put_var_ref` (through the cell), so the cell is what makes a function
100    /// declaration and its uses agree on one binding.
101    pub globals: BTreeMap<String, Gc<Cell>>,
102    /// Names of the globals that came from a *declaration*, which are
103    /// non-configurable properties of the global object.
104    pub declared: Vec<String>,
105    /// Names among the lexical globals that are `const`.
106    ///
107    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
108    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
109    /// path does not carry, so a store through it would look like a plain `let`. The
110    /// realm records it once, at declaration, and answers for every reader.
111    pub lexical_consts: BTreeSet<String>,
112    /// The error constructors by class name, so a runtime error can throw a real
113    /// `TypeError` instance rather than a look-alike object.
114    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
115    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
116    pub string_proto: Option<Gc<JsObject>>,
117    /// `Number.prototype`.
118    pub number_proto: Option<Gc<JsObject>>,
119    /// `Boolean.prototype`.
120    pub boolean_proto: Option<Gc<JsObject>>,
121    /// `BigInt.prototype`.
122    pub bigint_proto: Option<Gc<JsObject>>,
123    /// `Error.prototype`, the prototype of every error instance.
124    pub error_proto: Gc<JsObject>,
125    /// `Date.prototype`, so the constructor can build an instance in the
126    /// function-call form (`Date()` returns a string) without going through `new`.
127    pub date_proto: Gc<JsObject>,
128    /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
129    ///
130    /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
131    /// whole `ThrowTypeError/` directory finds it through
132    /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
133    /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
134    /// Creating a fresh one per property would make
135    /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
136    /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
137    pub throw_type_error: Option<Gc<JsObject>>,
138    /// `%GeneratorPrototype%`, the prototype of every generator object.
139    pub generator_proto: Gc<JsObject>,
140    /// `Promise.prototype`, the prototype of every promise.
141    pub promise_proto: Option<Gc<JsObject>>,
142    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
143    pub async_generator_proto: Option<Gc<JsObject>>,
144    /// `Symbol.prototype`.
145    pub symbol_proto: Option<Gc<JsObject>>,
146    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
147    /// `_date_value`.
148    ///
149    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
150    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
151    /// language does not have and `new Error()` listed `_class` beside `message` and
152    /// `stack` — and a caller that copies every own property (which
153    /// `Object.create(null, props)` effectively does) tried to write an internal name and
154    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
155    /// and `JSON.stringify`, while remaining an ordinary traced property.
156    ///
157    /// `RefCell` because interning is memoisation rather than observable state: filling the
158    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
159    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
160    /// built while reporting a failure must not require an exclusive borrow.
161    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
162
163    /// The `Symbol.for` registry: `key -> symbol`.
164    ///
165    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
166    /// symbol every time within one script while a fresh realm starts empty.
167    pub symbol_registry: BTreeMap<String, Value>,
168    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
169    pub regexp_proto: Option<Gc<JsObject>>,
170    /// The `RegExp` constructor.
171    pub regexp_ctor: Option<Gc<JsObject>>,
172    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
173    ///
174    /// The prototype rather than the constructor on purpose: a script that replaces
175    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
176    /// error wrapping, which the `using` test suite checks explicitly.
177    pub suppressed_error_proto: Option<Gc<JsObject>>,
178    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
179    pub disposable_stack_proto: Option<Gc<JsObject>>,
180    /// `Map.prototype`.
181    pub map_proto: Option<Gc<JsObject>>,
182    /// `Set.prototype`.
183    pub set_proto: Option<Gc<JsObject>>,
184    /// Every live `FinalizationRegistry`, held weakly.
185    ///
186    /// The cleanup callback has to run from a *safe point* — a place where script is not
187    /// already executing and no engine borrow is held — and the collector cannot enumerate
188    /// heap objects by type. Registering each registry here gives the drain a list to walk.
189    ///
190    /// The handles are weak on purpose: a registry the script dropped must be collectable,
191    /// and it must not be resurrected merely because the drain knew about it. Entries whose
192    /// target has expired are swept out as the drain walks, so the vector does not grow
193    /// without bound in a program that creates many short-lived registries.
194    pub finalization_registries: Vec<WeakGc<JsObject>>,
195    /// `ArrayBuffer.prototype`.
196    pub array_buffer_proto: Option<Gc<JsObject>>,
197    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
198    pub typed_array_proto: Option<Gc<JsObject>>,
199    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
200    ///
201    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
202    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
203    /// `"Object"` and `r instanceof Int32Array` is false.
204    pub typed_array_protos: Vec<Gc<JsObject>>,
205    /// `DataView.prototype`.
206    pub data_view_proto: Option<Gc<JsObject>>,
207    /// The `AsyncDisposableStack` prototype.
208    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
209    /// `Iterator.prototype`.
210    pub iterator_proto: Option<Gc<JsObject>>,
211    /// The `Iterator` constructor itself.
212    ///
213    /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
214    /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
215    /// place it can live is the realm.
216    pub iterator_ctor: Option<Gc<JsObject>>,
217    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
218    ///
219    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
220    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
221    /// `[object Iterator Helper]`).
222    pub iterator_helper_proto: Option<Gc<JsObject>>,
223    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
224    /// that was not already an `Iterator`.
225    ///
226    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
227    /// untouched and does *not* override `@@toStringTag`, so
228    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
229    pub iterator_wrap_proto: Option<Gc<JsObject>>,
230    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
231    pub generator_function_proto: Option<Gc<JsObject>>,
232    /// `%AsyncFunction.prototype%`.
233    pub async_function_proto: Option<Gc<JsObject>>,
234    /// `%AsyncGeneratorFunction.prototype%`.
235    pub async_generator_function_proto: Option<Gc<JsObject>>,
236    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
237    ///
238    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
239    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
240    /// prototype per iterator made every array iterator's prototype distinct.
241    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
242    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
243    ///
244    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
245    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
246    /// both faster and impossible to break from a script.
247    well_known_symbols: WellKnownSymbols,
248    /// The classes the host registered, and the prototype each one hands its instances.
249    pub host_classes: HostClasses,
250}
251
252/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
253///
254/// One per realm, because a class id is only meaningful within the runtime that handed it
255/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
256/// a host class cannot collide.
257pub struct HostClasses {
258    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
259    /// `JS_GetOpaque(val, 0)` has to match nothing.
260    next_id: u32,
261    /// What each registered class does.
262    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
263    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
264    ///
265    /// A strong reference, so the prototype a host installed outlives every script
266    /// reference to it — which is what `JS_SetClassProto` promises.
267    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
268}
269
270impl HostClasses {
271    fn new() -> HostClasses {
272        HostClasses {
273            next_id: 1,
274            defs: std::collections::BTreeMap::new(),
275            protos: std::collections::BTreeMap::new(),
276        }
277    }
278
279    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
280    pub fn register(&mut self, def: ClassDef) -> ClassId {
281        let id = ClassId::from_raw(self.next_id);
282        self.next_id += 1;
283        self.defs.insert(id, std::rc::Rc::new(def));
284        id
285    }
286
287    /// Register `def` under an id the caller already has (`JS_NewClass`).
288    ///
289    /// The C API splits "get an id" from "register a class" because a module may be
290    /// initialised lazily; registering twice under one id replaces the definition, and an
291    /// object created under the old one keeps the old behaviour, since it carries its own
292    /// reference.
293    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
294        if !id.is_valid() {
295            return false;
296        }
297        // Keep the counter past any id handed out explicitly, so a later `register` cannot
298        // reuse one.
299        self.next_id = self.next_id.max(id.get() + 1);
300        self.defs.insert(id, std::rc::Rc::new(def));
301        true
302    }
303
304    /// What `id` was registered with.
305    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
306        self.defs.get(&id).cloned()
307    }
308
309    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
310    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
311        self.protos.insert(id, proto);
312    }
313
314    /// The prototype installed for `id`, if the host installed one.
315    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
316        self.protos.get(&id).cloned()
317    }
318
319    /// How many classes the host registered.
320    pub fn len(&self) -> usize {
321        self.defs.len()
322    }
323
324    /// Whether no class has been registered.
325    pub fn is_empty(&self) -> bool {
326        self.defs.is_empty()
327    }
328}
329
330impl Default for HostClasses {
331    fn default() -> HostClasses {
332        HostClasses::new()
333    }
334}
335
336/// One binding of the frame that called `eval`, so the eval'd code can read and
337/// write it by name.
338struct EvalBinding {
339    /// The name it was declared with.
340    name: String,
341    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
342    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
343    /// a function that declares `a` must find that `a`.
344    frame: usize,
345    /// Which table of that frame it lives in.
346    slot: EvalSlot,
347    /// The slot index within that table.
348    index: usize,
349}
350
351/// Which table of a frame an [`EvalBinding`] indexes.
352#[derive(Clone, Copy)]
353enum EvalSlot {
354    Arg,
355    Local,
356}
357
358/// One activation record.
359struct Frame {
360    /// The bytecode being run.
361    code: Gc<CompiledCode>,
362    /// The cells this closure captured.
363    env: Gc<ClosureEnv>,
364    /// The `this` binding.
365    this: Value,
366    /// Argument slots, sized to the declared parameter count.
367    args: Vec<Value>,
368    /// How many values the caller actually passed, which is what `arguments.length`
369    /// reports and what `...rest` slices from.
370    passed_count: usize,
371    /// The passed values, **only when they do not fit in [`Self::args`]**.
372    ///
373    /// `args` is sized to the declared parameters, so a call that passes no more than
374    /// that already holds every passed value in its first `passed_count` slots — copying
375    /// them here as well was two writes and a buffer per call, on the hottest path in
376    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
377    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
378    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
379    /// its own copy.
380    ///
381    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
382    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
383    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
384    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
385    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
386    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
387    #[allow(clippy::box_collection)]
388    passed_overflow: Option<Box<Vec<Value>>>,
389    /// Local slots.
390    locals: Vec<Value>,
391    /// Reference cells for this frame's own captured bindings.
392    cells: Vec<Gc<Cell>>,
393    /// The operand stack.
394    stack: Vec<Value>,
395    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
396    local_vars: Option<Gc<LocalVars>>,
397
398    /// Index of the next instruction, not a byte offset.
399    ///
400    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
401    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
402    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
403    /// `Frame`, and `frames.push` copies the whole struct on every call.
404    pc: usize,
405    /// Byte offset of the instruction being executed, which is what a stack trace
406    /// reports. `pc` has already moved past it by the time an instruction runs.
407    ///
408    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
409    at: usize,
410    /// The callee, so a native builtin can tell which constructor it is.
411    callee: Value,
412    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
413    new_target: Value,
414    /// What this frame costs against [`Interp::stack_limit`], in bytes.
415    ///
416    /// Cached rather than recomputed because it is charged on every call and a call is the
417    /// hottest thing in the interpreter.
418    cost: usize,
419    /// [`Interp::stack_used`] before this frame was pushed.
420    ///
421    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
422    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
423    /// leave the counter wrong. There are eight places that drop frames; one subtraction
424    /// forgotten in any of them would leak budget until the depth limit moved.
425    stack_base: usize,
426    /// Whether this frame's body ended in a `tail_call`.
427    ///
428    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
429    /// with its own frame just like `call` does and only skips storing the result
430    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
431    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
432    /// pushed as usual, and this marker makes its return value the *caller's* return
433    /// value without running the instructions after the call.
434    tail: bool,
435}
436
437impl Frame {
438    /// Read a local slot, taking the frame as `self`.
439    ///
440    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
441    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
442    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
443    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
444    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
445    #[inline]
446    fn read_loc(&self, slot: usize) -> Value {
447        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
448        if cell == -1 {
449            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
450        }
451        match self.cells.get(cell as usize) {
452            Some(cell) => cell.get(),
453            None => Value::Undefined,
454        }
455    }
456
457    /// [`Self::read_loc`] for an argument slot.
458    #[inline]
459    fn read_arg(&self, slot: usize) -> Value {
460        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
461        if cell == -1 {
462            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
463        }
464        match self.cells.get(cell as usize) {
465            Some(cell) => cell.get(),
466            None => Value::Undefined,
467        }
468    }
469
470    /// The values the caller actually passed, which is what `arguments` exposes.
471    ///
472    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
473    fn passed(&self) -> &[Value] {
474        match &self.passed_overflow {
475            Some(values) => values,
476            None => &self.args[..self.passed_count],
477        }
478    }
479
480    /// The decoded instructions of the function this frame runs.
481    ///
482    /// A method rather than `frame.code.insns` at the call site so that the borrow is
483    /// obviously of the frame — the dispatch loop holds one across a `get`.
484    fn insns(&self) -> &[crate::insn::Insn] {
485        &self.code.insns
486    }
487}
488
489impl js_gc::Trace for Frame {
490    fn trace(&self, tracer: &mut js_gc::Tracer) {
491        self.code.trace(tracer);
492        self.env.trace(tracer);
493        self.this.trace(tracer);
494        for value in &self.args {
495            value.trace(tracer);
496        }
497        for value in self.passed() {
498            value.trace(tracer);
499        }
500        for value in &self.locals {
501            value.trace(tracer);
502        }
503        for cell in &self.cells {
504            cell.trace(tracer);
505        }
506        if let Some(local_vars) = &self.local_vars {
507            tracer.visit(local_vars);
508        }
509        for value in &self.stack {
510            value.trace(tracer);
511        }
512        self.callee.trace(tracer);
513        self.new_target.trace(tracer);
514    }
515}
516
517/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
518/// emitted `if_false` treats as "keep going".
519/// How many finished frames' value buffers are kept for reuse.
520const RECYCLE_SLOTS: usize = 8;
521
522/// The largest buffer worth keeping. See [`Interp::free_values`].
523const RECYCLE_MAX_CAPACITY: usize = 4096;
524
525const RESUME_NEXT: i32 = 0;
526/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
527/// generator fall into its `return_async`.
528const RESUME_RETURN: i32 = 1;
529/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
530/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
531/// must forward the exception into the inner iterator rather than finish.
532const RESUME_THROW: i32 = 2;
533
534/// One microtask.
535///
536/// The queue holds *data* rather than closures because its contents are GC values: a
537/// closure would be invisible to the collector, and a pending reaction is exactly the
538/// kind of thing that must keep its handlers and its promise alive.
539pub enum Job {
540    /// A `then` reaction about to run.
541    Reaction {
542        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
543        handler: Option<Value>,
544        /// The value or reason to call it with.
545        argument: Value,
546        /// Whether the source promise rejected, which decides the pass-through kind.
547        rejected: bool,
548        /// The promise the answer settles.
549        promise: Gc<JsObject>,
550    },
551    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
552    Thenable {
553        /// The `then` that was found on the value.
554        then: Value,
555        /// The thenable itself, which becomes `then`'s `this`.
556        value: Value,
557        /// The promise being resolved.
558        promise: Gc<JsObject>,
559    },
560    /// A pending `import(specifier)`.
561    Import {
562        /// The specifier, already converted to a string.
563        specifier: String,
564        /// The module that asked, which the specifier resolves against.
565        referrer: String,
566        /// The promise `import()` handed back.
567        promise: Gc<JsObject>,
568    },
569    /// An async generator resuming after the value it awaited settled.
570    GeneratorResume {
571        /// The async generator to continue.
572        generator: Gc<JsObject>,
573        /// The promise the pending method returned.
574        promise: Gc<JsObject>,
575        /// Whether this delivers the value or raises the reason.
576        kind: ResumeKind,
577        /// The settled value, or the rejection reason.
578        value: Value,
579    },
580    /// An async function resuming after the value it awaited settled.
581    Resume {
582        /// The body, parked in a coroutine.
583        coroutine: Gc<JsObject>,
584        /// The promise the async function handed its caller.
585        promise: Gc<JsObject>,
586        /// Whether this resumption delivers a value or raises one.
587        kind: ResumeKind,
588        /// The settled value, or the rejection reason.
589        value: Value,
590    },
591}
592
593/// One macro-task: work the event loop owes the script but has not run yet.
594///
595/// The microtask queue ([`Job`]) is different: those run before the host regains control.
596/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
597/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
598/// logic: the engine decides *what* is due, the host decides *how to wait*.
599///
600/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
601/// reference counting even though nothing else references it — the same rule the `HostFn`
602/// documentation states from the other side (a host closure must not hold a `Gc`, so the
603/// `Gc` lives here instead).
604pub enum Task {
605    /// A `setTimeout` that is due at `due_at`.
606    ///
607    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
608    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
609    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
610    /// would give this engine a timer the reference cannot produce, with nothing to
611    /// compare it against.
612    Timer {
613        /// The id `setTimeout` returned, for `clearTimeout`.
614        id: i32,
615        /// What to call when it fires.
616        callback: Value,
617        /// When it becomes runnable, as a monotonic instant.
618        due_at: std::time::Instant,
619    },
620}
621
622/// A descriptor the host has to poll, and which directions have a handler.
623///
624/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
625/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
626/// blocks on it, and the host reports back through [`Interp::fire_fd`].
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub struct FdInterest {
629    /// The descriptor to watch.
630    pub fd: i32,
631    /// Whether `os.setReadHandler` registered a callback.
632    pub read: bool,
633    /// Whether `os.setWriteHandler` registered a callback.
634    pub write: bool,
635}
636
637/// The callbacks registered for one descriptor, per direction.
638#[derive(Default)]
639pub(crate) struct FdHandlers {
640    /// `os.setReadHandler`'s callback.
641    pub read: Option<Value>,
642    /// `os.setWriteHandler`'s callback.
643    pub write: Option<Value>,
644}
645
646/// The file name `eval` reports, which the reference does not inherit from the caller.
647///
648/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
649/// reference and the names show up in stack traces.
650/// The description of the private symbol a class brand is made from.
651///
652/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
653/// place no script can reach, since no expression can name a private symbol.
654const BRAND_DESCRIPTION: &str = "brand";
655
656/// One validated property lookup.
657///
658/// Covers both own-property hits and prototype hits. The second kind was deliberately left
659/// uncached at first ("a prototype hit depends on more than the object and the name"), and
660/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
661/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
662/// names on every iteration (measured: 100 ns per call over an empty loop).
663pub struct FieldCache {
664    /// The name, so two different properties of one object do not collide.
665    key: PropertyKey,
666    /// Where the value was found, relative to the chain below.
667    index: usize,
668    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
669    level: u8,
670    /// The receiver and every prototype down to (and including) the level that answered,
671    /// each with the length of its property table at the time.
672    ///
673    /// That length is the whole guard, and it is sufficient for the ways the answer can
674    /// change without a lookup: adding or deleting any property moves it, and a
675    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
676    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
677    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
678    /// the one that was cached.
679    ///
680    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
681    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
682    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
683}
684
685/// How many links of a prototype chain a [`FieldCache`] remembers.
686///
687/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
688/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
689/// at three.
690const MAX_CACHED_CHAIN: usize = 3;
691
692/// A remembered global-variable lookup.
693///
694/// A `var` global is an ordinary property of the global object, so reading one walks the
695/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
696/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
697/// fixed by the bytecode, and the slot in the object's table only changes if the global
698/// object is mutated, which the index-and-name check below catches.
699pub struct GlobalCache {
700    /// The global object the lookup was resolved on, weakly.
701    object: js_gc::WeakGc<JsObject>,
702    /// Index of the data property in the global object's table.
703    index: usize,
704}
705
706/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
707const GLOBAL_CACHE_SLOTS: usize = 1024;
708
709/// How many property lookups are remembered.
710///
711/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
712/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
713/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
714/// lookup itself. Making it bigger stops helping: the working set of a real program's
715/// property sites is bounded by its code size.
716const FIELD_CACHE_SLOTS: usize = 4096;
717
718/// How much the heap may grow past the last `out of memory` before saying it again.
719///
720/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
721/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
722/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
723/// because it looks like it works. The reference gets this for free: it fails inside
724/// `js_malloc`, and its printing path happens not to allocate.
725///
726/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
727/// allocating is stopped within a rounding error of the limit) and far above what a
728/// handler needs.
729const OOM_HYSTERESIS: usize = 64 * 1024;
730
731/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
732pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
733
734/// How many instructions run between polls of [`Interp::interrupt`].
735///
736/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
737/// order of magnitude on both implementations — which is what lets a C driver compare its
738/// output byte for byte (see `scripts/m15-capi.sh --embed`).
739pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
740
741/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
742///
743/// Chosen so that the byte budget is what actually decides for every ordinary
744/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
745/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
746/// millions of frames.
747pub const MAX_FRAMES: usize = 200_000;
748
749const EVAL_FILE: &str = "<input>";
750
751/// The file name `std.evalScript` reports.
752const EVAL_SCRIPT_FILE: &str = "<evalScript>";
753
754/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
755///
756/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
757/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
758fn clamp_delay(delay_ms: f64) -> std::time::Duration {
759    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
760    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
761    // non-positive delay mean "due now".
762    if delay_ms.is_nan() || delay_ms <= 0.0 {
763        return std::time::Duration::ZERO;
764    }
765    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
766}
767
768impl js_gc::Trace for Task {
769    fn trace(&self, tracer: &mut js_gc::Tracer) {
770        let Task::Timer { callback, .. } = self;
771        callback.trace(tracer);
772    }
773}
774
775/// What one turn of the event loop did, so the caller cannot spin by accident.
776///
777/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
778/// core until the timer is due. Naming the three cases makes the wait explicit.
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub enum Turn {
781    /// Something ran. Call again immediately — there may be more ready work.
782    Ran,
783    /// Nothing is runnable, but descriptors are registered: the host must poll
784    /// [`Interp::pending_fds`] for at most this long, then report readiness with
785    /// [`Interp::fire_fd`].
786    ///
787    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
788    /// the failure this project treats as worst — a handler that silently never fires —
789    /// so the two cannot be confused by accident.
790    Poll(std::time::Duration),
791    /// Nothing is runnable yet, but something is pending. Block at most this long, then
792    /// call again.
793    Wait(std::time::Duration),
794    /// Nothing is pending at all: the loop is done.
795    Done,
796}
797
798impl js_gc::Trace for Job {
799    fn trace(&self, tracer: &mut js_gc::Tracer) {
800        match self {
801            Job::Reaction {
802                handler,
803                argument,
804                promise,
805                ..
806            } => {
807                if let Some(handler) = handler {
808                    handler.trace(tracer);
809                }
810                argument.trace(tracer);
811                tracer.visit(promise);
812            }
813            Job::Thenable {
814                then,
815                value,
816                promise,
817            } => {
818                then.trace(tracer);
819                value.trace(tracer);
820                tracer.visit(promise);
821            }
822            Job::Resume {
823                coroutine,
824                promise,
825                value,
826                ..
827            } => {
828                tracer.visit(coroutine);
829                tracer.visit(promise);
830                value.trace(tracer);
831            }
832            Job::Import { promise, .. } => tracer.visit(promise),
833            Job::GeneratorResume {
834                generator,
835                promise,
836                value,
837                ..
838            } => {
839                tracer.visit(generator);
840                tracer.visit(promise);
841                value.trace(tracer);
842            }
843        }
844    }
845}
846
847/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
848#[derive(Debug, Clone, Copy, PartialEq, Eq)]
849pub enum ResumeKind {
850    /// The generator was just created and is being run to its first suspension.
851    Start,
852    /// `next(v)`.
853    Next,
854    /// `return(v)`.
855    Return,
856    /// `throw(e)`.
857    Throw,
858}
859
860/// A generator object's saved execution.
861///
862/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
863/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
864/// separately allocated buffers.
865pub struct GeneratorState {
866    /// The detached frame, or `None` once the generator has finished or while it runs.
867    frame: Option<Frame>,
868    /// How far it got.
869    phase: GeneratorPhase,
870    /// Whether the last suspension was an `await` rather than a `yield`.
871    ///
872    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
873    /// value and a magic number, because the emitted code branches on which method
874    /// resumed it, while an `await` simply continues with its value. Getting this wrong
875    /// leaves an extra value on the operand stack that the next instruction then
876    /// consumes — a wrong answer rather than a crash.
877    parked_on_await: bool,
878    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
879    ///
880    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
881    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
882    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
883    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
884    /// delegating. Tracking it as part of the phase, the way the reference splits
885    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
886    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
887    /// exception and never reached `xs.throw`.
888    parked_on_yield_star: bool,
889    /// Pending `next`/`return`/`throw` calls, oldest first.
890    ///
891    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
892    /// called back to back must answer in that order, with the second call's value
893    /// arriving at the *second* `yield`. Running each call straight into the body — which
894    /// is what this engine did before — delivered the last queued value to whichever
895    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
896    /// `a === b ===` the final argument.
897    ///
898    /// The front entry is the one being served; it stays there (with `async_busy` set)
899    /// until its promise settles, because an `await` inside the body is a suspension of
900    /// the *driver*, not the end of the request.
901    requests: std::collections::VecDeque<AsyncRequest>,
902    /// Whether the front request is in flight.
903    async_busy: bool,
904}
905
906/// How one async-generator request ended.
907enum AsyncOutcome {
908    /// The method answered this `{value, done}`.
909    Value(Value),
910    /// The body threw.
911    Error(Value),
912}
913
914/// One queued `next`/`return`/`throw` on an async generator: the reference's
915/// `JSAsyncGeneratorRequest`.
916pub struct AsyncRequest {
917    /// Which method was called.
918    kind: ResumeKind,
919    /// Its argument.
920    value: Value,
921    /// The promise the method answered.
922    promise: Gc<JsObject>,
923}
924
925/// Which of §27.5.3.3's states a generator is in.
926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
927enum GeneratorPhase {
928    /// Created, `initial_yield` reached, body not entered.
929    SuspendedStart,
930    /// Parked at a `yield`.
931    SuspendedYield,
932    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
933    Executing,
934    /// Finished; the frame is gone.
935    Completed,
936}
937
938impl js_gc::Trace for GeneratorState {
939    fn trace(&self, tracer: &mut js_gc::Tracer) {
940        if let Some(frame) = &self.frame {
941            frame.trace(tracer);
942        }
943        for request in &self.requests {
944            request.value.trace(tracer);
945            tracer.visit(&request.promise);
946        }
947    }
948}
949
950/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
951/// them in.
952///
953/// Each is a field rather than a map entry because the runtime reads them on hot paths
954/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
955/// failure — reaching a default here means the builtin did not install, and every
956/// accessor panics rather than silently answering `undefined`.
957///
958/// [`builtins::symbol`]: crate::builtins::symbol
959#[derive(Default)]
960pub struct WellKnownSymbols {
961    /// The symbol values, positionally. Empty until `Symbol` installs.
962    symbols: Vec<Value>,
963}
964
965/// Which well-known symbol a caller wants.
966///
967/// A typed accessor beats passing a name around: a typo is a compile error rather than
968/// an `undefined` key that quietly matches nothing.
969#[derive(Debug, Clone, Copy, PartialEq, Eq)]
970pub enum WellKnown {
971    /// `Symbol.toPrimitive`.
972    ToPrimitive,
973    /// `Symbol.iterator`.
974    Iterator,
975    /// `Symbol.match`.
976    Match,
977    /// `Symbol.matchAll`.
978    MatchAll,
979    /// `Symbol.replace`.
980    Replace,
981    /// `Symbol.search`.
982    Search,
983    /// `Symbol.split`.
984    Split,
985    /// `Symbol.toStringTag`.
986    ToStringTag,
987    /// `Symbol.isConcatSpreadable`.
988    IsConcatSpreadable,
989    /// `Symbol.hasInstance`.
990    HasInstance,
991    /// `Symbol.species`.
992    Species,
993    /// `Symbol.unscopables`.
994    Unscopables,
995    /// `Symbol.asyncIterator`.
996    AsyncIterator,
997    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
998    Disposable,
999    /// `Symbol.asyncDispose` — the awaited form.
1000    AsyncDisposable,
1001}
1002
1003impl WellKnown {
1004    /// The index `Symbol`'s installer creates this symbol at.
1005    fn index(self) -> usize {
1006        match self {
1007            WellKnown::ToPrimitive => 0,
1008            WellKnown::Iterator => 1,
1009            WellKnown::Match => 2,
1010            WellKnown::MatchAll => 3,
1011            WellKnown::Replace => 4,
1012            WellKnown::Search => 5,
1013            WellKnown::Split => 6,
1014            WellKnown::ToStringTag => 7,
1015            WellKnown::IsConcatSpreadable => 8,
1016            WellKnown::HasInstance => 9,
1017            WellKnown::Species => 10,
1018            WellKnown::Unscopables => 11,
1019            WellKnown::AsyncIterator => 12,
1020            WellKnown::Disposable => 13,
1021            WellKnown::AsyncDisposable => 14,
1022        }
1023    }
1024}
1025
1026impl Realm {
1027    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1028    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1029        self.well_known_symbols.symbols = symbols;
1030    }
1031
1032    /// A well-known symbol.
1033    pub fn well_known(&self, which: WellKnown) -> Value {
1034        self.well_known_symbols
1035            .symbols
1036            .get(which.index())
1037            .cloned()
1038            .unwrap_or(Value::Undefined)
1039    }
1040
1041    /// The well-known symbol as a property key.
1042    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1043        match self.well_known(which) {
1044            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1045            // Unreachable once `Symbol` has installed; an empty string key matches
1046            // nothing, which degrades to "the object has no such method".
1047            _ => PropertyKey::from(String::new()),
1048        }
1049    }
1050}
1051
1052/// The interpreter: a realm plus a frame stack.
1053pub struct Interp<'a> {
1054    /// The heap everything is allocated on.
1055    pub heap: &'a Heap,
1056    /// The realm.
1057    pub realm: Realm,
1058    /// Active frames, outermost first.
1059    frames: Vec<Frame>,
1060    /// Value buffers from frames that have finished, reused by the next call.
1061    ///
1062    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1063    /// the locals and the operand stack — and free all four on return. `call:recursion`
1064    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1065    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1066    ///
1067    /// Bounded in both directions: a few buffers per kind, and none larger than
1068    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1069    /// and keeping its buffer would pin that memory for the rest of the run.
1070    free_values: Vec<Vec<Value>>,
1071    /// A strict-mode `eval`'s own variable scope, while its script runs.
1072    ///
1073    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1074    /// become a global. Name lookups still fall through to the realm, which is why
1075    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1076    eval_scope: Option<BTreeMap<String, Value>>,
1077    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1078    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1079    eval_depth: usize,
1080    /// The calling frame's own bindings, which the running `eval` can read and write.
1081    ///
1082    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1083    /// come from the frame, and a write is applied back to the frame (or to the cell
1084    /// the frame captured) when the eval finishes. That is what makes
1085    /// `f("a = 3")` visible to the caller as `a === 3`.
1086    eval_bindings: Vec<EvalBinding>,
1087    /// The calling frame's `arguments`, while an `eval` runs.
1088    ///
1089    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1090    /// own yet still has to see the caller's `arguments`.
1091    eval_arguments: Option<Value>,
1092    /// The `with` objects live at the moment the running `eval` started, innermost first.
1093    ///
1094    /// `None` outside an eval, which is what keeps a finished block's object from
1095    /// shadowing ordinary bytecode reads.
1096    eval_with: Option<Vec<Gc<JsObject>>>,
1097    /// The bindings the running direct `eval` makes visible, as name → cell.
1098    ///
1099    /// Set for the duration of an eval and then restored, but every closure created
1100    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1101    /// `eval("f = () => i")` work after the eval has returned.
1102    active_eval_scope: Option<Gc<EvalScope>>,
1103    /// The frame that called the direct `eval` currently running, if any.
1104    ///
1105    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1106    /// on the global object, which is what keeps
1107    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1108    /// gives each call its own `x`.
1109    eval_caller: Option<Option<usize>>,
1110    /// The caller's `new.target`, while an `eval` runs.
1111    ///
1112    /// The eval'd code is a script with no constructor of its own, so it inherits the
1113    /// one the enclosing function was called with.
1114    eval_new_target: Option<Value>,
1115    /// `new.target` for the frame about to be pushed.
1116    ///
1117    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1118    /// value reaches the frame without threading a parameter through every call site.
1119    pending_new_target: Option<Value>,
1120    /// Names of the native functions currently executing, outermost first.
1121    ///
1122    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1123    /// trace still names it with `(native)` instead of a position, so the names are
1124    /// tracked separately and stitched into [`Interp::stack_trace`].
1125    ///
1126    /// The third field is how many bytecode frames were live when the native was entered,
1127    /// which is what places it *among* them rather than before all of them. Native
1128    /// functions used to be emitted up front on the grounds that they never re-enter
1129    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1130    /// The natives currently running, innermost last: the function object and the
1131    /// depth it was entered at.
1132    ///
1133    /// The *name* is deliberately not stored. It used to be, read with
1134    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1135    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1136    /// benchmark. A stack trace is built rarely; it can read the name then.
1137    native_frames: Vec<(Gc<JsObject>, usize)>,
1138    /// The native function currently executing, for the ones that have to know *which*
1139    /// function they are — a typed-array constructor reads its element type off itself.
1140    ///
1141    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1142    /// reports whatever the enclosing bytecode frame was called with.
1143    current_native: Option<Gc<JsObject>>,
1144    /// Text written by `print` and friends, in order.
1145    ///
1146    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1147    /// once at the end, which is also when upstream's line buffering becomes
1148    /// visible for the cases compared here.
1149    pub output: String,
1150    /// Where `print` also writes, as it goes. `output` keeps the full log for
1151    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1152    ///
1153    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1154    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1155    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1156    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1157    /// would show a script's output all at once when it finished.
1158    pub output_sink: Option<Box<dyn std::io::Write>>,
1159    /// Where recent property reads found their value.
1160    ///
1161    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1162    /// table remembering *which object* and *which entry of its property table* answered a
1163    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1164    /// can move; the property can become an accessor), which is what makes a stale entry a
1165    /// miss rather than a wrong answer.
1166    ///
1167    /// The object is held weakly: a cache that held it strongly would keep up to
1168    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1169    /// program cannot see and cannot work around.
1170    pub field_cache: Vec<Option<FieldCache>>,
1171    /// Global lookups, by binding slot. See [`GlobalCache`].
1172    global_cache: Vec<Option<GlobalCache>>,
1173    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1174    /// under its limit. See [`Interp::check_memory`].
1175    pub oom_reported_at: usize,
1176    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1177    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1178    ///
1179    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1180    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1181    /// host that wants to stop a runaway script must not have to wait for it to return.
1182    ///
1183    /// Two things this cannot do, both of them differences a host can observe:
1184    ///
1185    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1186    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1187    ///   needs a signal that the `catch` machinery does not see, which is a change to
1188    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1189    ///   a host that stops the script itself.
1190    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1191    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1192    ///   both, so the difference is when the counter hits zero, not whether it will.
1193    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1194    /// Instructions until the next [`Interp::interrupt`] poll.
1195    pub interrupt_counter: u32,
1196    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1197    ///
1198    /// A separate field from [`Interp::uncatchable`] because the two live for different
1199    /// spans. This one is the host's standing request; it survives the start of an
1200    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1201    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1202    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1203    /// cleared it before the script it was set for had a chance to throw.
1204    pub uncatchable_next: bool,
1205    /// Whether the exception now unwinding may be caught by a `catch`.
1206    ///
1207    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1208    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1209    /// a host stopping a runaway loop is not fought by the loop.
1210    ///
1211    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1212    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1213    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1214    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1215    pub uncatchable: bool,
1216    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1217    ///
1218    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1219    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1220    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1221    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1222    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1223    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1224    ///
1225    /// The numbers come out close for the same reason a C frame and a heap frame of this
1226    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1227    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1228    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1229    /// `crates/quickjs-cli/tests/limits.rs`.
1230    pub stack_limit: usize,
1231    /// The most frames that may be live at once, whatever the byte budget says.
1232    ///
1233    /// A second bound for a reason the reference does not have: our frames cost less than
1234    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1235    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1236    /// `--stack-size 1G` from being a memory bomb.
1237    pub max_frames: usize,
1238    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1239    ///
1240    /// Script execution does not return until this has drained, which is what makes
1241    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1242    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1243    /// not a `for`.
1244    pub(crate) jobs: std::collections::VecDeque<Job>,
1245    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1246    ///
1247    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1248    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1249    pub(crate) tasks: Vec<Task>,
1250    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1251    /// barrier'd evaluation started.
1252    ///
1253    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1254    /// lets a REPL report an error from the line it just evaluated without also reporting
1255    /// its own readline loop.
1256    trace_barriers: Vec<usize>,
1257    /// `os.signal` handlers, keyed by signal number.
1258    ///
1259    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1260    /// a handler cannot be freed while it is still registered.
1261    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1262    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1263    ///
1264    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1265    /// that is only reachable from a host closure could be freed while still registered.
1266    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1267    /// The next timer id.
1268    ///
1269    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1270    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1271    next_timer_id: i32,
1272    /// Errors thrown by timer callbacks, already rendered.
1273    ///
1274    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1275    /// that throws has no promise behind it. Both are reported by the host at the end of
1276    /// the loop, but only one is fixed up by a later `.catch`.
1277    timer_errors: Vec<String>,
1278    /// The module registry, keyed by canonical name.
1279    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1280    /// How the host turns a specifier into bytes.
1281    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1282    /// The module the host was asked to run, for `import.meta.main`.
1283    pub main_module_name: Option<String>,
1284    /// Module bodies currently running, innermost last.
1285    ///
1286    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1287    /// this is the only place that knows which module that is.
1288    pub module_stack: Vec<String>,
1289    /// Rejections that no handler has claimed, with the promise they belong to.
1290    ///
1291    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1292    /// reason alone cannot say whether somebody eventually listened.
1293    unhandled: Vec<(Gc<JsObject>, Value)>,
1294}
1295
1296impl<'a> Interp<'a> {
1297    /// Build an interpreter over `heap`, with a fresh realm.
1298    pub fn new(heap: &'a Heap) -> Interp<'a> {
1299        let object_proto = JsObject::ordinary(heap, None);
1300        let function_proto = JsObject::function(
1301            heap,
1302            Some(object_proto.clone()),
1303            Callable::Native {
1304                func: |_, _, _| Ok(Value::Undefined),
1305                own_instance: false,
1306            },
1307        );
1308        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1309        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1310        let mut interp = Interp {
1311            heap,
1312            realm: Realm {
1313                global,
1314                object_proto,
1315                function_proto,
1316                array_proto,
1317                array_constructor: None,
1318                promise_constructor: None,
1319                globals: BTreeMap::new(),
1320                declared: Vec::new(),
1321                lexical_consts: BTreeSet::new(),
1322                errors: BTreeMap::new(),
1323                string_proto: None,
1324                number_proto: None,
1325                boolean_proto: None,
1326                bigint_proto: None,
1327                error_proto: JsObject::ordinary(heap, None),
1328                date_proto: JsObject::ordinary(heap, None),
1329                throw_type_error: None,
1330                generator_proto: JsObject::ordinary(heap, None),
1331                promise_proto: None,
1332                async_generator_proto: None,
1333                symbol_proto: None,
1334                symbol_registry: BTreeMap::new(),
1335                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1336                regexp_proto: None,
1337                regexp_ctor: None,
1338                suppressed_error_proto: None,
1339                disposable_stack_proto: None,
1340                map_proto: None,
1341                set_proto: None,
1342                finalization_registries: Vec::new(),
1343                array_buffer_proto: None,
1344                typed_array_proto: None,
1345                typed_array_protos: Vec::new(),
1346                data_view_proto: None,
1347                async_disposable_stack_proto: None,
1348                iterator_proto: None,
1349                iterator_ctor: None,
1350                iterator_helper_proto: None,
1351                iterator_wrap_proto: None,
1352                generator_function_proto: None,
1353                async_function_proto: None,
1354                async_generator_function_proto: None,
1355                iterator_protos: std::collections::BTreeMap::new(),
1356                well_known_symbols: WellKnownSymbols::default(),
1357                host_classes: HostClasses::new(),
1358            },
1359            frames: Vec::new(),
1360            free_values: Vec::new(),
1361            global_cache: {
1362                let mut cache = Vec::new();
1363                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1364                cache
1365            },
1366            eval_scope: None,
1367            eval_depth: 0,
1368            eval_bindings: Vec::new(),
1369            eval_arguments: None,
1370            eval_with: None,
1371            active_eval_scope: None,
1372            eval_caller: None,
1373            pending_new_target: None,
1374            eval_new_target: None,
1375            native_frames: Vec::new(),
1376            current_native: None,
1377            output: String::new(),
1378            output_sink: None,
1379            field_cache: {
1380                let mut cache = Vec::new();
1381                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1382                cache
1383            },
1384            oom_reported_at: 0,
1385            interrupt: None,
1386            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1387            uncatchable_next: false,
1388            uncatchable: false,
1389            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1390            // absent.
1391            stack_limit: DEFAULT_STACK_SIZE,
1392            max_frames: MAX_FRAMES,
1393            jobs: std::collections::VecDeque::new(),
1394            tasks: Vec::new(),
1395            trace_barriers: Vec::new(),
1396            signal_handlers: std::collections::BTreeMap::new(),
1397            fd_handlers: std::collections::BTreeMap::new(),
1398            next_timer_id: 1,
1399            timer_errors: Vec::new(),
1400            modules: std::collections::BTreeMap::new(),
1401            module_loader: None,
1402            main_module_name: None,
1403            module_stack: Vec::new(),
1404            unhandled: Vec::new(),
1405        };
1406        crate::builtins::install(&mut interp);
1407        interp
1408    }
1409
1410    // -- allocation helpers -------------------------------------------------
1411
1412    /// A new string value.
1413    /// A `BigInt` value from a computed big integer.
1414    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1415        Value::BigInt(Gc::new(self.heap, value))
1416    }
1417
1418    /// A string value from bytes that are already WTF-8, which is how a string with an
1419    /// unpaired surrogate reaches a `Value`.
1420    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1421        Value::string_wtf8(self.heap, text)
1422    }
1423
1424    /// A new string value, from text that is valid UTF-8.
1425    pub fn string(&self, text: impl Into<String>) -> Value {
1426        Value::string(self.heap, text)
1427    }
1428
1429    /// A new ordinary object with the given prototype.
1430    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1431        JsObject::ordinary(self.heap, proto)
1432    }
1433
1434    // -- host classes -------------------------------------------------------
1435
1436    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1437    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1438        self.realm.host_classes.register(def)
1439    }
1440
1441    /// Register `def` under an id the host already holds (`JS_NewClass`).
1442    ///
1443    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1444    /// `JS_NewClass`.
1445    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1446        self.realm.host_classes.define(id, def)
1447    }
1448
1449    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1450    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1451        self.realm.host_classes.set_proto(id, proto);
1452    }
1453
1454    /// The prototype installed for `id`, if any.
1455    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1456        self.realm.host_classes.proto(id)
1457    }
1458
1459    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1460    ///
1461    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1462    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1463    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1464    /// host installed none.
1465    ///
1466    /// Answers `None` for an id that was never registered: the C API would return an
1467    /// exception, and silently making an ordinary object instead would move the failure to
1468    /// the first `JS_GetOpaque` that no longer matches.
1469    pub fn new_host_object(
1470        &mut self,
1471        proto: Option<Gc<JsObject>>,
1472        class_id: ClassId,
1473    ) -> Option<Gc<JsObject>> {
1474        let class = self.realm.host_classes.def(class_id)?;
1475        let proto = proto
1476            .or_else(|| self.realm.host_classes.proto(class_id))
1477            .or_else(|| Some(self.realm.object_proto.clone()));
1478        Some(JsObject::host_object(self.heap, proto, class_id, class))
1479    }
1480
1481    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1482    ///
1483    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1484    /// object, it is an object of another class, or the class never got a payload. A host
1485    /// that has to tell them apart uses [`JsObject::host_class_id`].
1486    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1487        let object = value.as_object()?;
1488        if object.host_class_id()? != class_id {
1489            return None;
1490        }
1491        object.host_opaque()
1492    }
1493
1494    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1495    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1496        match value.as_object() {
1497            Some(object) => object.set_host_opaque(opaque),
1498            None => false,
1499        }
1500    }
1501
1502    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1503    ///
1504    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1505    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1506    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1507    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1508    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1509    /// said `[object Object]` instead of `[object Array Iterator]`.
1510    ///
1511    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1512    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1513    /// its own.
1514    pub fn new_iterator_prototype(
1515        &mut self,
1516        tag: &str,
1517        next: crate::object::NativeFn,
1518    ) -> Gc<JsObject> {
1519        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1520            return existing.clone();
1521        }
1522        let parent = self.realm.iterator_proto.clone();
1523        let proto = self.new_object(parent);
1524        let next = self.new_native("next", 0, next);
1525        proto.define(
1526            "next",
1527            Property::with_attributes(Value::Object(next), true, false),
1528        );
1529        let key = self.realm.well_known_key(WellKnown::Iterator);
1530        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1531        proto.define_key(
1532            &key,
1533            Property::with_attributes(Value::Object(identity), true, false),
1534        );
1535        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1536        let tag_value = self.string(tag);
1537        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1538        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1539        // checks it.
1540        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1541        self.realm
1542            .iterator_protos
1543            .insert(tag.to_string(), proto.clone());
1544        proto
1545    }
1546
1547    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1548    ///
1549    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1550    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1551    /// produced. That is why the two branches are not merged.
1552    pub fn object_own_property_keys(
1553        &mut self,
1554        object: &Gc<JsObject>,
1555    ) -> JsResult<Vec<PropertyKey>> {
1556        if let Some(keys) = self.proxy_own_keys(object)? {
1557            return Ok(keys);
1558        }
1559        // Integer-like keys ascending, then the string keys in insertion order, then the
1560        // symbols — the order every schema that walks an object expects.
1561        let entries = object.property_entries();
1562        let mut numeric: Vec<u32> = Vec::new();
1563        // An integer-indexed exotic object reports its indices as own keys even though they
1564        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1565        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1566        // order). The length is asked per call, so a resizable buffer's view reports the
1567        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1568        if object.typed_array_parts().is_some() {
1569            for index in 0..object.typed_array_length().unwrap_or(0) {
1570                // `u32::try_from` cannot fail for a real length, but the length is a
1571                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1572                // as an array index and one element beyond is not.
1573                match u32::try_from(index) {
1574                    Ok(index) => numeric.push(index),
1575                    Err(_) => break,
1576                }
1577            }
1578        }
1579        let mut strings: Vec<PropertyKey> = Vec::new();
1580        let mut symbols: Vec<PropertyKey> = Vec::new();
1581        for (key, _) in entries {
1582            match &key {
1583                // A class-private name is never reported by any enumeration: that is the
1584                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1585                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1586                // symbol skip, `Object.assign`) therefore cannot see it.
1587                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1588                PropertyKey::Symbol(_) => symbols.push(key),
1589                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1590                    Some(index) => {
1591                        if !numeric.contains(&index) {
1592                            numeric.push(index);
1593                        }
1594                    }
1595                    None => strings.push(key),
1596                },
1597            }
1598        }
1599        numeric.sort_unstable();
1600        let mut keys: Vec<PropertyKey> = numeric
1601            .into_iter()
1602            .map(|index| PropertyKey::from(index.to_string()))
1603            .collect();
1604        keys.extend(strings);
1605        keys.extend(symbols);
1606        Ok(keys)
1607    }
1608
1609    /// The state behind a promise object, or `None` when `object` is not one.
1610    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1611        object.with(|data| match &data.kind {
1612            ObjectKind::Promise(state) => Some(state.clone()),
1613            _ => None,
1614        })
1615    }
1616
1617    /// A new pending promise.
1618    pub fn new_promise(&mut self) -> Gc<JsObject> {
1619        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1620        // the one place every promise is built, and a subclass that builds its instances
1621        // somewhere else would be invisible to `instanceof`.
1622        let default = self.realm.promise_proto.clone();
1623        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1624        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1625        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1626        // `prototype` getter therefore still gets a working promise; the alternative is a
1627        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1628        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1629        let promise = JsObject::ordinary(self.heap, proto);
1630        promise.with_mut(|data| {
1631            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1632                crate::object::PromiseState::default(),
1633            )));
1634        });
1635        promise
1636    }
1637
1638    /// Fulfil `promise`, unless it has already settled.
1639    ///
1640    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1641    /// after `reject`, changes nothing.
1642    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1643        let Some(state) = self.promise_state(promise) else {
1644            return;
1645        };
1646        let reactions = {
1647            let mut state = state.borrow_mut();
1648            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1649                return;
1650            }
1651            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1652            std::mem::take(&mut state.reactions)
1653        };
1654        self.queue_reactions(reactions, value, false);
1655    }
1656
1657    /// Reject `promise`, unless it has already settled.
1658    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1659        let Some(state) = self.promise_state(promise) else {
1660            return;
1661        };
1662        let reactions = {
1663            let mut state = state.borrow_mut();
1664            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1665                return;
1666            }
1667            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1668            std::mem::take(&mut state.reactions)
1669        };
1670        // Remember it only when nothing is listening *now*; a `then` registered later
1671        // prunes the entry in `perform_then`.
1672        if reactions.is_empty() {
1673            self.unhandled.push((promise.clone(), reason.clone()));
1674        }
1675        self.queue_reactions(reactions, reason, true);
1676    }
1677
1678    /// Queue one job per reaction.
1679    ///
1680    /// This is what makes `then` asynchronous even on an already-settled promise:
1681    /// `p.then(f); g()` calls `g` first.
1682    fn queue_reactions(
1683        &mut self,
1684        reactions: Vec<crate::object::PromiseReaction>,
1685        argument: Value,
1686        rejected: bool,
1687    ) {
1688        for reaction in reactions {
1689            let handler = if rejected {
1690                reaction.on_rejected.clone()
1691            } else {
1692                reaction.on_fulfilled.clone()
1693            };
1694            self.jobs.push_back(Job::Reaction {
1695                handler,
1696                argument: argument.clone(),
1697                rejected,
1698                promise: reaction.promise,
1699            });
1700        }
1701    }
1702
1703    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1704    /// resolve/reject pair.
1705    ///
1706    /// The pair are callable objects rather than Rust closures, because the script gets
1707    /// them and may stash them for later.
1708    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1709        let promise = self.new_promise();
1710        // Both handlers are built-ins with an empty name and length 1, in
1711        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1712        // off `Object.getOwnPropertyNames`.
1713        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1714        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1715        (promise, Value::Object(resolve), Value::Object(reject))
1716    }
1717
1718    /// §27.2.1.5 `NewPromiseCapability(C)`.
1719    ///
1720    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1721    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1722    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1723    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1724    /// silently ignored argument.
1725    ///
1726    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1727    /// the engine's own executor is exactly what `new_promise_capability` builds.
1728    pub fn new_promise_capability_for(
1729        &mut self,
1730        constructor: &Value,
1731    ) -> JsResult<(Value, Value, Value)> {
1732        let Some(object) = constructor.as_object().cloned() else {
1733            return Err(self.type_error("promise constructor is not a constructor"));
1734        };
1735        if !object.is_constructor() {
1736            return Err(self.type_error("promise constructor is not a constructor"));
1737        }
1738        if self
1739            .realm
1740            .promise_constructor
1741            .as_ref()
1742            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1743        {
1744            let (promise, resolve, reject) = self.new_promise_capability();
1745            return Ok((Value::Object(promise), resolve, reject));
1746        }
1747        let state = self.new_object(Some(self.realm.object_proto.clone()));
1748        // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1749        // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1750        // which only a *custom* constructor can observe, and none of the combinator tests
1751        // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1752        let executor = self.builtin_function(
1753            "",
1754            2,
1755            Callable::CapabilityExecutor {
1756                state: state.clone(),
1757            },
1758        );
1759        let promise = self.construct(
1760            Value::Object(object.clone()),
1761            Value::Object(object),
1762            vec![Value::Object(executor)],
1763        )?;
1764        // The pair is read *after* the constructor returns, so a constructor that never
1765        // called its executor, or called it with non-callables, is the spec's step 11
1766        // `TypeError` — not something the engine can paper over.
1767        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1768            return Err(self.type_error("promise executor never ran"));
1769        };
1770        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1771            return Err(self.type_error("promise executor never ran"));
1772        };
1773        for handler in [&resolve, &reject] {
1774            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1775                return Err(self.type_error("promise capability handler is not callable"));
1776            }
1777        }
1778        Ok((promise, resolve, reject))
1779    }
1780
1781    /// §27.2.3.1 `PromiseResolve(C, x)`.
1782    ///
1783    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1784    /// an `x` that is already a promise of exactly this constructor is handed back
1785    /// unchanged, and anything else gets a fresh capability from `C`.
1786    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1787        if let Value::Object(object) = &value
1788            && self.promise_state(object).is_some()
1789        {
1790            // `x.constructor === C` means "already the right kind", so no capability is
1791            // built — which is observable through a `resolve` that counts its calls.
1792            let x_constructor = self.get_property(object, "constructor")?;
1793            let same = match (
1794                x_constructor.as_ref().and_then(Value::as_object),
1795                constructor.as_object(),
1796            ) {
1797                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1798                _ => false,
1799            };
1800            if same {
1801                return Ok(value);
1802            }
1803        }
1804        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1805        self.call_value(resolve, Value::Undefined, vec![value])?;
1806        Ok(promise)
1807    }
1808
1809    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1810    /// promise, as `{ value: completion }`.
1811    ///
1812    /// The three cases are the reference's, and they differ on purpose:
1813    ///
1814    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1815    ///   exception before any promise exists;
1816    /// * a **runtime** error rejects the returned promise;
1817    /// * success resolves it with `{ value }`, where the value is the script's completion
1818    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1819    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1820    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1821    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1822    ///
1823    /// # What this does not do
1824    ///
1825    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1826    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1827    /// the parser and the suspension machinery to accept a suspended top-level script, and
1828    /// is not implemented — such source is a syntax error here. Everything else about the
1829    /// flag is reproduced.
1830    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1831        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1832        // too, and the reference truncates that one at the same place as a runtime failure.
1833        if barrier {
1834            let depth = self.frames.len();
1835            self.trace_barriers.push(depth);
1836        }
1837        // Compiled before the promise exists, so a parse failure propagates as a throw
1838        // instead of being folded into a rejection.
1839        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1840            Ok(compiled) => compiled,
1841            Err(error) => {
1842                if barrier {
1843                    self.trace_barriers.pop();
1844                }
1845                return Err(error);
1846            }
1847        };
1848        // An async body answers its own promise, and that promise is what the reference
1849        // hands back — the same object, not a wrapper around it. Its resolution value is
1850        // the `{value}` object the compiled epilogue built.
1851        if compiled.kind.is_async() {
1852            let strict = compiled.strict;
1853            let promise = self.run_eval_script(compiled, strict)?;
1854            if barrier {
1855                self.trace_barriers.pop();
1856            }
1857            return Ok(promise);
1858        }
1859        let (promise, resolve, reject) = self.new_promise_capability();
1860        let strict = compiled.strict;
1861        match self.run_eval_script(compiled, strict) {
1862            Ok(value) => {
1863                // `{ value }` is a plain object, so resolving with it adopts nothing even
1864                // when the completion value is itself a promise.
1865                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1866                self.set_property(&wrapped, "value", value)?;
1867                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1868            }
1869            Err(Signal::Throw(error)) => {
1870                self.call_value(reject, Value::Undefined, vec![error])?;
1871            }
1872            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1873        }
1874        if barrier {
1875            self.trace_barriers.pop();
1876        }
1877        Ok(Value::Object(promise))
1878    }
1879
1880    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1881    ///
1882    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1883    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1884    /// timer table, where the collector already scans it.
1885    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1886        let (promise, resolve, _reject) = self.new_promise_capability();
1887        let resolve = self.new_host_function(
1888            "resolve",
1889            1,
1890            Box::new(
1891                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1892                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1893                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1894                },
1895            ),
1896        );
1897        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1898        // timer table is part of what the collector walks.
1899        self.schedule_timer(Value::Object(resolve), delay_ms);
1900        Ok(Value::Object(promise))
1901    }
1902
1903    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1904    /// new promise resolved with it.
1905    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1906        if let Value::Object(object) = &value
1907            && self.promise_state(object).is_some()
1908        {
1909            return Ok(value);
1910        }
1911        let promise = self.new_promise();
1912        self.resolve_promise_with(&promise, value)?;
1913        Ok(Value::Object(promise))
1914    }
1915
1916    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1917    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1918        // Resolving a promise with itself is a `TypeError`. The check exists because the
1919        // alternative is a chain of self-reactions that never settles.
1920        if let Value::Object(object) = &value
1921            && object.ptr_eq(promise)
1922        {
1923            // The spec rejects *and* throws, so both the promise and the caller see it.
1924            let thrown = self.type_error("cannot resolve a promise with itself");
1925            let Signal::Throw(error) = thrown.clone() else {
1926                unreachable!("type_error always throws")
1927            };
1928            self.reject_promise(promise, error);
1929            return Err(thrown);
1930        }
1931        let then = match &value {
1932            Value::Object(object) => self.get_property(object, "then")?,
1933            _ => None,
1934        };
1935        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1936        if !callable_then {
1937            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1938            self.fulfill_promise(promise, value);
1939            return Ok(());
1940        }
1941        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1942        // inside `resolve`, so a script cannot make a promise settle synchronously.
1943        self.jobs.push_back(Job::Thenable {
1944            then: then.expect("checked callable"),
1945            value,
1946            promise: promise.clone(),
1947        });
1948        Ok(())
1949    }
1950
1951    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1952    ///
1953    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1954    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1955    ///
1956    /// The property read is **not** short-circuitable even for a real promise: the spec says
1957    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1958    /// expects it to run. Skipping the read for promises not only lost the throw, it made
1959    /// the combinator's loop infinite — the test's iterator never sets `done`.
1960    pub fn invoke_then(
1961        &mut self,
1962        thenable: Value,
1963        on_fulfilled: Value,
1964        on_rejected: Value,
1965    ) -> JsResult<()> {
1966        let then = match &thenable {
1967            Value::Object(object) => self.get_property(object, "then")?,
1968            primitive => {
1969                let boxed = self.object_from(primitive)?;
1970                self.get_property(&boxed, "then")?
1971            }
1972        };
1973        let Some(then) = then else {
1974            return Err(self.type_error("thenable has no then method"));
1975        };
1976        if !matches!(&then, Value::Object(object) if object.is_callable()) {
1977            return Err(self.type_error("then is not a function"));
1978        }
1979        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1980        Ok(())
1981    }
1982
1983    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1984    ///
1985    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1986    /// promise.
1987    pub fn perform_then(
1988        &mut self,
1989        promise: &Gc<JsObject>,
1990        on_fulfilled: Option<Value>,
1991        on_rejected: Option<Value>,
1992    ) -> JsResult<Value> {
1993        let Some(state) = self.promise_state(promise) else {
1994            return Err(self.type_error("not a promise"));
1995        };
1996        // Whether a rejection handler is being attached decides whether a recorded
1997        // rejection stops being unhandled, so it is read before the values are moved.
1998        let has_rejection_handler = on_rejected.is_some();
1999        let derived = self.new_promise();
2000        let reaction = crate::object::PromiseReaction {
2001            on_fulfilled,
2002            on_rejected,
2003            promise: derived.clone(),
2004        };
2005        let settled = {
2006            let mut state = state.borrow_mut();
2007            // A rejection somebody reacts to is no longer unhandled.
2008            state.handled = true;
2009            match &state.status {
2010                crate::object::PromiseStatus::Pending => {
2011                    state.reactions.push(reaction.clone());
2012                    None
2013                }
2014                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2015                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2016            }
2017        };
2018        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2019        // later, means somebody is listening after all.
2020        if has_rejection_handler {
2021            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2022        }
2023        if let Some((argument, rejected)) = settled {
2024            let handler = if rejected {
2025                reaction.on_rejected
2026            } else {
2027                reaction.on_fulfilled
2028            };
2029            self.jobs.push_back(Job::Reaction {
2030                handler,
2031                argument,
2032                rejected,
2033                promise: reaction.promise,
2034            });
2035        }
2036        Ok(Value::Object(derived))
2037    }
2038
2039    /// The rejections nobody listened to, formatted the way the reference reports them.
2040    ///
2041    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2042    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2043    /// unhandled at the point the queue drains, because a `then` may still be attached
2044    /// before the host acts on it.
2045    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2046        let entries = std::mem::take(&mut self.unhandled);
2047        // Somebody may have attached a handler after the rejection was recorded, so the
2048        // promise is the authority rather than the list.
2049        let still_unhandled: Vec<Value> = entries
2050            .into_iter()
2051            .filter_map(|(promise, reason)| {
2052                let handled = self
2053                    .promise_state(&promise)
2054                    .map(|state| state.borrow().handled)
2055                    .unwrap_or(true);
2056                (!handled).then_some(reason)
2057            })
2058            .collect();
2059        still_unhandled
2060            .into_iter()
2061            .map(|reason| {
2062                let text = self.describe_exception(&reason);
2063                let stack = match &reason {
2064                    Value::Object(object) => self
2065                        .get_property(object, "stack")
2066                        .ok()
2067                        .flatten()
2068                        .map(|value| value.to_js_string())
2069                        // `stack` carries a trailing newline of its own, which would leave
2070                        // a blank line between two reported rejections.
2071                        .map(|text| text.trim_end().to_string())
2072                        .unwrap_or_default(),
2073                    _ => String::new(),
2074                };
2075                if stack.is_empty() {
2076                    format!("Possibly unhandled promise rejection: {text}")
2077                } else {
2078                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2079                }
2080            })
2081            .collect()
2082    }
2083
2084    /// Run the microtask queue to exhaustion.
2085    ///
2086    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2087    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2088    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2089    ///
2090    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2091    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2092    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2093    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2094        crate::builtins::json::parse_text(self, text, true)
2095    }
2096
2097    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2098    ///
2099    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2100    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2101    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2102    ///
2103    /// The callback is called with **no arguments**. The reference stores only the function
2104    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2105    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2106    /// extra arguments arrive as `undefined`.
2107    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2108        let id = self.next_timer_id;
2109        // Wrap rather than grow: the id reaches the script as an `Int32`.
2110        self.next_timer_id = if self.next_timer_id == i32::MAX {
2111            1
2112        } else {
2113            self.next_timer_id + 1
2114        };
2115        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2116        self.tasks.push(Task::Timer {
2117            id,
2118            callback,
2119            due_at,
2120        });
2121        id
2122    }
2123
2124    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2125    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2126    pub fn cancel_timer(&mut self, id: i32) -> bool {
2127        let before = self.tasks.len();
2128        self.tasks.retain(|task| match task {
2129            Task::Timer { id: task_id, .. } => *task_id != id,
2130        });
2131        self.tasks.len() != before
2132    }
2133
2134    /// How long until the earliest pending timer, or `None` when none is pending.
2135    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2136        let now = std::time::Instant::now();
2137        self.tasks
2138            .iter()
2139            .map(|task| match task {
2140                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2141            })
2142            .min()
2143    }
2144
2145    /// Run one turn of the event loop.
2146    ///
2147    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2148    /// run at most one due timer, then drain again. The blocking belongs to the caller
2149    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2150    /// is how it asks.
2151    ///
2152    /// One timer per turn rather than all of them: a timer callback may schedule another
2153    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2154    /// starve the microtask queue.
2155    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2156        self.drain_jobs()?;
2157        let now = std::time::Instant::now();
2158        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2159        // followed by `setTimeout(g, 1)` must run `g` first.
2160        let due = self
2161            .tasks
2162            .iter()
2163            .enumerate()
2164            .filter(|(_, task)| match task {
2165                Task::Timer { due_at, .. } => *due_at <= now,
2166            })
2167            .min_by_key(|(_, task)| match task {
2168                Task::Timer { due_at, .. } => *due_at,
2169            })
2170            .map(|(index, _)| index);
2171        let Some(index) = due else {
2172            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2173            // descriptor is registered but no timer is closer, so a script that never
2174            // touches the descriptor still gets control back. Without a cap a handler on a
2175            // descriptor that is never ready would block for as long as the host allows.
2176            let timeout = self
2177                .next_timeout()
2178                .unwrap_or(std::time::Duration::from_secs(10))
2179                .min(std::time::Duration::from_secs(10));
2180            if !self.fd_handlers.is_empty() {
2181                // Blocking on a timer while descriptors are registered would starve them,
2182                // and blocking on the descriptors while a timer is due would delay it; the
2183                // host polls with the earlier of the two deadlines, which this timeout is.
2184                return Ok(Turn::Poll(timeout));
2185            }
2186            return Ok(match self.next_timeout() {
2187                Some(wait) => Turn::Wait(wait),
2188                None => Turn::Done,
2189            });
2190        };
2191        let Task::Timer { callback, .. } = self.tasks.remove(index);
2192        let this = Value::Undefined;
2193        // A throwing timer callback must not stop the loop: the reference reports it and
2194        // keeps going, because the alternative is that one bad timer silently stops every
2195        // later one.
2196        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2197        match self.call_value(callback, this, Vec::new()) {
2198            Ok(_) => {}
2199            Err(Signal::Throw(value)) => {
2200                let text = self.describe_exception(&value);
2201                self.timer_errors.push(text);
2202            }
2203            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2204        }
2205        self.drain_jobs()?;
2206        Ok(Turn::Ran)
2207    }
2208
2209    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2210    ///
2211    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2212    /// left is removed — the reference does the same, so a script can rely on
2213    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2214    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2215        let entry = self.fd_handlers.entry(fd).or_default();
2216        if readable {
2217            entry.read = callback;
2218        } else {
2219            entry.write = callback;
2220        }
2221        if entry.read.is_none() && entry.write.is_none() {
2222            self.fd_handlers.remove(&fd);
2223        }
2224    }
2225
2226    /// Register or clear an `os.signal` handler.
2227    ///
2228    /// `None` removes it; the host separately restores the default disposition or sets
2229    /// ignore, because which of those happened is the script's choice (`null` versus
2230    /// `undefined`) and not something this table can express.
2231    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2232        match handler {
2233            Some(handler) => {
2234                self.signal_handlers.insert(signal, handler);
2235            }
2236            None => {
2237                self.signal_handlers.remove(&signal);
2238            }
2239        }
2240    }
2241
2242    /// Run the handler for `signal`, reporting whether one ran.
2243    ///
2244    /// A throwing handler is reported and the loop continues, like a timer's.
2245    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2246        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2247            return Ok(false);
2248        };
2249        match self.call_value(handler, Value::Undefined, Vec::new()) {
2250            Ok(_) => {}
2251            Err(Signal::Throw(value)) => {
2252                let text = self.describe_exception(&value);
2253                self.timer_errors.push(text);
2254            }
2255            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2256        }
2257        self.drain_jobs()?;
2258        Ok(true)
2259    }
2260
2261    /// The descriptors the host has to poll, and in which direction.
2262    ///
2263    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2264    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2265    /// `os_poll` asks for.
2266    pub fn pending_fds(&self) -> Vec<FdInterest> {
2267        self.fd_handlers
2268            .iter()
2269            .map(|(fd, entry)| FdInterest {
2270                fd: *fd,
2271                read: entry.read.is_some(),
2272                write: entry.write.is_some(),
2273            })
2274            .collect()
2275    }
2276
2277    /// Call the handler registered for `fd`, reporting whether one ran.
2278    ///
2279    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2280    /// poll iteration and then restarts the loop, because the handler may have changed the
2281    /// registration list underneath it; doing the same here keeps a handler that
2282    /// unregisters itself from being called with stale state.
2283    ///
2284    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2285    /// every later one, exactly as with timers.
2286    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2287        let Some(entry) = self.fd_handlers.get(&fd) else {
2288            return Ok(false);
2289        };
2290        let callback = if readable {
2291            entry.read.clone()
2292        } else if writable {
2293            entry.write.clone()
2294        } else {
2295            None
2296        };
2297        let Some(callback) = callback else {
2298            return Ok(false);
2299        };
2300        self.drain_jobs()?;
2301        match self.call_value(callback, Value::Undefined, Vec::new()) {
2302            Ok(_) => {}
2303            Err(Signal::Throw(value)) => {
2304                let text = self.describe_exception(&value);
2305                self.timer_errors.push(text);
2306            }
2307            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2308        }
2309        self.drain_jobs()?;
2310        Ok(true)
2311    }
2312
2313    /// Take the errors timer callbacks threw, leaving the list empty.
2314    pub fn take_timer_errors(&mut self) -> Vec<String> {
2315        std::mem::take(&mut self.timer_errors)
2316    }
2317
2318    /// Whether anything is still pending: a microtask or a timer.
2319    pub fn has_pending_work(&self) -> bool {
2320        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2321    }
2322
2323    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2324    pub fn has_pending_timers_or_jobs(&self) -> bool {
2325        !self.jobs.is_empty() || !self.tasks.is_empty()
2326    }
2327
2328    /// Run every queued microtask, including ones queued while draining.
2329    pub fn drain_jobs(&mut self) -> JsResult<()> {
2330        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2331        // would spin forever, so the drain is bounded the way the call stack is.
2332        let mut budget = 1_000_000usize;
2333        while let Some(job) = self.jobs.pop_front() {
2334            if budget == 0 {
2335                return Err(Signal::Throw(
2336                    self.make_error("InternalError", "promise job queue did not drain"),
2337                ));
2338            }
2339            budget -= 1;
2340            self.run_job(job)?;
2341            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2342            // engine may run script that the script itself did not ask for. Doing it here
2343            // rather than from a drop hook is what keeps the callback out of arbitrary
2344            // engine bookkeeping — see `builtins::weak`'s header.
2345            crate::builtins::weak::drain_finalizers(self)?;
2346        }
2347        // A script that queued no jobs may still have dropped targets, so the checkpoint
2348        // runs once more after the queue empties.
2349        crate::builtins::weak::drain_finalizers(self)?;
2350        Ok(())
2351    }
2352
2353    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2354    ///
2355    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2356    /// `None` and is swept out here. This is also where the realm learns that a registry
2357    /// died, which is why it is a mutation rather than a read.
2358    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2359        let handles = std::mem::take(&mut self.realm.finalization_registries);
2360        let mut live = Vec::with_capacity(handles.len());
2361        for handle in handles {
2362            let Some(object) = handle.upgrade() else {
2363                continue;
2364            };
2365            let Some(state) = object.finalization_state() else {
2366                continue;
2367            };
2368            live.push((object.clone(), *state));
2369            self.realm.finalization_registries.push(object.downgrade());
2370        }
2371        live
2372    }
2373
2374    /// Run one microtask.
2375    fn run_job(&mut self, job: Job) -> JsResult<()> {
2376        match job {
2377            Job::Reaction {
2378                handler: None,
2379                argument,
2380                rejected,
2381                promise,
2382            } => {
2383                // No handler: the settlement passes straight through to the derived
2384                // promise, which is why `p.catch(f)` ignores fulfilments.
2385                if rejected {
2386                    self.reject_promise(&promise, argument);
2387                } else {
2388                    self.fulfill_promise(&promise, argument);
2389                }
2390                Ok(())
2391            }
2392            Job::Reaction {
2393                handler: Some(handler),
2394                argument,
2395                promise,
2396                ..
2397            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2398                Ok(answer) => {
2399                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2400                        self.reject_promise(&promise, error);
2401                    }
2402                    Ok(())
2403                }
2404                Err(Signal::Throw(reason)) => {
2405                    self.reject_promise(&promise, reason);
2406                    Ok(())
2407                }
2408                Err(other) => Err(other),
2409            },
2410            Job::Thenable {
2411                then,
2412                value,
2413                promise,
2414            } => {
2415                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2416                // the value it produces settles `promise`.
2417                // The thenable's `then` gets this promise's own pair, so whatever it
2418                // produces settles `promise`.
2419                let resolve = JsObject::function(
2420                    self.heap,
2421                    Some(self.realm.function_proto.clone()),
2422                    Callable::PromiseResolve(promise.clone()),
2423                );
2424                let reject = JsObject::function(
2425                    self.heap,
2426                    Some(self.realm.function_proto.clone()),
2427                    Callable::PromiseReject(promise.clone()),
2428                );
2429                match self.call_value(
2430                    then,
2431                    value,
2432                    vec![Value::Object(resolve), Value::Object(reject)],
2433                ) {
2434                    Ok(_) => Ok(()),
2435                    Err(Signal::Throw(reason)) => {
2436                        self.reject_promise(&promise, reason);
2437                        Ok(())
2438                    }
2439                    Err(other) => Err(other),
2440                }
2441            }
2442            Job::Resume {
2443                coroutine,
2444                promise,
2445                kind,
2446                value,
2447            } => self.drive_async(&coroutine, &promise, kind, value),
2448            Job::GeneratorResume {
2449                generator,
2450                promise,
2451                kind,
2452                value,
2453            } => self.step_async_generator(&generator, &promise, kind, value),
2454            Job::Import {
2455                specifier,
2456                referrer,
2457                promise,
2458            } => {
2459                self.run_dynamic_import(&specifier, &referrer, &promise);
2460                Ok(())
2461            }
2462        }
2463    }
2464
2465    /// One element of a `Promise` combinator settled.
2466    ///
2467    /// The shared state object holds the result array, the number still outstanding, and
2468    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2469    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2470    /// to settle, only whatever `Sub` said a capability is.
2471    ///
2472    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2473    /// and `any` must ignore every later settlement, and `all` must not report a second
2474    /// rejection after the first.
2475    fn settle_combinator(
2476        &mut self,
2477        state: &Gc<JsObject>,
2478        index: usize,
2479        fulfilled: bool,
2480        value: Value,
2481    ) -> JsResult<()> {
2482        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2483        // Each element settles at most once: a thenable may call `onFulfilled` twice
2484        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2485        // call a no-op. Without it the second call decremented `remaining` again and settled
2486        // `all` with a short values array (`call-resolve-element-items`).
2487        let done = field("done");
2488        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2489        let settled = field("settled").is_some_and(|value| value.to_boolean());
2490        if settled {
2491            return Ok(());
2492        }
2493        if let Some(Value::Object(done)) = &done {
2494            if done
2495                .array_get(index)
2496                .is_some_and(|value| value.to_boolean())
2497            {
2498                return Ok(());
2499            }
2500            done.array_set(self.heap, index, Value::Bool(true));
2501        }
2502        let resolve = field("resolve");
2503        let reject = field("reject");
2504        let keys = field("keys");
2505        let results = field("results").and_then(|value| value.as_object().cloned());
2506        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2507        // promise: the handler is a plain function the constructor chose.
2508        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2509            if let Some(handler) = handler {
2510                interp.call_value(handler, Value::Undefined, vec![value])?;
2511            }
2512            Ok(())
2513        };
2514        match kind {
2515            // `race`: the first settlement wins and stops the rest.
2516            3 => {
2517                state.define_data("settled", Value::Bool(true));
2518                let handler = if fulfilled { resolve } else { reject };
2519                settle_with(self, handler, value)?;
2520                return Ok(());
2521            }
2522            // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2523            // the first rejection wins outright.
2524            0 | 4 if !fulfilled => {
2525                state.define_data("settled", Value::Bool(true));
2526                settle_with(self, reject, value)?;
2527                return Ok(());
2528            }
2529            // `any`: the first fulfilment wins.
2530            2 if fulfilled => {
2531                state.define_data("settled", Value::Bool(true));
2532                settle_with(self, resolve, value)?;
2533                return Ok(());
2534            }
2535            _ => {}
2536        }
2537        let Some(results) = &results else {
2538            return Ok(());
2539        };
2540        match kind {
2541            4 => {
2542                results.array_set(self.heap, index, value);
2543            }
2544            0 => {
2545                results.array_set(self.heap, index, value);
2546            }
2547            // `allSettled` (and its keyed twin) never rejects; each slot records what
2548            // happened.
2549            1 | 5 => {
2550                let record = self.new_object(Some(self.realm.object_proto.clone()));
2551                if fulfilled {
2552                    record.define_data("status", self.string("fulfilled"));
2553                    record.define_data("value", value);
2554                } else {
2555                    record.define_data("status", self.string("rejected"));
2556                    record.define_data("reason", value);
2557                }
2558                results.array_set(self.heap, index, Value::Object(record));
2559            }
2560            // `any`: a rejection is parked in the errors array and the sweep continues.
2561            2 => {
2562                results.array_set(self.heap, index, value);
2563            }
2564            _ => {}
2565        }
2566        let remaining = field("remaining")
2567            .map(|value| value.to_int32())
2568            .unwrap_or(0);
2569        let left = remaining - 1;
2570        state.define_data("remaining", Value::Int(left));
2571        if left != 0 {
2572            return Ok(());
2573        }
2574        state.define_data("settled", Value::Bool(true));
2575        match kind {
2576            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2577            // The keyed result: an ordinary object with a **null** prototype, holding the
2578            // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2579            4 | 5 => {
2580                let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2581                settle_with(self, resolve, keyed)?;
2582            }
2583            2 => {
2584                // The rejection is an `AggregateError` whose `errors` is the results array
2585                // itself — the slots are the reasons, in input order.
2586                let errors = results.array_elements().unwrap_or_default();
2587                let error = self.aggregate_error(errors, "all promises were rejected");
2588                settle_with(self, reject, error)?;
2589            }
2590            _ => {}
2591        }
2592        Ok(())
2593    }
2594
2595    /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2596    ///
2597    /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2598    /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2599    /// prototype is load-bearing in both directions: a key called `toString` must not
2600    /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2601    /// (`resolves-empty-object.js`).
2602    pub(crate) fn keyed_result_object(
2603        &mut self,
2604        keys: Option<&Value>,
2605        values: &Gc<JsObject>,
2606    ) -> JsResult<Value> {
2607        let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2608            return Ok(Value::Object(self.new_object(None)));
2609        };
2610        let result = self.new_object(None);
2611        let count = values.array_length().unwrap_or(0);
2612        for index in 0..count {
2613            let Some(key) = keys.array_get(index) else {
2614                continue;
2615            };
2616            let Some(value) = values.array_get(index) else {
2617                continue;
2618            };
2619            let property = Property::with_attributes(value, true, true);
2620            match &key {
2621                Value::Symbol(symbol) => {
2622                    result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2623                }
2624                other => {
2625                    let text = self.to_js_string(other)?;
2626                    result.define_key(&PropertyKey::from(text.as_str()), property);
2627                }
2628            }
2629        }
2630        Ok(Value::Object(result))
2631    }
2632
2633    /// Build an async function's result: a promise whose body runs as a coroutine.
2634    pub fn new_async_function(
2635        &mut self,
2636        function: Value,
2637        this: Value,
2638        args: Vec<Value>,
2639    ) -> JsResult<Value> {
2640        let promise = self.new_promise();
2641        let coroutine = self.new_coroutine(function, this, args)?;
2642        if let Err(Signal::Throw(reason)) =
2643            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2644        {
2645            self.reject_promise(&promise, reason);
2646        }
2647        Ok(Value::Object(promise))
2648    }
2649
2650    /// The coroutine an async body runs in.
2651    ///
2652    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2653    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2654    /// than growing a second state machine. The difference is only in the ending — a
2655    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2656    /// Run `code` as an async function body, answering the promise it settles.
2657    ///
2658    /// Used for a module with top-level `await`: its body is an async function whose
2659    /// caller is the host, so there is no function object to pass through
2660    /// [`Interp::new_async_function`].
2661    pub fn run_async_body(
2662        &mut self,
2663        code: Gc<CompiledCode>,
2664        env: Gc<ClosureEnv>,
2665        this: Value,
2666    ) -> JsResult<Value> {
2667        let promise = self.new_promise();
2668        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2669        if let Err(Signal::Throw(reason)) =
2670            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2671        {
2672            self.reject_promise(&promise, reason);
2673        }
2674        Ok(Value::Object(promise))
2675    }
2676
2677    fn new_coroutine(
2678        &mut self,
2679        function: Value,
2680        this: Value,
2681        args: Vec<Value>,
2682    ) -> JsResult<Gc<JsObject>> {
2683        let Some(object) = function.as_object().cloned() else {
2684            return Err(self.type_error("not a function"));
2685        };
2686        let Some((code, env)) = bytecode_of(&object) else {
2687            return Err(self.type_error("not a function"));
2688        };
2689        self.new_coroutine_from(code, env, this, args)
2690    }
2691
2692    /// Build a coroutine over an already-resolved body.
2693    fn new_coroutine_from(
2694        &mut self,
2695        code: Gc<CompiledCode>,
2696        env: Gc<ClosureEnv>,
2697        this: Value,
2698        args: Vec<Value>,
2699    ) -> JsResult<Gc<JsObject>> {
2700        let function = Value::Undefined;
2701        self.push_frame(code, env, this, args, function)?;
2702        let frame = self.frames.pop().expect("push_frame just pushed it");
2703        let state = GeneratorState {
2704            frame: Some(frame),
2705            phase: GeneratorPhase::SuspendedStart,
2706            parked_on_await: false,
2707            parked_on_yield_star: false,
2708            requests: std::collections::VecDeque::new(),
2709            async_busy: false,
2710        };
2711        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2712        coroutine.with_mut(|data| {
2713            data.kind = ObjectKind::Generator(Box::new(state));
2714        });
2715        Ok(coroutine)
2716    }
2717
2718    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2719    /// `await` and `value` is what it awaited.
2720    fn resume_coroutine(
2721        &mut self,
2722        coroutine: &Gc<JsObject>,
2723        kind: ResumeKind,
2724        value: Value,
2725    ) -> JsResult<(Value, bool)> {
2726        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2727            ObjectKind::Generator(state) => Some(std::mem::replace(
2728                state.as_mut(),
2729                GeneratorState {
2730                    frame: None,
2731                    phase: GeneratorPhase::Executing,
2732                    parked_on_await: false,
2733                    parked_on_yield_star: false,
2734                    requests: std::collections::VecDeque::new(),
2735                    async_busy: false,
2736                },
2737            )),
2738            _ => None,
2739        }) else {
2740            return Err(self.type_error("not a coroutine"));
2741        };
2742        let result = self.step_generator(&mut state, kind, value);
2743        coroutine.with_mut(|data| {
2744            data.kind = ObjectKind::Generator(Box::new(state));
2745        });
2746        let (value, done, _ready, _reason) = result?;
2747        Ok((value, done))
2748    }
2749
2750    /// Advance an async body and settle its promise with the outcome.
2751    fn drive_async(
2752        &mut self,
2753        coroutine: &Gc<JsObject>,
2754        promise: &Gc<JsObject>,
2755        kind: ResumeKind,
2756        value: Value,
2757    ) -> JsResult<()> {
2758        match self.resume_coroutine(coroutine, kind, value) {
2759            Ok((value, true)) => {
2760                // `Ok` with `done` means the body finished *normally*, even when it was
2761                // resumed by a `throw` — `try { await p } catch {}` completes by
2762                // returning. Only the `Err` arm below is a rejection.
2763                //
2764                // Resolving rather than fulfilling matters: `return promise` in an async
2765                // body adopts the inner promise, so `async function f(){ return
2766                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2767                // promise.
2768                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2769                    self.reject_promise(promise, reason);
2770                }
2771                Ok(())
2772            }
2773            Ok((value, false)) => {
2774                // Parked on `await`: follow what it awaited and resume with the outcome.
2775                let awaited = match self.promise_resolve_value(value) {
2776                    Ok(awaited) => awaited,
2777                    Err(Signal::Throw(error)) => {
2778                        self.reject_promise(promise, error);
2779                        return Ok(());
2780                    }
2781                    Err(other) => return Err(other),
2782                };
2783                self.hook_await(awaited, coroutine, promise)
2784            }
2785            Err(Signal::Throw(reason)) => {
2786                self.reject_promise(promise, reason);
2787                Ok(())
2788            }
2789            Err(other) => Err(other),
2790        }
2791    }
2792
2793    /// Arrange for `coroutine` to resume when `awaited` settles.
2794    fn hook_await(
2795        &mut self,
2796        awaited: Value,
2797        coroutine: &Gc<JsObject>,
2798        promise: &Gc<JsObject>,
2799    ) -> JsResult<()> {
2800        let resumed = JsObject::function(
2801            self.heap,
2802            Some(self.realm.function_proto.clone()),
2803            Callable::AwaitResume {
2804                coroutine: coroutine.clone(),
2805                promise: promise.clone(),
2806                kind: ResumeKind::Next,
2807            },
2808        );
2809        let raised = JsObject::function(
2810            self.heap,
2811            Some(self.realm.function_proto.clone()),
2812            Callable::AwaitResume {
2813                coroutine: coroutine.clone(),
2814                promise: promise.clone(),
2815                kind: ResumeKind::Throw,
2816            },
2817        );
2818        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2819        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2820        let Value::Object(awaited) = &awaited else {
2821            self.jobs.push_back(Job::Resume {
2822                coroutine: coroutine.clone(),
2823                promise: promise.clone(),
2824                kind: ResumeKind::Next,
2825                value: awaited,
2826            });
2827            return Ok(());
2828        };
2829        self.perform_then(
2830            awaited,
2831            Some(Value::Object(resumed)),
2832            Some(Value::Object(raised)),
2833        )?;
2834        Ok(())
2835    }
2836
2837    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2838    /// things an engine keeps outside it — array elements and an array's `length`.
2839    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2840        if let Some(property) = object.own_property_key(key) {
2841            return Some(property);
2842        }
2843        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2844        // be synthesized too — and every one of them is a plain writable, enumerable,
2845        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2846        // `undefined` before this, which made `key-is-numericindex` fail on its own
2847        // side effect check.
2848        //
2849        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2850        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2851        // likewise not elements however numeric they look.
2852        if object.typed_array_element_type().is_some()
2853            && let Some(numeric) = canonical_numeric_index(key)
2854            && numeric.is_finite()
2855            && numeric.fract() == 0.0
2856            && !(numeric == 0.0 && numeric.is_sign_negative())
2857            && numeric >= 0.0
2858            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2859        {
2860            let value = object.typed_array_element(numeric as usize)?;
2861            return Some(Property::data(value));
2862        }
2863        // An array's elements live in their own vector rather than the property table, so
2864        // a descriptor for one has to be synthesized — with the attributes an element has.
2865        if let Some(index) = key.as_str().and_then(array_index)
2866            && let Some(value) = object.array_get(index as usize)
2867            && !matches!(value, Value::Hole)
2868        {
2869            return Some(Property::data(value));
2870        }
2871        // `length` is an own property of an array that is not in its property table
2872        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2873        // and non-enumerable.
2874        if key.as_str() == Some("length")
2875            && let Some(length) = object.array_length()
2876        {
2877            return Some(Property {
2878                value: Some(crate::object::length_value(length)),
2879                writable: object.length_writable(),
2880                enumerable: false,
2881                configurable: false,
2882                getter: None,
2883                setter: None,
2884                descriptor_fields: None,
2885            });
2886        }
2887        None
2888    }
2889
2890    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2891    pub fn object_get_own_property(
2892        &mut self,
2893        object: &Gc<JsObject>,
2894        key: &PropertyKey,
2895    ) -> JsResult<Option<Property>> {
2896        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2897            return Ok(answer);
2898        }
2899        if let Some(exotic) = object.exotic()
2900            && let Some(answer) = exotic.get_own_property(self, object, key)?
2901        {
2902            return Ok(answer);
2903        }
2904        // A mapped `arguments` index is a data property as far as script can see: the
2905        // accessor pair that aliases the parameter is plumbing, and exposing it would
2906        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2907        // report a `get` where the spec has a `[[Value]]`.
2908        if let Some(index) = key.as_str().and_then(crate::object::array_index)
2909            && let Some(cell) = object.mapped_argument_cell(index as usize)
2910        {
2911            // Non-configurable is *not* the default: an ordinary mapped index is
2912            // configurable, and only becomes non-configurable once something
2913            // redefines it. Preserve whatever the property table currently says.
2914            // The attributes come from whatever the property table holds, because they
2915            // can be changed independently of the mapping; only the *value* and the
2916            // data-property *kind* are the accessor's secret.
2917            let flags = Self::ordinary_own_property(object, key);
2918            if let Some(existing) = &flags
2919                && !existing.is_accessor()
2920            {
2921                // Already demapped: the table entry is the answer, not the cell.
2922                return Ok(flags);
2923            }
2924            return Ok(Some(Property {
2925                value: Some(cell.get()),
2926                writable: true,
2927                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2928                configurable: flags.as_ref().is_some_and(|p| p.configurable),
2929                ..Property::default()
2930            }));
2931        }
2932        Ok(Self::ordinary_own_property(object, key))
2933    }
2934
2935    /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
2936    ///
2937    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
2938    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
2939    /// abstract operation here rather than a private helper in `error.rs`.
2940    ///
2941    /// The name is the whole point: the setter must behave as if the prototype were not
2942    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
2943    /// the accessor for every error object in the realm. Everything below follows from that:
2944    ///
2945    /// 1. `thisValue` must be an object — otherwise `TypeError`.
2946    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
2947    ///    accessor's own home an error rather than a self-shadow.
2948    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
2949    ///    either has a string or has made a mistake.
2950    /// 4. An existing *own* property decides the path — an own setter is called, an own
2951    ///    non-writable data property is a `TypeError` — and only a missing own property
2952    ///    falls through to defining one.
2953    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
2954    ///    traps and a non-extensible receiver is a `TypeError`.
2955    ///
2956    /// The installed shape is writable + configurable, not enumerable.
2957    pub fn setter_that_ignores_prototype_properties(
2958        &mut self,
2959        this_value: Value,
2960        home: &Gc<JsObject>,
2961        property_key: &str,
2962        args: &[Value],
2963    ) -> JsResult<Value> {
2964        let Some(receiver) = this_value.as_object().cloned() else {
2965            return Err(self.type_error("setter called on a non-object"));
2966        };
2967        if Gc::ptr_eq(&receiver, home) {
2968            return Err(self.type_error("cannot assign to the accessor's own home object"));
2969        }
2970        // No type check here: §7.3.40 takes an arbitrary `v`, and
2971        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
2972        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
2973        // before calling this.
2974        let value = args.first().cloned().unwrap_or(Value::Undefined);
2975        let key = PropertyKey::from(property_key);
2976        // Step 4: an own property on the receiver changes what happens, and there are three
2977        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
2978        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
2979        // `Set` with `throw = true`, and a test exists for each.
2980        if let Some(existing) = self.object_get_own_property(&receiver, &key)? {
2981            if existing.is_accessor() && existing.setter.is_none() {
2982                // A getter-only own accessor cannot be written through.
2983                return Err(self.type_error("no setter for the own property"));
2984            }
2985            // Everything else — an own data property, or an own accessor *with* a setter —
2986            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
2987            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
2988            // an own user setter receives the value (`setter-own-accessor`), because
2989            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
2990            // setter directly is the difference between one code path and two that can
2991            // disagree.
2992            self.set_property(&receiver, property_key, value.clone())?;
2993            return Ok(Value::Undefined);
2994        }
2995        let property = Property {
2996            value: Some(value.clone()),
2997            writable: true,
2998            // Enumerable, despite the accessor it shadows not being. The reference installs
2999            // it that way and six cases check it (`setter-creates-own-property` and friends).
3000            enumerable: true,
3001            configurable: true,
3002            ..Property::default()
3003        };
3004        if !self.object_define_own_property(&receiver, &key, property)? {
3005            return Err(self.type_error("the receiver refused the definition"));
3006        }
3007        Ok(Value::Undefined)
3008    }
3009
3010    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3011    ///
3012    /// The indices of a typed array are not properties at all — they are bytes in the
3013    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3014    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3015    /// enumerable and configurable, so a definition can only ever change the *value*, and
3016    /// every other descriptor is refused rather than applied.
3017    ///
3018    /// The order of the checks is the spec's, and two of them are load-bearing:
3019    ///
3020    /// * the index is validated **before** the value is converted, because the conversion
3021    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3022    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3023    ///   happens when the index was valid on the way in;
3024    /// * the store is attempted even when the index has gone out of bounds by the time the
3025    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3026    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3027    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3028    ///
3029    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3030    /// the existing element, which is harmless here: every valid index is already
3031    /// writable, enumerable and configurable, so a `false` in the merged property can only
3032    /// have come from the descriptor having named `false`.
3033    fn integer_indexed_define_own_property(
3034        &mut self,
3035        object: &Gc<JsObject>,
3036        numeric: f64,
3037        property: &Property,
3038    ) -> JsResult<bool> {
3039        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3040        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3041        if !typed_array_index_is_valid(object, numeric) {
3042            return Ok(false);
3043        }
3044        // Step 6: the indices are data properties, so an accessor descriptor is refused
3045        // rather than converted. `Object.defineProperty` turns the `false` into a
3046        // `TypeError`; `Reflect.defineProperty` reports it.
3047        if property.is_accessor() {
3048            return Ok(false);
3049        }
3050        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3051        // definition that asks for anything else cannot be honoured.
3052        if !property.writable || !property.enumerable || !property.configurable {
3053            return Ok(false);
3054        }
3055        // Step 10: only a descriptor that names a value stores anything.
3056        let Some(value) = property.value.clone() else {
3057            return Ok(true);
3058        };
3059        let Some(element) = object.typed_array_element_type() else {
3060            return Ok(false);
3061        };
3062        let stored = self.element_value(element, value)?;
3063        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3064            return Err(self.type_error(reason));
3065        }
3066        Ok(true)
3067    }
3068
3069    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3070    pub fn object_define_own_property(
3071        &mut self,
3072        object: &Gc<JsObject>,
3073        key: &PropertyKey,
3074        property: Property,
3075    ) -> JsResult<bool> {
3076        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3077            return Ok(accepted);
3078        }
3079        // A proxy always answers above — with `Some` from its trap, or with `None` when
3080        // the trap is absent, and then the definition belongs to the **target**
3081        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3082        // when there is no trap). Falling through to the ordinary path here defined the
3083        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3084        // property the target never saw.
3085        if object.proxy_state().is_some() {
3086            let Some((target, _handler)) = self.proxy_parts(object)? else {
3087                return Err(self.type_error("cannot use a proxy that has been revoked"));
3088            };
3089            return self.object_define_own_property(&target, key, property);
3090        }
3091        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3092        // they accept exactly one descriptor shape. This has to happen before the
3093        // ordinary path, which would happily store a data property next to the buffer —
3094        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3095        // and `TypedArray/prototype/set` are about this section.
3096        if object.typed_array_element_type().is_some()
3097            && let Some(index) = canonical_numeric_index(key)
3098        {
3099            return self.integer_indexed_define_own_property(object, index, &property);
3100        }
3101        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3102        // non-extensible object. The check lives here rather than in the callers because
3103        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3104        // `Array.prototype.filter` uses to store its result, and a species object made
3105        // non-extensible by its own constructor must make that a `TypeError`
3106        // (`target-array-non-extensible`).
3107        // Note the `is_none()`: an already-present property may still be **redefined** on a
3108        // non-extensible object, and only *adding* one is refused (as Distinct from
3109        // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3110        // properties — testing extensibility before looking for the property made every
3111        // `Object.freeze` of an ordinary object refuse its own second step).
3112        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3113            return Ok(false);
3114        }
3115        // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3116        // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3117        // an omitted field is left alone). Merging here rather than at each call site is
3118        // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3119        // the value and `enumerable` in place.
3120        //
3121        // The merge is a no-op when the property is absent: there is nothing to keep.
3122        let was_partial = property.descriptor_fields.is_some();
3123        let property = match property.descriptor_fields {
3124            None => property,
3125            Some(fields) => {
3126                let base = self.object_get_own_property(object, key)?;
3127                let mut merged = base.clone().unwrap_or_default();
3128                // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3129                // descriptor names, and switching kind discards the other half —
3130                // `{set: f}` on a data property is an accessor with no getter, not a data
3131                // property whose `get` happens to be absent.
3132                let wants_accessor = fields.get || fields.set;
3133                let wants_data = fields.value || fields.writable;
3134                if wants_accessor {
3135                    merged.value = None;
3136                    merged.writable = false;
3137                    merged.getter = property.getter.clone();
3138                    merged.setter = property.setter.clone();
3139                } else if wants_data {
3140                    merged.getter = None;
3141                    merged.setter = None;
3142                    if fields.value {
3143                        merged.value = property.value.clone();
3144                    }
3145                    if fields.writable {
3146                        merged.writable = property.writable;
3147                    }
3148                }
3149                if fields.enumerable {
3150                    merged.enumerable = property.enumerable;
3151                }
3152                if fields.configurable {
3153                    merged.configurable = property.configurable;
3154                }
3155                merged.descriptor_fields = None;
3156                merged
3157            }
3158        };
3159        // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3160        // descriptor. `define_property_on` runs the same check before it calls here, so an
3161        // ordinary object is already covered; what is *not* is the forwarding a proxy does
3162        // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3163        // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3164        // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3165        // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3166        // own define would have refused.
3167        //
3168        // Only partial descriptors are validated here. A whole `Property` passed by an
3169        // internal caller (`Property::data(…)`) carries attributes that say nothing about
3170        // what the descriptor "named", and those callers rely on the write landing.
3171        if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3172            // Every branch below is gated on `!existing.configurable`: a *configurable*
3173            // property may be reshaped however the descriptor likes, which is why an
3174            // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3175            // must succeed. Testing only `writable` refused that and broke
3176            // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3177            let same_kind = existing.is_accessor() == property.is_accessor();
3178            if !same_kind {
3179                // Step 4: a non-configurable property may not change kind.
3180                if !existing.configurable {
3181                    return Ok(false);
3182                }
3183            } else if existing.is_accessor() {
3184                // Step 6: an accessor's halves are its value.
3185                if !existing.configurable
3186                    && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3187                        || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3188                {
3189                    return Ok(false);
3190                }
3191            } else if !existing.configurable && !existing.writable {
3192                // Step 7: a non-configurable *and* non-writable data property's value is
3193                // fixed, and it may not become writable again.
3194                if property.writable {
3195                    return Ok(false);
3196                }
3197                let current = existing.value.clone().unwrap_or(Value::Undefined);
3198                let requested = property.value.clone().unwrap_or(Value::Undefined);
3199                if !current.same_value(&requested) {
3200                    return Ok(false);
3201                }
3202            }
3203            // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3204            // is frozen with it.
3205            if !existing.configurable
3206                && (property.configurable || property.enumerable != existing.enumerable)
3207            {
3208                return Ok(false);
3209            }
3210        }
3211        // A host class that intercepts definitions owns the attributes of the properties it
3212        // defines: `_class`-style storage on the native side is the usual reason.
3213        if let Some(exotic) = object.exotic()
3214            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3215        {
3216            return Ok(accepted);
3217        }
3218        // An array index is stored in the element vector, which can hold a plain value and
3219        // nothing else. An accessor — or a data property with non-default attributes —
3220        // therefore has to live in the property table, and the element slot is blanked so
3221        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3222        // {get})` stored the accessor where no read ever looked, and the array kept
3223        // answering its old value.
3224        // An array's `length` is not stored in the property table, so defining it has to
3225        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3226        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3227        // {value: 1})` reported success and changed nothing.
3228        if key.as_str() == Some("length") && object.is_array() {
3229            // `{writable: false}` on `length` does not change the length, but it does make
3230            // it read-only — after which neither a later `{writable: true}` nor a store
3231            // past the end may succeed.
3232            if property.value.is_none() {
3233                if !object.length_writable() && property.writable {
3234                    return Ok(false);
3235                }
3236                object.set_length_writable(property.writable);
3237                return Ok(true);
3238            }
3239            if !object.length_writable() {
3240                return Ok(false);
3241            }
3242        }
3243        if key.as_str() == Some("length")
3244            && object.is_array()
3245            && let Some(value) = property.value.clone()
3246        {
3247            let requested = value.to_number();
3248            let valid = requested.is_finite()
3249                && requested >= 0.0
3250                && requested.fract() == 0.0
3251                && requested <= u32::MAX as f64;
3252            if !valid {
3253                return Err(self.range_error("invalid array length"));
3254            }
3255            // Truncating deletes the elements above the new length, and a non-configurable
3256            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3257            // makes `a.length = 2` fail rather than quietly drop it.
3258            let current = object.array_length().unwrap_or(0);
3259            let requested = requested as usize;
3260            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3261                return Ok(false);
3262            }
3263            object.array_set_length(self.heap, requested);
3264            return Ok(true);
3265        }
3266        let plain = property.writable
3267            && property.enumerable
3268            && property.configurable
3269            && !property.is_accessor();
3270        if let Some(index) = key.as_str().and_then(array_index)
3271            && object.is_array()
3272        {
3273            // Growing the array needs a writable `length`: after
3274            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3275            // be added.
3276            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3277                return Ok(false);
3278            }
3279            if plain && property.value.is_some() {
3280                // An ordinary element: the vector is where a read looks first, so it has
3281                // to be the vector that changes — unless the index is too far out to be
3282                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3283                // one property, because past its own limit it stores the index as an
3284                // ordinary key. Falling through to `define_key` below is the same choice,
3285                // and the alternative was worse: the store used to be *dropped* and the
3286                // length left at 0, which is a silent wrong answer.
3287                let value = property.value.clone().unwrap_or(Value::Undefined);
3288                object.delete_key(key);
3289                if object.array_set(self.heap, index as usize, value) {
3290                    return Ok(true);
3291                }
3292                // Past the dense limit the element lives in the table like any property.
3293                object.note_element_descriptor();
3294                object.define_key(key, property);
3295                // A sparse store past the dense limit still extends `length`, which is what
3296                // `a[a.length] = v` relies on — but only extends: shortening would delete
3297                // the sparse properties above the index, including this one.
3298                if index as usize + 1 > object.array_length().unwrap_or(0) {
3299                    object.array_set_length(self.heap, index as usize + 1);
3300                }
3301                return Ok(true);
3302            }
3303            // A non-plain element — an accessor, or an attribute that is not the default —
3304            // lives in the table while the slot becomes a hole. Recording it keeps every
3305            // later `a[i] = v` off the dense path, where the write would have shadowed the
3306            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3307            // replace the accessor with a plain data property.
3308            object.note_element_descriptor();
3309            object.define_key(key, property);
3310            // The slot stays, so `length` does not shrink; a hole is not an element, so
3311            // the table entry is now what a read finds.
3312            object.array_set(self.heap, index as usize, Value::Hole);
3313            return Ok(true);
3314        }
3315        object.define_key(key, property);
3316        Ok(true)
3317    }
3318
3319    /// Build a proxy object over `target`, with its traps read from `handler`.
3320    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3321        JsObject::proxy(self.heap, target, handler)
3322    }
3323
3324    /// The `revoke` function for a proxy's slots.
3325    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3326        let revoke = JsObject::function(
3327            self.heap,
3328            Some(self.realm.function_proto.clone()),
3329            Callable::Revoker(slots),
3330        );
3331        // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3332        // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3333        // inherited from `Function.prototype` reads the same but fails the three cases that
3334        // check the own-property list (`revocation-function-{length,name,property-order}`).
3335        revoke.define("length", Property::name_or_length(Value::Int(0)));
3336        revoke.define("name", Property::name_or_length(self.string("")));
3337        revoke
3338    }
3339
3340    /// A new array.
3341    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3342        let array = JsObject::array(
3343            self.heap,
3344            Some(self.realm.array_proto.clone()),
3345            elements.len(),
3346        );
3347        for (index, element) in elements.into_iter().enumerate() {
3348            array.array_set(self.heap, index, element);
3349        }
3350        array
3351    }
3352
3353    /// A new native function object.
3354    ///
3355    /// The observable `name` and `length` are installed as properties here, which is
3356    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3357    /// so `f.name = "x"` behaves like the writable property it is.
3358    /// A native constructor that builds its own instance after validating its arguments.
3359    ///
3360    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3361    /// check runs before `new.target.prototype` is read.
3362    pub fn new_native_ctor(
3363        &self,
3364        name: impl Into<String>,
3365        length: u32,
3366        func: NativeFn,
3367    ) -> Gc<JsObject> {
3368        let function = JsObject::function(
3369            self.heap,
3370            Some(self.realm.function_proto.clone()),
3371            Callable::Native {
3372                func,
3373                own_instance: true,
3374            },
3375        );
3376        function.set_constructible(true);
3377        function.define(
3378            "length",
3379            Property::name_or_length(Value::Int(length as i32)),
3380        );
3381        function.define("name", Property::name_or_length(self.string(name)));
3382        function
3383    }
3384
3385    /// A native constructor that lets `new` build the instance first.
3386    ///
3387    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3388    /// validation that must precede reading `new.target.prototype`, so the object can be
3389    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3390    /// which makes a *method* and therefore not a constructor at all.
3391    pub fn new_native_constructor(
3392        &self,
3393        name: impl Into<String>,
3394        length: u32,
3395        func: NativeFn,
3396    ) -> Gc<JsObject> {
3397        let function = self.new_native(name, length, func);
3398        function.set_constructible(true);
3399        function
3400    }
3401
3402    /// A new host function object: a native closure that carries its own state.
3403    ///
3404    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3405    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3406    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3407    /// this safe: the closure must not capture a `Gc`.
3408    pub fn new_host_function(
3409        &self,
3410        name: impl Into<String>,
3411        length: u32,
3412        func: crate::object::HostFn,
3413    ) -> Gc<JsObject> {
3414        self.new_host_inner(name.into(), length, func, false)
3415    }
3416
3417    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3418    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3419    pub fn new_host_ctor(
3420        &self,
3421        name: impl Into<String>,
3422        length: u32,
3423        func: crate::object::HostFn,
3424    ) -> Gc<JsObject> {
3425        let function = self.new_host_inner(name.into(), length, func, true);
3426        function.set_constructible(true);
3427        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3428        // installs its own methods on it, so it starts as a plain object.
3429        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3430        function.define(
3431            "prototype",
3432            Property {
3433                value: Some(Value::Object(proto)),
3434                writable: true,
3435                enumerable: false,
3436                configurable: false,
3437                ..Property::default()
3438            },
3439        );
3440        function
3441    }
3442
3443    fn new_host_inner(
3444        &self,
3445        name: String,
3446        length: u32,
3447        func: crate::object::HostFn,
3448        own_instance: bool,
3449    ) -> Gc<JsObject> {
3450        let function = JsObject::function(
3451            self.heap,
3452            Some(self.realm.function_proto.clone()),
3453            Callable::Host {
3454                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3455                own_instance,
3456            },
3457        );
3458        function.define(
3459            "length",
3460            Property::name_or_length(Value::Int(length as i32)),
3461        );
3462        function.define("name", Property::name_or_length(self.string(name)));
3463        function
3464    }
3465
3466    /// A callable object with the `length`/`name` a built-in function has, in that order.
3467    ///
3468    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3469    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3470    /// [`JsObject::function`] defines neither, which is why every capability helper built
3471    /// with it reported no own `length` and no own `name` at all.
3472    ///
3473    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3474    /// configurable.
3475    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3476        let function =
3477            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3478        function.define(
3479            "length",
3480            Property::name_or_length(Value::Int(length as i32)),
3481        );
3482        function.define("name", Property::name_or_length(self.string(name)));
3483        function
3484    }
3485
3486    /// A new native function object.
3487    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3488        let function = JsObject::function(
3489            self.heap,
3490            Some(self.realm.function_proto.clone()),
3491            Callable::Native {
3492                func,
3493                own_instance: false,
3494            },
3495        );
3496        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3497        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3498        // `length,name` and this listed `name,length`. A bytecode function already gets it
3499        // the right way round; only native ones were built backwards.
3500        function.define(
3501            "length",
3502            Property::name_or_length(Value::Int(length as i32)),
3503        );
3504        function.define("name", Property::name_or_length(self.string(name)));
3505        function
3506    }
3507
3508    /// A new bound function.
3509    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3510        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3511        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3512        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3513        let constructible = target
3514            .as_object()
3515            .is_some_and(|target| target.is_constructor());
3516        let bound = JsObject::function(
3517            self.heap,
3518            Some(self.realm.function_proto.clone()),
3519            Callable::Bound { target, this, args },
3520        );
3521        bound.set_constructible(constructible);
3522        bound
3523    }
3524
3525    /// A new reference cell.
3526    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3527        Gc::new(self.heap, Cell::new(value))
3528    }
3529
3530    // -- running ------------------------------------------------------------
3531
3532    /// Evaluate `code` as a script body and return its completion value.
3533    /// Compile and run `source` for the engine's own use, returning its completion value.
3534    ///
3535    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3536    /// needs to be a real async function, and the engine already runs those as coroutines,
3537    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3538    ///
3539    /// Differences from [`Self::eval_in_global`], both deliberate:
3540    ///
3541    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3542    ///   being built, and the source is an IIFE that only constructs a closure, so there
3543    ///   is nothing to drain — and draining here would run script-queued jobs in the
3544    ///   middle of `install`.
3545    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3546    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3547    ///   and it should not look like the user wrote something wrong.
3548    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3549        let program = match js_parse::parse_script(source) {
3550            Ok(program) => program,
3551            Err(error) => {
3552                let message = format!("builtin source does not parse: {error}");
3553                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3554            }
3555        };
3556        let mut code = match js_compile::compile_script_with_source(&program, source) {
3557            Ok(code) => code,
3558            Err(error) => {
3559                let message = format!("builtin source does not compile: {}", error.message);
3560                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3561            }
3562        };
3563        // The frame has to name something, and `<builtin>` is what a stack trace through
3564        // this code should say.
3565        code.set_filename("<builtin>");
3566        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3567        let closure_vars = compiled.code.closure_vars.clone();
3568        let env = self.global_env(&closure_vars);
3569        let this = Value::Object(self.realm.global.clone());
3570        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3571    }
3572
3573    /// Run an already-parsed script and drain the microtasks it queued.
3574    ///
3575    /// The drain is what lets an `async` function's body advance past its first `await`
3576    /// before the host sees the result: nothing else pumps the job queue.
3577    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3578        let this = Value::Object(self.realm.global.clone());
3579        self.run_script_with_this(code, this)
3580    }
3581
3582    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3583    ///
3584    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3585    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3586    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3587    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3588    /// state the next script evaluation tripped over.
3589    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3590        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3591        let closure_vars = compiled.code.closure_vars.clone();
3592        let env = self.global_env(&closure_vars);
3593        let callee = Value::Undefined;
3594        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3595        // The script is done, so the microtasks it queued run before the host sees the
3596        // result. Without this an `async` function's body would never advance past its
3597        // first `await`, because nothing else drains the queue.
3598        self.drain_jobs()?;
3599        Ok(result)
3600    }
3601
3602    /// Compile and run `source` in global scope, returning its completion value.
3603    ///
3604    /// This is what `eval` and `new Function` use. Running it as a script means it
3605    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3606    /// for a `Function` body; a *direct* eval that reads a local variable would need
3607    /// the compiler to hand its variable environment over, which is not implemented.
3608    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3609        self.eval_in_global_named(source, EVAL_FILE, false)
3610    }
3611
3612    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3613    ///
3614    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3615    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3616    /// through the code, so they cannot share one constant.
3617    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3618        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3619    }
3620
3621    /// Evaluate `source` as a global script, reported under `file`.
3622    ///
3623    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3624    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3625    /// from inside a C callback, where the interpreter is the running one rather than a
3626    /// context's own.
3627    pub fn eval_in_global_named(
3628        &mut self,
3629        source: &str,
3630        file: &str,
3631        barrier: bool,
3632    ) -> JsResult<Value> {
3633        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3634        // eval-created global binding — configurable, unlike a script's own `var`.
3635        self.eval_depth += 1;
3636        if barrier {
3637            let depth = self.frames.len();
3638            self.trace_barriers.push(depth);
3639        }
3640        let result = self.eval_in_global_inner(source, file);
3641        if barrier {
3642            self.trace_barriers.pop();
3643        }
3644        self.eval_depth -= 1;
3645        result
3646    }
3647
3648    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3649        let compiled = self.compile_global_script(source, file, false)?;
3650        let strict = compiled.strict;
3651        self.run_eval_script(compiled, strict)
3652    }
3653
3654    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3655    ///
3656    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3657    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3658    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3659    /// direct eval's is.
3660    pub fn eval_script_with_this(
3661        &mut self,
3662        source: &str,
3663        file: &str,
3664        this: Value,
3665    ) -> JsResult<Value> {
3666        let program = match js_parse::parse_script(source) {
3667            Ok(program) => program,
3668            Err(error) => {
3669                return Err(Signal::Throw(self.syntax_error_at(
3670                    file,
3671                    error.span.start.line,
3672                    error.span.start.column,
3673                    &error.message,
3674                )));
3675            }
3676        };
3677        let mut compiled = match js_compile::compile_script(&program) {
3678            Ok(compiled) => compiled,
3679            Err(error) => {
3680                return Err(Signal::Throw(self.syntax_error_at(
3681                    file,
3682                    error.span.start.line,
3683                    error.span.start.column,
3684                    &error.message,
3685                )));
3686            }
3687        };
3688        compiled.set_filename(file);
3689        self.run_script_with_this(compiled, this)
3690    }
3691
3692    /// Parse and compile `source` as a global script, without running it.
3693    ///
3694    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3695    /// before a promise exists to reject — while still evaluating in the same eval context
3696    /// (direct-eval strictness, `new.target`, `super`).
3697    fn compile_global_script(
3698        &mut self,
3699        source: &str,
3700        file: &str,
3701        async_body: bool,
3702    ) -> JsResult<CompiledFunction> {
3703        // A *direct* eval inherits the strictness of the code that called it, which is
3704        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3705        // implicit global. The caller's frame is the innermost one here, because a
3706        // native function does not push a frame of its own.
3707        let strict = self.current_strict();
3708        // `eval` runs in the caller's function context, so `new.target` is legal here
3709        // even though the source is a bare script — and so is `super.x` when the caller
3710        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3711        // caller's, which is what `special_object 4` already does.
3712        let context = js_parse::EvalContext {
3713            in_method: self.enclosing_home_object().is_some(),
3714            // `super()` belongs to a derived constructor, and an eval'd body is not a
3715            // constructor at all: the caller frame's `this` is already built.
3716            in_derived_constructor: false,
3717        };
3718        // A *global* eval is not a function body: `new.target` and `super` are out of
3719        // reach there. Its `{async: true}` form differs in the other direction — the body
3720        // may `await` — so the two flags are independent and the reference sets both from
3721        // the eval type rather than from the caller.
3722        let parsed = if async_body {
3723            js_parse::parse_suspensible_global_eval(source, strict)
3724        } else {
3725            js_parse::parse_eval_script_in(source, strict, context)
3726        };
3727        let program = match parsed {
3728            Ok(program) => program,
3729            Err(error) => {
3730                // The message is bare: the position lives in `fileName`,
3731                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3732                // the reference puts it. An `invalid source: L:C: ` prefix made
3733                // `e.message` differ from the reference while the stack already agreed.
3734                return Err(Signal::Throw(self.syntax_error_at(
3735                    file,
3736                    error.span.start.line,
3737                    error.span.start.column,
3738                    &error.message,
3739                )));
3740            }
3741        };
3742        let mut compiled = match if async_body {
3743            js_compile::compile_script_suspensible(&program)
3744        } else {
3745            js_compile::compile_script(&program)
3746        } {
3747            Ok(compiled) => compiled,
3748            // A construct the compiler does not handle yet is reported the same way a
3749            // parse error is: it happens before anything runs, so the trace is the
3750            // position in the source followed by the caller.
3751            Err(error) => {
3752                return Err(Signal::Throw(self.syntax_error_at(
3753                    file,
3754                    error.span.start.line,
3755                    error.span.start.column,
3756                    &error.message,
3757                )));
3758            }
3759        };
3760        compiled.set_filename(file);
3761        Ok(compiled)
3762    }
3763
3764    /// Run an `eval`'d script in the caller's scope.
3765    ///
3766    /// Three things have to come from the calling frame, because the eval'd code is a
3767    /// script and would otherwise see only the global object:
3768    ///
3769    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3770    /// * `arguments`, exposed as a binding of the eval's own scope, so
3771    ///   `f("arguments.length", 1)` sees the caller's arguments;
3772    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3773    ///   `eval("var v = 1")` into the global object.
3774    ///
3775    /// Locals of the calling function are *not* reachable: that needs the compiler to
3776    /// hand its variable environment over, which this milestone does not do.
3777    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3778        // `this` and `arguments` come from the innermost frame only — those are not
3779        // lexical — while the name bindings come from the whole chain of frames, part
3780        // of it being ordinary scope resolution.
3781        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3782        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3783        // read from its closure.
3784        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3785        // variable environment is the innermost frame of all: an arrow's own body is where
3786        // `var`s declared by an `eval` inside it belong.
3787        let caller_index = self
3788            .frames
3789            .iter()
3790            .rposition(|frame| !frame.code.code.is_arrow)
3791            .or_else(|| self.frames.len().checked_sub(1));
3792        let env_index = self.frames.len().checked_sub(1);
3793        let caller = caller_index.and_then(|index| self.frames.get(index));
3794        let (this, passed) = match caller {
3795            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3796            // No frame at all: the eval is running at the top level, so there is
3797            // nothing to inherit and the global receiver is right.
3798            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3799        };
3800        // Innermost frame first, so the first binding found for a name is the one that
3801        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3802        let mut bindings: Vec<EvalBinding> = Vec::new();
3803        // The calling function's own bindings, resolved by the compiler at the call
3804        // site. That table is the only reliable answer when a name is declared twice in
3805        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3806        // body means, and guessing by declaration order picks the wrong one as soon as
3807        // two loops in a row use the same name.
3808        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3809        // every direct call — a bare `eval(...)` callee — so finding one at the current
3810        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3811        // callee to a value first and leave no site behind.
3812        let mut direct = false;
3813        let mut resolved_here = false;
3814        if let Some(frame) = self.frames.last() {
3815            let (line, column) = frame
3816                .code
3817                .code
3818                .position_at(frame.at as u32)
3819                .unwrap_or_default();
3820            // The nearest site at or before the current position, not an exact match:
3821            // the recorded position of the `call` instruction is the callee's, which
3822            // sits a few columns inside the call expression the compiler recorded. A
3823            // site is unique per call, so "the closest one behind us" identifies it.
3824            if let Some(site) = frame
3825                .code
3826                .code
3827                .eval_sites
3828                .iter()
3829                .filter(|site| (site.line, site.column) <= (line, column))
3830                .max_by_key(|site| (site.line, site.column))
3831            {
3832                direct = true;
3833                resolved_here = true;
3834                for binding in &site.bindings {
3835                    // An enclosing function's frame sits `owner` levels below the one
3836                    // running the call.
3837                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3838                    else {
3839                        continue;
3840                    };
3841                    bindings.push(EvalBinding {
3842                        name: binding.name.clone(),
3843                        frame,
3844                        slot: if binding.is_arg {
3845                            EvalSlot::Arg
3846                        } else {
3847                            EvalSlot::Local
3848                        },
3849                        index: binding.index as usize,
3850                    });
3851                }
3852            }
3853        }
3854        for frame_index in (0..self.frames.len()).rev() {
3855            // Skip the innermost frame's flat scan when the compiler already answered
3856            // for it; an enclosing frame still needs one, because the eval resolves
3857            // those names dynamically.
3858            if resolved_here && frame_index == self.frames.len() - 1 {
3859                continue;
3860            }
3861            let frame = &self.frames[frame_index];
3862            for (index, arg) in frame.code.code.args.iter().enumerate() {
3863                bindings.push(EvalBinding {
3864                    name: arg.name.clone(),
3865                    frame: frame_index,
3866                    slot: EvalSlot::Arg,
3867                    index,
3868                });
3869            }
3870            for (index, local) in frame.code.code.vars.iter().enumerate() {
3871                bindings.push(EvalBinding {
3872                    name: local.name.clone(),
3873                    frame: frame_index,
3874                    slot: EvalSlot::Local,
3875                    index,
3876                });
3877            }
3878        }
3879        let mut seen = BTreeSet::new();
3880        bindings.retain(|binding| seen.insert(binding.name.clone()));
3881
3882        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3883        // elements is all the spec's ordinary uses need.
3884        //
3885        // Known divergence: this is bound for a *global* eval too, where there is no
3886        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3887        // needs "does the calling frame have an `arguments` of its own", which is not
3888        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3889        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3890        // the call-site detection does not answer it. Modelled as a binding in the caller's
3891        // variable environment, this would fall out; that is a larger change than the one
3892        // this comment is attached to.
3893        let arguments = Value::Object(self.new_array(passed));
3894
3895        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3896        // declares its `var`s in the caller's — which for a top-level eval is the global
3897        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3898        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3899        // vanish into a scope nobody reads back from.
3900        let previous_scope = if code_strict {
3901            self.eval_scope.replace(BTreeMap::new())
3902        } else {
3903            None
3904        };
3905        let previous_arguments = self.eval_arguments.replace(arguments);
3906        let previous_with = self.eval_with.replace(self.with_objects());
3907        let inherited_new_target = self
3908            .frames
3909            .iter()
3910            .rev()
3911            .find(|frame| !frame.code.code.is_arrow)
3912            .map(|frame| frame.new_target.clone());
3913        let previous_new_target = self
3914            .eval_new_target
3915            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3916        let eval_cells = self.eval_cells_for(&bindings);
3917        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3918        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3919        // `declare_eval_local` needs to know which frame that is.
3920        // An indirect eval gets the global environment, so nothing of the caller's is
3921        // recorded as the place its `var`s belong.
3922        let previous_caller = self
3923            .eval_caller
3924            .replace(if direct { env_index } else { None });
3925        // The cell-based view of the same bindings, which is what a closure created
3926        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3927        // whose compiler did not put a binding in a cell simply does not appear here —
3928        // reads and writes still work through `eval_bindings`, they just cannot outlive
3929        // the eval.
3930        let previous_eval_scope = self
3931            .active_eval_scope
3932            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3933        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3934        let closure_vars = compiled.code.closure_vars.clone();
3935        let env = self.global_env(&closure_vars);
3936        let callee = Value::Undefined;
3937        // An async body does not run here: it becomes a coroutine and answers a promise,
3938        // which is what makes `await` legal in it. `this` still has to be the caller's
3939        // (for a global eval, the global object), because `this` is not part of `await`.
3940        let result = if compiled.code.kind.is_async() {
3941            self.run_async_body(compiled, env, this)
3942        } else {
3943            self.execute(compiled, env, this, Vec::new(), callee)
3944        };
3945        self.eval_scope = previous_scope;
3946        self.eval_arguments = previous_arguments;
3947        self.eval_with = previous_with;
3948        self.eval_new_target = previous_new_target;
3949        self.eval_bindings = previous_bindings;
3950        self.eval_caller = previous_caller;
3951        self.active_eval_scope = previous_eval_scope;
3952        result
3953    }
3954
3955    /// The cell-backed subset of `bindings`, in the same priority order.
3956    ///
3957    /// Both lookup routes have to agree — the eval's own reads go through
3958    /// [`Interp::eval_binding_value`] and the closures it builds go through
3959    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3960    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3961    /// is not in a cell simply does not appear: reads and writes still work, they just
3962    /// cannot be handed to a closure that outlives the eval.
3963    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3964        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3965        for binding in bindings {
3966            let Some(frame) = self.frames.get(binding.frame) else {
3967                continue;
3968            };
3969            let cell = match binding.slot {
3970                EvalSlot::Arg => frame
3971                    .code
3972                    .arg_cell
3973                    .get(binding.index)
3974                    .copied()
3975                    .unwrap_or(-1),
3976                EvalSlot::Local => frame
3977                    .code
3978                    .loc_cell
3979                    .get(binding.index)
3980                    .copied()
3981                    .unwrap_or(-1),
3982            };
3983            if cell < 0 {
3984                continue;
3985            }
3986            if let Some(cell) = frame.cells.get(cell as usize) {
3987                names.push((binding.name.clone(), cell.clone()));
3988            }
3989        }
3990        names
3991    }
3992
3993    /// A `SyntaxError` that reports where in the source it happened.
3994    ///
3995    /// Compile-time failures never run, so they have no frame of their own; the
3996    /// reference still puts the position first in the trace, with no function name and
3997    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3998    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3999    /// reference borrows), which is how a script reads the position without parsing
4000    /// the trace.
4001    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4002    ///
4003    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4004    /// `columnNumber`, which is how the reference prints one. A positionless error
4005    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4006    /// the reference raises it from `js_resolve_module`, where there is no position.
4007    pub(crate) fn syntax_error_plain(
4008        &mut self,
4009        error: &js_parse::SyntaxError,
4010        file: &str,
4011    ) -> Value {
4012        if error.positionless {
4013            return self.make_error("SyntaxError", &error.message);
4014        }
4015        self.syntax_error_at(
4016            file,
4017            error.span.start.line,
4018            error.span.start.column,
4019            &error.message,
4020        )
4021    }
4022
4023    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4024        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
4025        let value = self.make_error("SyntaxError", message);
4026        if let Value::Object(object) = &value {
4027            let text = self.string(blamed);
4028            // `stack` is an own data property, and the reference keeps it
4029            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4030            object.define("stack", Property::with_attributes(text, true, false));
4031            let name = self.string(file);
4032            object.define("fileName", Property::with_attributes(name, true, true));
4033            object.define(
4034                "lineNumber",
4035                Property::with_attributes(Value::Int(line as i32), true, true),
4036            );
4037            object.define(
4038                "columnNumber",
4039                Property::with_attributes(Value::Int(column as i32), true, true),
4040            );
4041        }
4042        value
4043    }
4044
4045    /// Run a compiled script whose completion value is a function, returning it.
4046    ///
4047    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4048    /// get the closure out, which keeps the constant-pool plumbing in one place.
4049    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4050        self.run_script(code)
4051    }
4052
4053    /// The environment of a script or of any function compiled at global scope:
4054    /// every entry is a global binding, so each one resolves to the realm's cell.
4055    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4056        let mut cells = Vec::with_capacity(closure_vars.len());
4057        for closure_var in closure_vars {
4058            let cell = match closure_var.closure_type {
4059                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4060                    if closure_var.is_lexical =>
4061                {
4062                    // A lexical declaration: the cell is created here holding the
4063                    // dead-zone marker, which is what makes the binding exist and
4064                    // unreadable before its initialiser runs.
4065                    self.declare_global(&closure_var.name, closure_var.is_const);
4066                    self.realm.globals[&closure_var.name].clone()
4067                }
4068                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4069                    // A `var` or function declaration becomes a property of the global
4070                    // object, and it exists from here on — which is why
4071                    // `print(v); var v = 1` prints `undefined` instead of raising.
4072                    // Declaring it at instantiation time (rather than at the
4073                    // initialiser) is also what makes it non-configurable: the store
4074                    // then lands on an existing property instead of creating one.
4075                    self.declare_var_global(&closure_var.name);
4076                    // The cell is a placeholder that nothing indexes; it cannot be
4077                    // omitted because the slot has to hold something.
4078                    self.new_cell(Value::Undefined)
4079                }
4080                _ => {
4081                    // An undeclared global is read by name; the cell is a
4082                    // placeholder that nothing indexes.
4083                    self.new_cell(Value::Undefined)
4084                }
4085            };
4086            cells.push(cell);
4087        }
4088        Gc::new(
4089            self.heap,
4090            ClosureEnv {
4091                cells,
4092                eval_scope: None,
4093                local_vars: None,
4094                local_phase: 1,
4095            },
4096        )
4097    }
4098
4099    /// Push a frame and run until it returns.
4100    pub(crate) fn execute(
4101        &mut self,
4102        code: Gc<CompiledCode>,
4103        env: Gc<ClosureEnv>,
4104        this: Value,
4105        args: Vec<Value>,
4106        callee: Value,
4107    ) -> JsResult<Value> {
4108        let depth = self.frames.len();
4109        if depth == 0 {
4110            // A throw that reached the host ends the *active* mode: the next one is catchable
4111            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4112            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4113            // for the throw that evaluation will raise.
4114            self.uncatchable = false;
4115        }
4116        self.push_frame(code, env, this, args, callee)?;
4117        loop {
4118            // The fast loop first: it runs whole runs of records with `pc` in a register.
4119            //
4120            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4121            // reads it again — a store, a load and two bounds checks that a loop body does
4122            // not need, because nothing outside the loop can run in between. This is the
4123            // classic split: advance a register, and only spill it when leaving.
4124            //
4125            // `Some(value)` means the function ended by running off the end of its
4126            // instruction array, which is a normal return.
4127            let step = match self.run_fast() {
4128                Ok(Some(value)) => Ok(Step::Return(value)),
4129                Ok(None) => self.step(),
4130                Err(signal) => Err(signal),
4131            };
4132            match step {
4133                Ok(Step::Continue) => {}
4134                Ok(Step::Return(value)) => {
4135                    self.pop_frame();
4136                    // A frame that ended in a `tail_call` hands its value straight to
4137                    // its caller: nothing after the call can run, so every frame above
4138                    // the callee unwinds with the same value. See [`Frame::tail`] —
4139                    // the reference does not reuse frames either, so recursion depth
4140                    // and the stack-overflow limit behave the same way.
4141                    while self.frames.len() > depth && self.frame().tail {
4142                        self.pop_frame();
4143                    }
4144                    if self.frames.len() == depth {
4145                        return Ok(value);
4146                    }
4147                    // The caller resumes with the value on its stack.
4148                    self.frames
4149                        .last_mut()
4150                        .expect("a caller is live")
4151                        .stack
4152                        .push(value);
4153                }
4154                Err(Signal::Throw(value)) => {
4155                    // The host's standing request becomes the active mode for this unwind,
4156                    // and is consumed here so it does not leak into the next throw.
4157                    if self.uncatchable_next {
4158                        self.uncatchable_next = false;
4159                        self.uncatchable = true;
4160                    }
4161                    // An uncatchable throw walks past every `catch` on the way out. The
4162                    // frames are still popped, because the values they hold have to be
4163                    // dropped — only the search for a handler is skipped.
4164                    if self.uncatchable {
4165                        while self.frames.len() > depth {
4166                            self.frames.pop();
4167                        }
4168                        return Err(Signal::Throw(value));
4169                    }
4170                    // A handler lives on the stack of the frame that is throwing —
4171                    // `catch` pushed it there — so this frame gets the first chance
4172                    // to catch before it is popped.
4173                    let value = value;
4174                    loop {
4175                        if self.frames.len() <= depth {
4176                            return Err(Signal::Throw(value));
4177                        }
4178                        if self.catch_here(value.clone()).is_some() {
4179                            break;
4180                        }
4181                        self.frames.pop();
4182                    }
4183                }
4184                // A `yield` in a frame that `execute` is running directly means a
4185                // generator body was entered as an ordinary call, which only happens if
4186                // the generator check in `call_or_push` was bypassed.
4187                Ok(Step::Suspend(_)) => {
4188                    return Err(Signal::Throw(self.make_error(
4189                        "InternalError",
4190                        "a generator body ran as an ordinary call",
4191                    )));
4192                }
4193                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4194            }
4195        }
4196    }
4197
4198    /// Install a handler for `value` if this frame has one, resuming at it.
4199    ///
4200    /// The scan is the reference's: walk the frame's stack downwards looking for the
4201    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4202    /// `0` is an enumerator marker rather than a handler — it exists so that a
4203    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4204    /// here and the unwinding continues.
4205    fn catch_here(&mut self, value: Value) -> Option<()> {
4206        let frame = self.frames.last_mut()?;
4207        while let Some(top) = frame.stack.pop() {
4208            if let Value::CatchOffset(offset) = top {
4209                if offset == 0 {
4210                    continue;
4211                }
4212                frame.stack.push(value);
4213                frame.pc = offset as usize;
4214                return Some(());
4215            }
4216        }
4217        None
4218    }
4219
4220    fn push_frame(
4221        &mut self,
4222        code: Gc<CompiledCode>,
4223        env: Gc<ClosureEnv>,
4224        this: Value,
4225        mut args: Vec<Value>,
4226        callee: Value,
4227    ) -> JsResult<()> {
4228        // Two bounds, and the byte budget is the one that decides in practice. The
4229        // reference's message is `stack overflow` on an `InternalError`, not V8's
4230        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4231        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4232        let frame_cost = Self::frame_cost(&code);
4233        let stack_base = self.stack_used();
4234        if self.frames.len() >= self.max_frames
4235            || stack_base.saturating_add(frame_cost) > self.stack_limit
4236        {
4237            return Err(Signal::Throw(
4238                self.make_error("InternalError", "stack overflow"),
4239            ));
4240        }
4241        let arg_count = code.code.args.len();
4242        // How many were actually passed, which `arguments.length` reports and
4243        // `assert(x)` depends on: a call with one argument must not look like a call
4244        // with one argument and an explicit `undefined`.
4245        let passed = args.len();
4246        // Missing arguments are `undefined` in their slots; extra ones are dropped
4247        // from the slots but still reachable through `arguments`.
4248        //
4249        // A call that passes no more than the declared parameters needs **no** copy:
4250        // after the resize below, `args[..passed]` *is* the passed values. Only the
4251        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4252        // the rare case. This used to copy every call: one `Value` clone per argument
4253        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4254        let passed_overflow = (passed > arg_count).then(|| {
4255            let mut values = self.take_values(passed, Value::Undefined);
4256            values[..passed].clone_from_slice(&args[..passed]);
4257            values
4258        });
4259        // Only when the counts differ, which for the overwhelmingly common call — as many
4260        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4261        // lengths is two length compares and nothing else, but this is the hottest few
4262        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4263        if passed != arg_count {
4264            args.resize(arg_count, Value::Undefined);
4265            args.truncate(arg_count);
4266        }
4267        let cell_count = code.code.var_ref_count as usize;
4268        let mut cells = Vec::with_capacity(cell_count);
4269        for _ in 0..cell_count {
4270            cells.push(self.new_cell(Value::Undefined));
4271        }
4272        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4273        // A captured argument lives in its cell, not in the argument slot, so the
4274        // incoming value has to be moved there before the body runs.
4275        for (slot, cell) in code.arg_cell.iter().enumerate() {
4276            if *cell >= 0
4277                && let Some(value) = args.get(slot).cloned()
4278            {
4279                cells[*cell as usize].set(value);
4280            }
4281        }
4282        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4283        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4284        // reports `object`. Strict mode passes the value through untouched.
4285        let this = if code.code.strict {
4286            this
4287        } else if this.is_nullish() {
4288            Value::Object(self.realm.global.clone())
4289        } else if matches!(this, Value::Object(_)) {
4290            this
4291        } else {
4292            match crate::builtins::this_object(self, &this) {
4293                Ok(boxed) => Value::Object(boxed),
4294                Err(_) => this,
4295            }
4296        };
4297        let stack_depth = code.code.stack_size as usize + 1;
4298        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4299        // out of the same recycle pool the locals did.
4300        let stack = self.take_values(stack_depth, Value::Undefined);
4301        self.frames.push(Frame {
4302            code,
4303            env,
4304            this,
4305            args,
4306            passed_count: passed,
4307            passed_overflow: passed_overflow.map(Box::new),
4308            locals,
4309            cells,
4310            local_vars: None,
4311            // Exactly the depth the compiler computed, so the operand stack never
4312            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4313            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4314            // the buffer between calls, so "exactly" costs nothing after the first one.
4315            stack,
4316            pc: 0,
4317            at: 0,
4318            callee,
4319            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4320            cost: frame_cost,
4321            stack_base,
4322            tail: false,
4323        });
4324        Ok(())
4325    }
4326
4327    /// A value buffer of `len` slots, from the recycle pool when there is one.
4328    ///
4329    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4330    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4331        // A frame with no locals asks for nothing, and that is most frames: taking a
4332        // buffer out of the pool, clearing it and resizing it to zero is four operations
4333        // and a pool pop for an empty `Vec`, which is free to construct.
4334        if len == 0 {
4335            return Vec::new();
4336        }
4337        let mut buffer = self.free_values.pop().unwrap_or_default();
4338        buffer.clear();
4339        buffer.resize(len, fill);
4340        buffer
4341    }
4342
4343    /// Return a finished frame's value buffers for the next call to reuse.
4344    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4345        for mut buffer in [
4346            std::mem::take(&mut frame.locals),
4347            frame
4348                .passed_overflow
4349                .take()
4350                .map(|buffer| *buffer)
4351                .unwrap_or_default(),
4352            std::mem::take(&mut frame.stack),
4353        ] {
4354            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4355            // GC root: it kept every value the frame held reachable, which is invisible
4356            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4357            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4358            // exactly that within one run — the target `{}` of a finished IIFE was still
4359            // in its operand stack, in the pool.
4360            buffer.clear();
4361            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4362            // fill the pool with nothing to offer.
4363            if free_values.len() < RECYCLE_SLOTS
4364                && buffer.capacity() > 0
4365                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4366            {
4367                free_values.push(buffer);
4368            }
4369        }
4370    }
4371
4372    /// Pop a finished frame and keep its buffers.
4373    ///
4374    /// Every place that drops a frame goes through here: a recycled buffer is also where
4375    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4376    /// nothing but the reuse.
4377    fn pop_frame(&mut self) -> Option<()> {
4378        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4379        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4380        let last = self.frames.len().checked_sub(1)?;
4381        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4382        self.frames.truncate(last);
4383        Some(())
4384    }
4385
4386    /// Poll the host's interrupt handler, if one is installed.
4387    ///
4388    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4389    /// one `Option` test, and with no handler installed the whole function is that test —
4390    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4391    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4392    #[inline]
4393    fn check_interrupt(&mut self) -> JsResult<()> {
4394        if self.interrupt.is_none() {
4395            return Ok(());
4396        }
4397        if self.interrupt_counter > 0 {
4398            self.interrupt_counter -= 1;
4399            return Ok(());
4400        }
4401        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4402        // The closure is taken out for the duration so that a handler which re-enters the
4403        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4404        let mut handler = self.interrupt.take().expect("checked above");
4405        let abort = handler();
4406        self.interrupt = Some(handler);
4407        if abort {
4408            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4409            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4410            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4411            // documentation says.
4412            self.uncatchable = true;
4413            return Err(Signal::Throw(
4414                self.make_error("InternalError", "interrupted"),
4415            ));
4416        }
4417        Ok(())
4418    }
4419
4420    /// A memory checkpoint: does the heap still fit under its limit?
4421    ///
4422    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4423    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4424    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4425    /// only at calls would let it run until the machine died, which is the exact failure
4426    /// `--memory-limit` exists to prevent.
4427    ///
4428    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4429    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4430    /// script that catches it, drops the reference and carries on is legitimate: measured
4431    /// on `qjs --memory-limit 1M`, the engine recovers.
4432    fn check_memory(&mut self) -> JsResult<()> {
4433        // One `Cell` read and a predictable branch when no limit is set, and an integer
4434        // compare when one is. Containers report their own growth as it happens
4435        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4436        // walking it here was the first version and it was O(live) per 256 instructions,
4437        // which turned a 100k-element push loop into a five-minute one.
4438        let Some(limit) = self.heap.memory_limit() else {
4439            return Ok(());
4440        };
4441        let used = self.heap.used_bytes();
4442        if used <= limit {
4443            // Back under the limit — a collection or a dropped reference did it. The next
4444            // time it goes over is a new failure, not a repeat of this one.
4445            self.oom_reported_at = 0;
4446            return Ok(());
4447        }
4448        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4449        // block runs normally after `out of memory` — it allocates nothing, so nothing
4450        // fails. A check that re-fired on every instruction made the handler itself throw,
4451        // which is a dead end: the error became unobservable from script.
4452        //
4453        // Comparing against the total at the last report gives the same behaviour: the
4454        // handler runs while the total is unchanged, and the very next allocation over the
4455        // limit fails.
4456        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4457        {
4458            return Ok(());
4459        }
4460        self.oom_reported_at = used;
4461        Err(Signal::Throw(
4462            self.make_error("InternalError", "out of memory"),
4463        ))
4464    }
4465
4466    /// Fail before allocating `payload` bytes, if they would not fit.
4467    ///
4468    /// For the allocations whose size comes from script data — `new Array(n)`,
4469    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4470    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4471    /// answering NULL for the one big request.
4472    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4473        if self.heap.fits(payload) {
4474            return Ok(());
4475        }
4476        Err(Signal::Throw(
4477            self.make_error("InternalError", "out of memory"),
4478        ))
4479    }
4480
4481    /// Bytes of frame state the live call chain accounts for.
4482    pub fn stack_used(&self) -> usize {
4483        match self.frames.last() {
4484            Some(frame) => frame.stack_base + frame.cost,
4485            None => 0,
4486        }
4487    }
4488
4489    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4490    ///
4491    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4492    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4493    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4494    /// instead. That is the whole difference between the two models: it rations C stack, we
4495    /// ration frame state, and both quantities are dominated by the value slots — which is
4496    /// why the two depths come out comparable rather than merely proportional.
4497    fn frame_cost(code: &CompiledCode) -> usize {
4498        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4499        std::mem::size_of::<Frame>()
4500            + std::mem::size_of::<Value>() * slots
4501            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4502    }
4503
4504    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4505    ///
4506    /// Only names the eval created are here: a name the frame already declared statically
4507    /// is written through to its own slot instead, so this cannot shadow a real local.
4508    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4509        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4510        let (local_vars, phase) = self.visible_local_vars()?;
4511        if !local_vars.contains(name) {
4512            return None;
4513        }
4514        local_vars.get(name, phase)
4515    }
4516
4517    /// The variables a direct `eval` declared, as the code currently running sees them.
4518    ///
4519    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4520    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4521    /// else it is the current frame's, falling back to the frame the closure was created
4522    /// in.
4523    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4524    ///
4525    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4526    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4527    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4528    /// just to be asked `is_none`.
4529    fn has_visible_local_vars(&self) -> bool {
4530        let index = match self.eval_caller.flatten() {
4531            Some(caller) => caller,
4532            None => match self.frames.len().checked_sub(1) {
4533                Some(top) => top,
4534                None => return false,
4535            },
4536        };
4537        match self.frames.get(index) {
4538            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4539            None => false,
4540        }
4541    }
4542
4543    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4544        // While an `eval` runs, its own frame is on top but its variable environment is
4545        // the *caller's* — so the caller is what the lookup has to start from.
4546        let (index, phase) = match self.eval_caller.flatten() {
4547            Some(caller) => (
4548                caller,
4549                if self.in_parameter_list_at(caller) {
4550                    0
4551                } else {
4552                    1
4553                },
4554            ),
4555            None => (
4556                self.frames.len().checked_sub(1)?,
4557                if self.in_parameter_list() { 0 } else { 1 },
4558            ),
4559        };
4560        let frame = self.frames.get(index)?;
4561        // The frame's own variables, or — for an arrow, which has no variable environment
4562        // of its own — the one it was created in, which `ClosureEnv` carries.
4563        if let Some(local_vars) = frame.local_vars.clone() {
4564            return Some((local_vars, phase));
4565        }
4566        frame
4567            .env
4568            .local_vars
4569            .clone()
4570            .map(|local_vars| (local_vars, frame.env.local_phase))
4571    }
4572
4573    /// Whether the innermost frame is still evaluating its parameter list.
4574    ///
4575    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4576    /// and a closure created there may only see that much of [`LocalVars`].
4577    fn in_parameter_list(&self) -> bool {
4578        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4579    }
4580
4581    /// [`Interp::in_parameter_list`] for a specific frame.
4582    fn in_parameter_list_at(&self, frame: usize) -> bool {
4583        let Some(frame) = self.frames.get(frame) else {
4584            return false;
4585        };
4586        let code = &frame.code.code;
4587        if !code.has_parameter_expressions {
4588            return false;
4589        }
4590        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4591        // function as its body and let a direct `eval` act accordingly.
4592        if code.body_start == (0, 0) {
4593            return false;
4594        }
4595        match code.position_at(frame.at as u32) {
4596            Some(position) => position < code.body_start,
4597            None => false,
4598        }
4599    }
4600
4601    fn frame(&self) -> &Frame {
4602        self.frames.last().expect("a frame is live")
4603    }
4604
4605    fn frame_mut(&mut self) -> &mut Frame {
4606        self.frames.last_mut().expect("a frame is live")
4607    }
4608
4609    // -- slot access --------------------------------------------------------
4610
4611    /// Move a local's value out, leaving `undefined` in the slot.
4612    ///
4613    /// `None` for a captured slot: its value lives in a cell shared with every closure
4614    /// that closed over it, so it can never be exclusively ours and must not be taken.
4615    ///
4616    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4617    /// for every read and fatal for this one — a clone is exactly the second handle that
4618    /// rules out growing the string in place.
4619    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4620        let frame = self.frames.last_mut()?;
4621        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4622            return None;
4623        }
4624        frame
4625            .locals
4626            .get_mut(slot)
4627            .map(|value| std::mem::replace(value, Value::Undefined))
4628    }
4629
4630    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4631    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4632    ///
4633    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4634    /// it** — the value is put back before the general path runs — so a `valueOf` that
4635    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4636    /// error as it would have without the fusion. This is why the in-place attempt is a
4637    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4638    /// a wrong answer with a good excuse.
4639    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4640        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4641        // is put back on every path that does not append. An earlier version wrote the two
4642        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4643        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4644        // through with its value already taken and dropped: the general path below then
4645        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4646        // A wrong answer, from an optimisation, with every test green.
4647        if matches!(right, Value::String(_))
4648            && let Some(taken) = self.take_loc(slot)
4649        {
4650            if let Value::String(mut left) = taken {
4651                let appended = match left.get_mut() {
4652                    Some(string) => string.append_in_place(
4653                        // The pattern is the one `matches!` just checked.
4654                        match &right {
4655                            Value::String(text) => text,
4656                            _ => unreachable!("guarded above"),
4657                        },
4658                    ),
4659                    None => None,
4660                };
4661                self.put_loc(slot, Value::String(left));
4662                if let Some(added) = appended {
4663                    // The buffer grew where it stood, so the heap's running total has to
4664                    // be told: `measure_used` would report the new length, and the two must
4665                    // agree or the subtraction at free time leaves the counter wrong.
4666                    self.heap.adjust_payload(added as isize);
4667                    return Ok(());
4668                }
4669            } else {
4670                self.put_loc(slot, taken);
4671            }
4672        }
4673        // The two-number case, without an operand stack round trip. Everything below
4674        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4675        // store it — five operations and two `Value` clones for what is one integer add.
4676        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4677        // for string append and never got the numeric half, so `t += i` — a counting loop
4678        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4679        let left = self.get_loc(slot);
4680        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4681            self.put_loc(
4682                slot,
4683                match a.checked_add(*b) {
4684                    Some(sum) => Value::Int(sum),
4685                    None => Value::Float(*a as f64 + *b as f64),
4686                },
4687            );
4688            return Ok(());
4689        }
4690        self.push(left);
4691        self.push(right);
4692        self.binary_add()?;
4693        let value = self.pop();
4694        self.put_loc(slot, value);
4695        Ok(())
4696    }
4697
4698    fn get_arg(&self, slot: usize) -> Value {
4699        self.frame().read_arg(slot)
4700    }
4701
4702    fn put_arg(&mut self, slot: usize, value: Value) {
4703        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4704        if cell == -1 {
4705            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4706                *slot = value;
4707            }
4708        } else {
4709            self.frame().cells[cell as usize].set(value);
4710        }
4711    }
4712
4713    fn get_loc(&self, slot: usize) -> Value {
4714        // The cell mapping is `-1` for every slot that was not captured — which is all of
4715        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4716        // so the common case is one array read and a clone: 20% of every loop iteration
4717        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4718        // sample of `dispatch:arith`).
4719        self.frame().read_loc(slot)
4720    }
4721
4722    fn put_loc(&mut self, slot: usize, value: Value) {
4723        // One borrow instead of three, and the cell check on the frame we already hold.
4724        let frame = self.frames.last_mut().expect("a frame is live");
4725        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4726        if cell < 0 {
4727            if let Some(slot) = frame.locals.get_mut(slot) {
4728                *slot = value;
4729            }
4730        } else if let Some(cell) = frame.cells.get(cell as usize) {
4731            cell.set(value);
4732        }
4733    }
4734
4735    // -- globals ------------------------------------------------------------
4736
4737    /// The name a global-slot operand refers to.
4738    fn global_name(&self, slot: usize) -> String {
4739        self.frame()
4740            .code
4741            .code
4742            .closure_vars
4743            .get(slot)
4744            .map(|c| c.name.clone())
4745            .unwrap_or_default()
4746    }
4747
4748    /// The facts about a global binding that decide where it lives.
4749    ///
4750    /// A script's globals split in two, and the split is observable: `var` and
4751    /// function declarations become properties of the global object (`globalThis.v`
4752    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4753    /// declarations live in the global *lexical* environment and are invisible there
4754    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4755    /// `is_lexical` flag means the answer is already in the bytecode.
4756    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4757        let name = self.global_name(slot);
4758        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4759        // while forwarding a reference through a nested function is built with the
4760        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4761        // closure. Presence in the realm's lexical table is the same fact, recorded
4762        // once, and every slot sees it.
4763        let lexical = self.realm.globals.contains_key(&name);
4764        let is_const = self.realm.lexical_consts.contains(&name);
4765        (name, lexical, is_const)
4766    }
4767
4768    /// The value of `name` in the innermost active `with` object, if any.
4769    ///
4770    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4771    /// innermost frame first and innermost block first within one. Walking frames rather
4772    /// than keeping a separate stack is what makes a closure called from inside a `with`
4773    /// see it, and what keeps the object alive only as long as the block is.
4774    /// The innermost active `with` object that has `name`, if any.
4775    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4776        let objects = self.eval_with.clone().unwrap_or_default();
4777        for object in objects {
4778            let key = self.string(name.to_string());
4779            if self
4780                .has_property(&key, &Value::Object(object.clone()))
4781                .ok()?
4782            {
4783                return Some(object);
4784            }
4785        }
4786        None
4787    }
4788
4789    /// Every active `with` object, innermost first.
4790    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4791        let mut objects = Vec::new();
4792        for frame in self.frames.iter().rev() {
4793            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4794                if var.kind != js_compile::VarKind::With {
4795                    continue;
4796                }
4797                // A captured binding lives in its cell and not in the slot list, so the
4798                // cell is consulted first — a closure created inside the block is exactly
4799                // what makes the object captured. Before the store runs the slot still
4800                // holds `undefined`, and a `with` object is always boxed, so a non-object
4801                // entry is simply not in scope yet.
4802                let value = frame
4803                    .code
4804                    .loc_cell
4805                    .get(index)
4806                    .copied()
4807                    .filter(|cell| *cell >= 0)
4808                    .and_then(|cell| frame.cells.get(cell as usize))
4809                    .map(|cell| cell.get())
4810                    .or_else(|| frame.locals.get(index).cloned());
4811                if let Some(Value::Object(object)) = value {
4812                    objects.push(object);
4813                }
4814            }
4815        }
4816        objects
4817    }
4818
4819    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4820        for object in self.eval_with.clone().unwrap_or_default() {
4821            let key = self.string(name.to_string());
4822            if self.has_property(&key, &Value::Object(object.clone()))? {
4823                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4824            }
4825        }
4826        Ok(None)
4827    }
4828
4829    /// Whether every scope between here and the global object is an ordinary one.
4830    ///
4831    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4832    /// bytecode resolved; when any is live the general path has to run in full order. When
4833    /// none is — every ordinary program — a global read is a property read and nothing
4834    /// else, and that is worth caching.
4835    fn scopes_are_plain(&self) -> bool {
4836        self.eval_caller.is_none()
4837            && self.eval_with.is_none()
4838            && self.eval_arguments.is_none()
4839            && self.eval_bindings.is_empty()
4840            && self.eval_scope.is_none()
4841            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4842            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4843            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4844            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4845            // upstream corpus caught and no unit test did.
4846            && !self.has_visible_local_vars()
4847            && self.frame().env.eval_scope.is_none()
4848    }
4849
4850    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4851        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4852        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4853        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4854        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4855        // borrow outlive the `&mut self` the lookup needs.
4856        //
4857        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4858        // forwarded through a nested function has its flags cleared, so the flag cannot
4859        // be believed.
4860        let code = self.frame().code.clone();
4861        let name = code
4862            .code
4863            .closure_vars
4864            .get(slot)
4865            .map(|c| c.name.as_str())
4866            .unwrap_or_default();
4867        let lexical = self.realm.globals.contains_key(name);
4868        // The common case, first: an ordinary global `var`, with a cache in front of the
4869        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4870        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4871        // cache hit and return without touching any of it.
4872        if !lexical && self.scopes_are_plain() {
4873            return self.get_plain_global(name, slot);
4874        }
4875        if name == "arguments"
4876            && let Some(arguments) = &self.eval_arguments
4877        {
4878            return Ok(arguments.clone());
4879        }
4880        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4881        // the objects live when the eval started are consulted before anything else. The
4882        // snapshot is taken at entry rather than scanning the frames on every read: a
4883        // block that has already finished still leaves its object in the slot, and a
4884        // bytecode read outside the block must not see it.
4885        if let Some(value) = self.with_lookup(name)? {
4886            return Ok(value);
4887        }
4888        // A variable a direct `eval` declared shadows everything the compiler resolved,
4889        // including an enclosing function's binding: the eval put it in the caller's own
4890        // variable environment, which is nearer than any captured scope.
4891        if let Some((local_vars, phase)) = self.visible_local_vars()
4892            && let Some(cell) = local_vars.get(name, phase)
4893        {
4894            return Ok(cell.get());
4895        }
4896        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4897        // its local `a` wins over a global `a`.
4898        if let Some(value) = self.eval_binding_value(name) {
4899            return Ok(value);
4900        }
4901        // A closure created by an `eval` resolves its free names against the bindings
4902        // that eval saw, even after the eval (and its frames) are gone.
4903        if let Some(cell) = self
4904            .frame()
4905            .env
4906            .eval_scope
4907            .as_ref()
4908            .and_then(|scope| scope.get(name))
4909        {
4910            let value = cell.get();
4911            if matches!(value, Value::Uninitialized) {
4912                return Err(self.throw_reference(name));
4913            }
4914            return Ok(value);
4915        }
4916        // A binding declared by the strict `eval` currently running shadows anything
4917        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4918        if let Some(scope) = &self.eval_scope
4919            && let Some(value) = scope.get(name)
4920        {
4921            return Ok(value.clone());
4922        }
4923        if lexical {
4924            // A lexical global is a binding in a side table, so the dead zone is
4925            // visible and it is nowhere on the global object.
4926            if let Some(cell) = self.realm.globals.get(name) {
4927                let value = cell.get();
4928                if matches!(value, Value::Uninitialized) {
4929                    return Err(self.throw_reference(name));
4930                }
4931                return Ok(value);
4932            }
4933            return Err(self.throw_reference(name));
4934        }
4935        // A `var` global is an ordinary property, so the prototype chain and the
4936        // global object's own builtins are all reachable through it.
4937        match self.get_property(&self.realm.global.clone(), name)? {
4938            Some(value) => Ok(value),
4939            None => Err(self.throw_reference(name)),
4940        }
4941    }
4942
4943    /// Read a plain global `var`: a cached own data property, or the full lookup.
4944    ///
4945    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4946    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4947    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4948        let object = self.realm.global.clone();
4949        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4950        if let Some(cached) = &self.global_cache[site]
4951            && object.upgrades_to(&cached.object)
4952            && let Some(value) = object.data_property_at(cached.index, name)
4953        {
4954            return Ok(value);
4955        }
4956        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4957        // chain exactly as before, then remember the answer if it is worth remembering.
4958        let Some(value) = self.get_property(&object, name)? else {
4959            return Err(self.throw_reference(name));
4960        };
4961        if let Some(index) = object.own_data_index(name) {
4962            self.global_cache[site] = Some(GlobalCache {
4963                object: object.downgrade(),
4964                index,
4965            });
4966        }
4967        Ok(value)
4968    }
4969
4970    /// Store to a global binding.
4971    ///
4972    /// Returns a signal when the store is refused: a `const` global may only be
4973    /// written by its initialiser, and a non-configurable `var` global may not be
4974    /// deleted but is always writable.
4975    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4976        let (name, lexical, is_const) = self.global_binding(slot);
4977
4978        // An assignment inside a `with` writes through to the object that supplies the
4979        // name, which for an `eval` means consulting the same chain `get_global` does.
4980        if let Some(owner) = self.with_owner(&name) {
4981            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4982            return Ok(());
4983        }
4984        // A variable the running eval *declared* takes the write before any caller
4985        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4986        // environment even when an enclosing function has a `var c` of its own.
4987        if self.eval_caller.flatten().is_some()
4988            && let Some((local_vars, phase)) = self.visible_local_vars()
4989            && local_vars.contains(&name)
4990            && let Some(cell) = local_vars.get(&name, phase)
4991        {
4992            cell.set(value);
4993            return Ok(());
4994        }
4995        // A binding of the frame that called `eval` takes the write, which is what
4996        // makes `f("a = 3")` change the caller's `a`.
4997        if self.set_eval_binding(&name, &value)? {
4998            return Ok(());
4999        }
5000        // A closure that outlived its `eval` writes through to the same cell it reads.
5001        if let Some(cell) = self
5002            .frame()
5003            .env
5004            .eval_scope
5005            .as_ref()
5006            .and_then(|scope| scope.get(&name))
5007            .cloned()
5008        {
5009            cell.set(value);
5010            return Ok(());
5011        }
5012        // Inside a strict `eval`, a name it declared itself is stored there. An
5013        // *assignment* to a name nobody declared is not a declaration, so it falls
5014        // through: strict mode raises `ReferenceError` for it, which is what
5015        // `eval("1 + (@not_def = 1)")` has to do.
5016        if let Some(scope) = self.eval_scope.as_mut()
5017            && scope.contains_key(&name)
5018        {
5019            scope.insert(name, value);
5020            return Ok(());
5021        }
5022        if lexical {
5023            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5024                if is_const && !matches!(cell.get(), Value::Uninitialized) {
5025                    return Err(self.read_only_global(&name));
5026                }
5027                cell.set(value);
5028                return Ok(());
5029            }
5030            // Writing an undeclared lexical global is a `ReferenceError` in strict
5031            // mode and a silent global creation otherwise; creating the cell here
5032            // keeps both paths from losing the value.
5033            let cell = self.new_cell(value);
5034            self.realm.globals.insert(name, cell);
5035            return Ok(());
5036        }
5037        // A variable a direct `eval` declared in this call shadows the global object, even
5038        // when the global already has a property of that name — `var c = "global"` at the
5039        // top level must not capture `eval("var c = 1")` inside a function.
5040        if let Some((local_vars, phase)) = self.visible_local_vars()
5041            && local_vars.contains(&name)
5042            && let Some(cell) = local_vars.get(&name, phase)
5043        {
5044            cell.set(value);
5045            return Ok(());
5046        }
5047        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5048        // remembered a global's slot index since M12b, but the *store* side never did: it
5049        // converted the name to a `PropertyKey` (two allocations) and then scanned the
5050        // global object's whole table — which holds every builtin — on every assignment to
5051        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5052        // full global lookup per iteration; measured with a counter, `s` as a global made
5053        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5054        //
5055        // Re-validated exactly like the read: same object, same index, still the name, and
5056        // — the one extra check a store needs — still writable. A global that is an
5057        // accessor, non-writable, or inherited fails here and falls through to the full
5058        // path below, which reports the failure the way it always did.
5059        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5060        let global = self.realm.global.clone();
5061        if let Some(cached) = &self.global_cache[site]
5062            && global.upgrades_to(&cached.object)
5063            && global.write_data_at(cached.index, &name, value.clone())
5064        {
5065            return Ok(());
5066        }
5067        match global.own_property(&name) {
5068            // A `var` global is writable, so the store goes straight through — but
5069            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5070            // store (a non-writable or accessor-without-setter global) is a silent
5071            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5072            // split every other assignment has.
5073            Some(_) => {
5074                let on_failure = if self.current_strict() {
5075                    DeleteFailure::Throw
5076                } else {
5077                    DeleteFailure::Ignore
5078                };
5079                let result = self.set_property_with(&global, &name, value, on_failure);
5080                // Teach the cache the slot for a plain writable own data property, which is
5081                // what a declared `var` is. Without this the fast path above could never
5082                // fire for a global that is only ever *written* — its entry would have to
5083                // be put there by a read of the same slot, and a write-only loop has none.
5084                if result.is_ok()
5085                    && let Some(index) = global.own_data_index(&name)
5086                {
5087                    self.global_cache[site] = Some(GlobalCache {
5088                        object: global.downgrade(),
5089                        index,
5090                    });
5091                }
5092                result
5093            }
5094            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5095            // declaration creates a *configurable* property, which is what makes it
5096            // deletable and is the one way a global differs from a declared `var`.
5097            // In strict mode the same store is a `ReferenceError` instead: that is the
5098            // whole point of strict mode, and creating the global silently meant
5099            // `"use strict"; x = 1` looked like it worked.
5100            None => {
5101                if self.current_strict() {
5102                    return Err(self.throw_reference(&name));
5103                }
5104                // A direct eval declares here rather than on the global object: its
5105                // `var`s belong to the caller's variable environment. `declare_eval_local`
5106                // also covers a plain assignment to a variable an earlier eval made.
5107                if let Some(cell) = self.declare_eval_local(&name) {
5108                    cell.set(value);
5109                    return Ok(());
5110                }
5111                global.define_data(&name, value);
5112                Ok(())
5113            }
5114        }
5115    }
5116
5117    /// The value of a binding of the frame that called `eval`, if there is one.
5118    fn eval_binding_value(&self, name: &str) -> Option<Value> {
5119        let binding = self
5120            .eval_bindings
5121            .iter()
5122            .find(|binding| binding.name == name)?;
5123        let owner = self.frames.get(binding.frame)?;
5124        let (slot, index) = (binding.slot, binding.index);
5125        Some(match slot {
5126            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5127                cell if cell >= 0 => owner
5128                    .cells
5129                    .get(cell as usize)
5130                    .map(|cell| cell.get())
5131                    .unwrap_or(Value::Undefined),
5132                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5133            },
5134            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5135                cell if cell >= 0 => owner
5136                    .cells
5137                    .get(cell as usize)
5138                    .map(|cell| cell.get())
5139                    .unwrap_or(Value::Undefined),
5140                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5141            },
5142        })
5143    }
5144
5145    /// Write to a binding of the frame that called `eval`.
5146    ///
5147    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5148    /// matched binding can still refuse the store, which is why this is fallible: a
5149    /// `const` is read-only everywhere, and a named function expression's own name is
5150    /// read-only in strict mode.
5151    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5152        let Some(binding) = self
5153            .eval_bindings
5154            .iter()
5155            .find(|binding| binding.name == name)
5156        else {
5157            return Ok(false);
5158        };
5159        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5160        let strict = self.current_strict();
5161        let Some(owner) = self.frames.get_mut(frame) else {
5162            return Ok(false);
5163        };
5164        match slot {
5165            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5166                cell if cell >= 0 => {
5167                    if let Some(cell) = owner.cells.get(cell as usize) {
5168                        cell.set(value.clone());
5169                    }
5170                }
5171                _ => {
5172                    if let Some(slot) = owner.args.get_mut(index) {
5173                        *slot = value.clone();
5174                    }
5175                }
5176            },
5177            EvalSlot::Local => {
5178                let declared = owner.code.code.vars.get(index);
5179                // A `const` is read-only even through `eval`. The realm records this for
5180                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5181                // the bytecode, so this is where it has to be enforced.
5182                if declared.is_some_and(|var| var.is_const) {
5183                    return Err(self.read_only_local(name));
5184                }
5185                // The name of a named function expression is read-only too, but only
5186                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5187                // such a name is ignored, the same as a direct store would be.
5188                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5189                    return if strict {
5190                        Err(self.read_only_local(name))
5191                    } else {
5192                        Ok(true)
5193                    };
5194                }
5195                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5196                    cell if cell >= 0 => {
5197                        if let Some(cell) = owner.cells.get(cell as usize) {
5198                            cell.set(value.clone());
5199                        }
5200                    }
5201                    _ => {
5202                        if let Some(slot) = owner.locals.get_mut(index) {
5203                            *slot = value.clone();
5204                        }
5205                    }
5206                }
5207            }
5208        }
5209        Ok(true)
5210    }
5211
5212    /// The `TypeError` an assignment to a read-only binding raises.
5213    fn read_only_local(&self, name: &str) -> Signal {
5214        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5215    }
5216
5217    /// Declare `name` as a variable of the frame that called the running `eval`.
5218    ///
5219    /// `None` when there is no direct eval in progress, or it was called from the top
5220    /// level — then the caller's variable environment *is* the global one and the
5221    /// existing path is right.
5222    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5223        let caller = self.eval_caller.flatten()?;
5224        // The bottom frame is the top-level script, whose variable environment *is* the
5225        // global one — so `eval("var x = 1")` at the top level still creates a global.
5226        if caller == 0 {
5227            return None;
5228        }
5229        // A name the eval's *own* variable environment already binds is not a new
5230        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5231        // `arguments`, and creating a second binding would leave the first — the one
5232        // closures read — untouched. A binding of an *outer* frame does not count: a
5233        // declaration shadows it rather than writing through.
5234        if self
5235            .eval_bindings
5236            .iter()
5237            .any(|binding| binding.name == name && binding.frame == caller)
5238        {
5239            return None;
5240        }
5241        let phase = if self.in_parameter_list_at(caller) {
5242            0
5243        } else {
5244            1
5245        };
5246        self.frame_local_vars(caller)?;
5247        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5248        if let Some(cell) = local_vars.get(name, 1) {
5249            return Some(cell);
5250        }
5251        let cell = self.new_cell(Value::Undefined);
5252        Some(local_vars.declare(name, phase, cell))
5253    }
5254
5255    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5256    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5257        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5258            return Some(local_vars.clone());
5259        }
5260        let local_vars = Gc::new(self.heap, LocalVars::new());
5261        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5262        Some(local_vars)
5263    }
5264
5265    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5266    /// property of the global object. Used to decide whether a store inside an
5267    /// `eval` writes through to the realm or declares a binding of its own.
5268    ///
5269    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5270    /// write to `Object.prototype.toString`, and must not shadow it either.
5271    fn global_knows(&mut self, name: &str) -> bool {
5272        if self.realm.globals.contains_key(name) {
5273            return true;
5274        }
5275        self.realm.global.own_property(name).is_some()
5276    }
5277
5278    /// Whether the code currently running is strict.
5279    ///
5280    /// Read off the frame's function, which is where the parser's answer ended up; a
5281    /// native function never runs strict-only checks, and there is no frame at all
5282    /// before the first script.
5283    pub fn current_strict(&self) -> bool {
5284        self.frames
5285            .last()
5286            .is_some_and(|frame| frame.code.code.strict)
5287    }
5288
5289    /// Initialise a declared global, which is what ends its dead zone.
5290    ///
5291    /// A `var` global becomes a property of the global object: writable, so a later
5292    /// assignment goes through, and non-configurable, so `delete` refuses.
5293    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5294        let (name, lexical, _) = self.global_binding(slot);
5295        // A `var` declared by the strict `eval` currently running belongs to the
5296        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5297        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5298        // initialised in place, which is what a re-declaration inside eval does.
5299        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5300            self.eval_scope
5301                .as_mut()
5302                .expect("checked above")
5303                .insert(name, value);
5304            return Ok(());
5305        }
5306        if let Some(scope) = self.eval_scope.as_mut()
5307            && scope.contains_key(&name)
5308        {
5309            scope.insert(name, value);
5310            return Ok(());
5311        }
5312        if lexical {
5313            // The cell exists (created at declaration time) holding the dead-zone
5314            // marker; storing the value is what makes the binding readable.
5315            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5316                cell.set(value);
5317                return Ok(());
5318            }
5319            let cell = self.new_cell(value);
5320            self.realm.globals.insert(name, cell);
5321            return Ok(());
5322        }
5323        let global = self.realm.global.clone();
5324        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5325        // to answer `false` and leave the binding in place. `with_attributes` ties
5326        // `configurable` to `writable`, so the property is built field by field.
5327        global.define(
5328            &name,
5329            Property {
5330                value: Some(value),
5331                writable: true,
5332                enumerable: true,
5333                configurable: false,
5334                ..Property::default()
5335            },
5336        );
5337        Ok(())
5338    }
5339
5340    /// The `TypeError` a store to a `const` global raises.
5341    fn read_only_global(&self, name: &str) -> Signal {
5342        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5343    }
5344
5345    // -- properties ---------------------------------------------------------
5346
5347    /// Read `object[key]`, following the prototype chain.
5348    ///
5349    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5350    /// lookup returns the owner rather than just the value.
5351    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5352        self.get_property_key(object, &PropertyKey::from(key))
5353    }
5354
5355    /// [`Interp::get_property`] with a key that may be a symbol.
5356    pub fn get_property_key(
5357        &mut self,
5358        object: &Gc<JsObject>,
5359        key: &PropertyKey,
5360    ) -> JsResult<Option<Value>> {
5361        self.get_property_key_for(object, None, key)
5362    }
5363
5364    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5365    ///
5366    /// The receiver matters when the property is found on a *prototype*: a getter has to
5367    /// see the object the read started from. For a primitive that is the primitive
5368    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5369    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5370    /// the owner.
5371    pub fn get_property_key_for(
5372        &mut self,
5373        object: &Gc<JsObject>,
5374        receiver: Option<&Value>,
5375        key: &PropertyKey,
5376    ) -> JsResult<Option<Value>> {
5377        // A proxy answers for itself, before any of the shortcuts below: `new
5378        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5379        // have.
5380        if object.proxy_state().is_some() {
5381            let receiver = receiver
5382                .cloned()
5383                .unwrap_or_else(|| Value::Object(object.clone()));
5384            return self.proxy_get(object, &receiver, key);
5385        }
5386        // A host class's `get_property` trap replaces the whole read, prototype walk
5387        // included — that is what makes a native accessor free rather than a JavaScript
5388        // getter call.
5389        if let Some(exotic) = object.exotic() {
5390            let receiver_value = receiver
5391                .cloned()
5392                .unwrap_or_else(|| Value::Object(object.clone()));
5393            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5394                return Ok(Some(value));
5395            }
5396            // With no `get_property` trap, a `get_own_property` trap still answers for the
5397            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5398            // and the hook lives exactly there. A key the trap reports as absent is still
5399            // looked for on the prototype, which is why the search resumes *above*.
5400            if let Some(property) = exotic.get_own_property(self, object, key)? {
5401                return match property {
5402                    Some(property) => self.read_property(property, object, receiver),
5403                    None => match lookup_key_above(object, key) {
5404                        Some((_, property)) => self.read_property(property, object, receiver),
5405                        None => Ok(None),
5406                    },
5407                };
5408            }
5409        }
5410        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5411        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5412        // The `[[Get]]` short-circuit therefore belongs to this one arm.
5413        //
5414        // Constructibility is exactly the split the reference makes: `function f(){}` and
5415        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5416        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5417        // function" — it *is* the predicate, which is why no extra marker is needed.
5418        if let Some(text) = key.as_str()
5419            && (text == "caller" || text == "arguments")
5420            && object.is_constructor()
5421            && object.is_callable()
5422            && !object.is_bound_function()
5423            && object.own_property(text).is_none()
5424        {
5425            return Ok(Some(Value::Undefined));
5426        }
5427        // The element-vector and `length` shortcuts are string-only: an array index
5428        // has no symbol spelling.
5429        if let Some(text) = key.as_str() {
5430            if let Some(value) = self.own_element(object, text) {
5431                return Ok(Some(value));
5432            }
5433            // `length` is not stored as a property: an array's length is its element
5434            // count, and keeping one copy of it is what makes `push`/`pop` and
5435            // `a.length = n` agree.
5436            if let Some(length) = object.array_length()
5437                && text == "length"
5438            {
5439                // Not `Value::Int(length as i32)`: see [`length_value`].
5440                return Ok(Some(crate::object::length_value(length)));
5441            }
5442        }
5443        // A proxy or a hooked exotic object anywhere above `object` makes the static
5444        // table walk below wrong: a proxy's own table is *empty by design* (the properties
5445        // live on its target), so the walk skipped that link entirely and everything behind
5446        // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5447        // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5448        // -target-is-proxy.js` are the four.
5449        if Self::chain_needs_dispatch(object) {
5450            return self.walk_get(object, receiver, key);
5451        }
5452        match lookup_key(object, key) {
5453            Some((_, property)) => self.read_property(property, object, receiver),
5454            None => Ok(None),
5455        }
5456    }
5457
5458    /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5459    /// answer for itself.
5460    ///
5461    /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5462    /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5463    /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5464    /// an inherited getter the object the read started from.
5465    fn walk_get(
5466        &mut self,
5467        start: &Gc<JsObject>,
5468        receiver: Option<&Value>,
5469        key: &PropertyKey,
5470    ) -> JsResult<Option<Value>> {
5471        let receiver = receiver
5472            .cloned()
5473            .unwrap_or_else(|| Value::Object(start.clone()));
5474        let mut current = Some(start.clone());
5475        while let Some(holder) = current {
5476            // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5477            // has to ask it, not read its (empty) own-property table. `Object.create(new
5478            // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5479            // instead found nothing.
5480            if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5481                return Ok(Some(value));
5482            }
5483            // A host class's `get_property` trap replaces the whole read for that holder,
5484            // prototype walk included — the same rule `get_property_key_for` applies to the
5485            // first object.
5486            if let Some(exotic) = holder.exotic()
5487                && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5488            {
5489                return Ok(Some(value));
5490            }
5491            if let Some(property) = self.object_get_own_property(&holder, key)? {
5492                return self.read_property(property, &holder, Some(&receiver));
5493            }
5494            current = self.object_prototype_of(&holder)?;
5495        }
5496        Ok(None)
5497    }
5498
5499    /// Whether `object` or anything above it has properties that cannot be read out of a
5500    /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5501    ///
5502    /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5503    /// is the hot path for every property read; this is the check that decides whether it
5504    /// is safe to take it.
5505    fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5506        object
5507            .chain()
5508            .iter()
5509            .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5510    }
5511
5512    /// The value a property read answers.
5513    ///
5514    /// One place rather than three, because an accessor has to run with the *receiver* as
5515    /// `this` whether the descriptor came from the property table, an exotic
5516    /// `get_own_property` trap, or a prototype above one.
5517    fn read_property(
5518        &mut self,
5519        property: Property,
5520        object: &Gc<JsObject>,
5521        receiver: Option<&Value>,
5522    ) -> JsResult<Option<Value>> {
5523        if property.is_accessor() {
5524            match &property.getter {
5525                Some(getter) if !matches!(getter, Value::Undefined) => {
5526                    let receiver = receiver
5527                        .cloned()
5528                        .unwrap_or_else(|| Value::Object(object.clone()));
5529                    self.call_value(getter.clone(), receiver, Vec::new())
5530                        .map(Some)
5531                }
5532                // An accessor with no getter reads as `undefined`.
5533                _ => Ok(Some(Value::Undefined)),
5534            }
5535        } else {
5536            Ok(property.value)
5537        }
5538    }
5539
5540    /// `super.key` — start the search at `proto`, but report to `receiver`.
5541    ///
5542    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5543    /// found on the prototype of a class has to see the *instance* as `this`, and a
5544    /// plain property read off `proto` would lose that.
5545    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5546        let start = self.require_object(proto)?;
5547        let key = self.propkey(key)?;
5548        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5549        if matches!(proto, Value::Null) {
5550            return Ok(Value::Undefined);
5551        }
5552        match lookup_key(&start, &key) {
5553            Some((_, property)) if property.is_accessor() => match &property.getter {
5554                Some(getter) if !matches!(getter, Value::Undefined) => {
5555                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5556                }
5557                _ => Ok(Value::Undefined),
5558            },
5559            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5560            None => Ok(Value::Undefined),
5561        }
5562    }
5563
5564    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5565    ///
5566    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5567    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5568    /// assignment follows.
5569    fn super_write(
5570        &mut self,
5571        receiver: &Value,
5572        proto: &Value,
5573        key: &Value,
5574        value: Value,
5575    ) -> JsResult<()> {
5576        let target = self.require_object(receiver)?;
5577        let key = self.propkey(key)?;
5578        if !matches!(proto, Value::Null)
5579            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5580        {
5581            if property.is_accessor() {
5582                if let Some(setter) = &property.setter
5583                    && !matches!(setter, Value::Undefined)
5584                {
5585                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5586                }
5587                return Ok(());
5588            }
5589            // A data property on the prototype is writable or not; reading `owner` at
5590            // all is only for the attribute check.
5591            if !property.writable {
5592                return Err(self.type_error(format!("'{key}' is read-only")));
5593            }
5594            let _ = owner;
5595        }
5596        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5597    }
5598
5599    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5600    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5601        match value.as_object() {
5602            Some(object) => Ok(object.clone()),
5603            None => Err(Signal::Throw(
5604                self.make_error("TypeError", "value is not an object"),
5605            )),
5606        }
5607    }
5608
5609    /// Build the class object `define_class` produces.
5610    ///
5611    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5612    /// whose prototype property is a fresh object inheriting from the parent's
5613    /// prototype, and whose own prototype is the parent constructor — which is what makes
5614    /// a static method inherited too.
5615    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5616        let ctor = self.pop();
5617        let parent = self.pop();
5618        let Value::Object(function) = &ctor else {
5619            return Err(Signal::Throw(
5620                self.make_error("TypeError", "class constructor must be a function"),
5621            ));
5622        };
5623        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5624        // but gives the instances no prototype at all.
5625        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5626            match &parent {
5627                Value::Null => (Some(self.realm.function_proto.clone()), None),
5628                Value::Object(parent_class) => {
5629                    if !parent_class.is_callable() {
5630                        return Err(Signal::Throw(
5631                            self.make_error("TypeError", "parent class must be constructor"),
5632                        ));
5633                    }
5634                    let proto = self.get_property(parent_class, "prototype")?;
5635                    match proto {
5636                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5637                        Some(Value::Null) => (Some(parent_class.clone()), None),
5638                        _ => {
5639                            return Err(Signal::Throw(self.make_error(
5640                                "TypeError",
5641                                "parent prototype must be an object or null",
5642                            )));
5643                        }
5644                    }
5645                }
5646                _ => {
5647                    return Err(Signal::Throw(
5648                        self.make_error("TypeError", "parent class must be constructor"),
5649                    ));
5650                }
5651            }
5652        } else {
5653            (
5654                Some(self.realm.function_proto.clone()),
5655                Some(self.realm.object_proto.clone()),
5656            )
5657        };
5658        let proto = self.new_object(parent_proto);
5659        function.set_proto(parent_ctor);
5660        // A class is not callable without `new`, and its `prototype` is not writable —
5661        // both follow from being a class and are what `class A {}; A()` throws on.
5662        function.set_class_constructor(true);
5663        function.set_home_object(None);
5664        self.set_function_name(&ctor, name);
5665        self.define_class_properties(function, &ctor, &proto)?;
5666        Ok((ctor, proto))
5667    }
5668
5669    /// Give the constructor its `prototype` and `length`, and the prototype its
5670    /// `constructor` back-pointer.
5671    fn define_class_properties(
5672        &mut self,
5673        function: &Gc<JsObject>,
5674        ctor: &Value,
5675        proto: &Gc<JsObject>,
5676    ) -> JsResult<()> {
5677        proto.define(
5678            "constructor",
5679            Property::with_attributes(ctor.clone(), true, false),
5680        );
5681        function.define(
5682            "prototype",
5683            Property::prototype_of(Value::Object(proto.clone()), false),
5684        );
5685        if let Some((code, _)) = bytecode_of(function) {
5686            let length = code.code.defined_args;
5687            function.define(
5688                "length",
5689                Property::name_or_length(Value::Int(length as i32)),
5690            );
5691        }
5692        Ok(())
5693    }
5694
5695    /// The own array element `key` names, if this object has one.
5696    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5697        // A typed array's elements live in its buffer, not in a property list: reading one
5698        // goes through the view's element type so a bounds check and a detached buffer are
5699        // both handled there.
5700        //
5701        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5702        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5703        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5704        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5705        // consulted. Testing with `array_index` rejected all three, which let a throwing
5706        // getter installed on `TypedArray.prototype["-1"]` run.
5707        if object.typed_array_parts().is_some() {
5708            let property_key = PropertyKey::from(key);
5709            let numeric = canonical_numeric_index(&property_key)?;
5710            if typed_array_index_is_valid(object, numeric) {
5711                return object.typed_array_element(numeric as usize);
5712            }
5713            // Canonical, but not a valid index: `undefined`, and *final*.
5714            return Some(Value::Undefined);
5715        }
5716        let index = array_index(key)?;
5717        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5718        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5719        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5720        // `[1,,3][1]`.
5721        match object.array_get(index as usize) {
5722            Some(Value::Hole) | None => None,
5723            other => other,
5724        }
5725    }
5726
5727    /// Store `object[key] = value`, honouring setters and inherited properties.
5728    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5729        self.set_property_with(object, key, value, DeleteFailure::Throw)
5730    }
5731
5732    /// Store a property, choosing what to do when the object refuses.
5733    ///
5734    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5735    /// mode, which is the one place assignment differs by mode. Native code (the array
5736    /// methods, `JSON`) always asks for the throw.
5737    pub fn set_property_with(
5738        &mut self,
5739        object: &Gc<JsObject>,
5740        key: &str,
5741        value: Value,
5742        on_failure: DeleteFailure,
5743    ) -> JsResult<()> {
5744        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5745    }
5746
5747    /// [`Interp::set_property_with`] with a key that may be a symbol.
5748    pub fn set_property_with_key(
5749        &mut self,
5750        object: &Gc<JsObject>,
5751        key: &PropertyKey,
5752        value: Value,
5753        on_failure: DeleteFailure,
5754    ) -> JsResult<()> {
5755        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5756    }
5757
5758    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5759    ///
5760    /// The receiver split lives one level up, in
5761    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5762    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5763    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5764    /// stores into `object` itself, which is why the element branch below converts `V`
5765    /// before asking whether the index is valid: `V` may put it back in bounds
5766    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5767    fn set_property_with_key_receiver_aware(
5768        &mut self,
5769        object: &Gc<JsObject>,
5770        key: &PropertyKey,
5771        value: Value,
5772        on_failure: DeleteFailure,
5773    ) -> JsResult<()> {
5774        // A proxy's `set` trap decides, and its `false` means the same thing an
5775        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5776        if object.proxy_state().is_some() {
5777            let receiver = Value::Object(object.clone());
5778            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5779                return match (accepted, on_failure) {
5780                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5781                    (false, DeleteFailure::Throw) => {
5782                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5783                    }
5784                };
5785            }
5786        }
5787        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5788        // refusal and means exactly what a proxy's `false` means.
5789        if let Some(exotic) = object.exotic() {
5790            let receiver = Value::Object(object.clone());
5791            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5792                return match (accepted, on_failure) {
5793                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5794                    (false, DeleteFailure::Throw) => {
5795                        Err(self.type_error(format!("property '{key}' is read-only")))
5796                    }
5797                };
5798            }
5799        }
5800        // The element and `length` shortcuts only exist for string keys: an array
5801        // index has no symbol spelling, and a symbol named `length` is an ordinary
5802        // property.
5803        let text = key.as_str();
5804        // A typed array's elements are a window onto its buffer: the store has to go
5805        // through the view's element type so the value is wrapped (or clamped) and so an
5806        // out-of-range or detached write is a silent no-op, as the spec says.
5807        //
5808        // The key test is `CanonicalNumericIndexString`, like every other index operation
5809        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5810        // does not exist, so they do nothing and leave no own property behind
5811        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5812        // path, which created a property named `"-0"`.
5813        //
5814        // The conversion comes **first**, before the index is checked at all, and that
5815        // order is observable twice over:
5816        //
5817        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5818        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5819        //   then store the converted value;
5820        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5821        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5822        //   run and its exception to escape.
5823        //
5824        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5825        // validity check, not a validity check that skips the conversion. The store itself
5826        // is a no-op when the index is invalid by then, which is why no extra guard is
5827        // needed around `typed_array_set`.
5828        if let Some(element) = object.typed_array_element_type()
5829            && let Some(numeric) = canonical_numeric_index(key)
5830        {
5831            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5832            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5833            // in `Interp`, because it is script-observable and the storage borrow inside
5834            // `typed_array_set` must not be held across it.
5835            let stored = self.element_value(element, value)?;
5836            if typed_array_index_is_valid(object, numeric)
5837                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5838            {
5839                return Err(self.type_error(reason));
5840            }
5841            return Ok(());
5842        }
5843        if let Some(text) = text
5844            && let Some(index) = array_index(text)
5845            && object.is_array()
5846        {
5847            // An accessor defined on an index lives in the property table while the
5848            // element slot is a hole, so the store has to go through the property first.
5849            // Writing the vector directly skipped the setter entirely.
5850            if let Some(existing) = object.own_property_key(key) {
5851                if existing.is_accessor() {
5852                    return match existing.setter.clone() {
5853                        Some(setter) if !matches!(setter, Value::Undefined) => {
5854                            let receiver = Value::Object(object.clone());
5855                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5856                        }
5857                        _ => match on_failure {
5858                            DeleteFailure::Throw => Err(self.type_error(format!(
5859                                "cannot set property '{text}', it has only a getter"
5860                            ))),
5861                            DeleteFailure::Ignore => Ok(()),
5862                        },
5863                    };
5864                }
5865                if !existing.writable {
5866                    return match on_failure {
5867                        DeleteFailure::Throw => {
5868                            Err(self.type_error(format!("'{text}' is read-only")))
5869                        }
5870                        DeleteFailure::Ignore => Ok(()),
5871                    };
5872                }
5873            }
5874            {
5875                // Growing the array needs a writable `length`.
5876                if (index as usize) >= object.array_length().unwrap_or(0)
5877                    && !object.length_writable()
5878                {
5879                    return match on_failure {
5880                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5881                        DeleteFailure::Ignore => Ok(()),
5882                    };
5883                }
5884                // Adding an index past the end makes the array longer, which a
5885                // non-extensible array refuses.
5886                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5887                    return match on_failure {
5888                        DeleteFailure::Throw => Err(self.type_error(format!(
5889                            "cannot add property '{key}', object is not extensible"
5890                        ))),
5891                        DeleteFailure::Ignore => Ok(()),
5892                    };
5893                }
5894                if object.element_is_locked(index) {
5895                    return match on_failure {
5896                        DeleteFailure::Throw => {
5897                            Err(self.type_error(format!("'{key}' is read-only")))
5898                        }
5899                        DeleteFailure::Ignore => Ok(()),
5900                    };
5901                }
5902                // The element vector is only half of `[[Set]]` for an index: the
5903                // prototype chain is consulted first, and a setter there answers instead
5904                // of the element store. This branch used to write the element directly, so
5905                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5906                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5907                // the reference calls the setter and the array keeps no own index.
5908                //
5909                // An *exotic* prototype has no entry to find, because its indices live
5910                // outside the property table — `Object.setPrototypeOf([], typedArray)`
5911                // then looked like "nothing on the chain" and the store created the
5912                // element, where the view's `[[Set]]` answers `true` and does nothing for
5913                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
5914                // checks the array's `length` stays 0). So the dispatch comes first.
5915                if !object.has_own_key(key)
5916                    && let Some(proto) = object.proto()
5917                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
5918                {
5919                    let receiver = Value::Object(object.clone());
5920                    let accepted =
5921                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5922                    return if accepted {
5923                        Ok(())
5924                    } else {
5925                        match on_failure {
5926                            DeleteFailure::Throw => {
5927                                Err(self.type_error(format!("'{key}' is read-only")))
5928                            }
5929                            DeleteFailure::Ignore => Ok(()),
5930                        }
5931                    };
5932                }
5933                if let Some((owner, property)) = lookup_key(object, key)
5934                    && !owner.ptr_eq(object)
5935                {
5936                    match &property {
5937                        property if property.is_accessor() => {
5938                            match &property.setter {
5939                                Some(setter) if !matches!(setter, Value::Undefined) => {
5940                                    let receiver = Value::Object(object.clone());
5941                                    self.call_value(setter.clone(), receiver, vec![value])?;
5942                                }
5943                                _ => {
5944                                    return match on_failure {
5945                                        DeleteFailure::Throw => Err(self.type_error(format!(
5946                                            "cannot set property '{text}', it has only a getter"
5947                                        ))),
5948                                        DeleteFailure::Ignore => Ok(()),
5949                                    };
5950                                }
5951                            }
5952                            return Ok(());
5953                        }
5954                        property if !property.writable => {
5955                            return match on_failure {
5956                                DeleteFailure::Throw => {
5957                                    Err(self.type_error(format!("'{text}' is read-only")))
5958                                }
5959                                DeleteFailure::Ignore => Ok(()),
5960                            };
5961                        }
5962                        _ => {}
5963                    }
5964                }
5965                if object.array_set(self.heap, index as usize, value.clone()) {
5966                    return Ok(());
5967                }
5968                // Past the dense limit the slot is too far out to be worth one `Value`
5969                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5970                // constant time by keeping the index as an ordinary property. The store
5971                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5972                // to a legal program.
5973                object.define_key(key, Property::with_attributes(value, true, true));
5974                // Extend, never shorten: the index may be *inside* the current length (a
5975                // huge `length` with a sparse store), and shortening would delete the
5976                // sparse properties above it — including the one just stored.
5977                if index as usize + 1 > object.array_length().unwrap_or(0) {
5978                    object.array_set_length(self.heap, index as usize + 1);
5979                }
5980                return Ok(());
5981            }
5982        }
5983        if text == Some("length") && object.is_array() {
5984            if !object.length_writable() {
5985                return match on_failure {
5986                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5987                    DeleteFailure::Ignore => Ok(()),
5988                };
5989            }
5990            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
5991            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
5992            // answered `NaN`, which left the assignment silently ignored
5993            // (`S15.4.5.2_A3_T2`).
5994            let length = self.to_js_number(&value)?;
5995            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
5996            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
5997            // `RangeError`s; the old code only tested "finite and non-negative" and then
5998            // truncated, so `[].length = 4294967297` quietly produced a length no array can
5999            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6000            let valid = length.is_finite()
6001                && length >= 0.0
6002                && length.fract() == 0.0
6003                && length <= u32::MAX as f64;
6004            if !valid {
6005                return Err(self.range_error("invalid array length"));
6006            }
6007            {
6008                let length = length as usize;
6009                // `a.length = n` with `n` below a non-configurable element cannot
6010                // drop that element, so the whole assignment fails. The spec makes
6011                // this a `TypeError` rather than a silent no-op, in any mode.
6012                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6013                    // Sloppy mode stops the truncation at the blocking element
6014                    // instead of failing; strict mode raises.
6015                    // Both modes stop at the blocking element; they differ in
6016                    // whether that is reported. The reference truncates *then*
6017                    // throws, so the array is left in the shortened state.
6018                    object.array_truncate(self.heap, blocked + 1);
6019                    return match on_failure {
6020                        DeleteFailure::Throw => {
6021                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
6022                        }
6023                        DeleteFailure::Ignore => Ok(()),
6024                    };
6025                }
6026                object.array_set_length(self.heap, length);
6027                return Ok(());
6028            }
6029        }
6030        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6031        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6032        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6033        //
6034        // The prototype step is a dispatch, not a lookup. Walking the chain here and
6035        // applying whatever came back is the same thing for an ordinary prototype and
6036        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6037        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6038        // answers "not mine, the receiver is not me" without touching the buffer. This
6039        // code used to find nothing owned by `o`, find no property on the view either,
6040        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6041        // object and never converted (`key-is-valid-index-prototype-chain-set`,
6042        // `key-is-canonical-invalid-index-prototype-chain-set`).
6043        //
6044        // The read-only and accessor rules of step 1 are what make
6045        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6046        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6047        let own = match self.lookup_for_write(object, key)? {
6048            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6049            _ => None,
6050        };
6051        if let Some(property) = own {
6052            if property.is_accessor() {
6053                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6054                    Some(setter) => {
6055                        let receiver = Value::Object(object.clone());
6056                        self.call_value(setter, receiver, vec![value])?;
6057                        Ok(())
6058                    }
6059                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6060                    // Sloppy code swallows that refusal, strict code raises — the same
6061                    // rule the read-only *data* property below follows, and skipping it
6062                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6063                    // return silently. The reference answers `TypeError: 'x' is
6064                    // read-only`.
6065                    None => match on_failure {
6066                        DeleteFailure::Throw => {
6067                            Err(self.type_error(format!("'{key}' is read-only")))
6068                        }
6069                        DeleteFailure::Ignore => Ok(()),
6070                    },
6071                };
6072            }
6073            // An own non-writable data property stops here: nothing may change it.
6074            if !property.writable {
6075                return match on_failure {
6076                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6077                    DeleteFailure::Ignore => Ok(()),
6078                };
6079            }
6080            // An existing writable own property keeps its attributes: only the value
6081            // moves. Redefining instead would reset them, which is how a
6082            // non-configurable global `var` used to become deletable.
6083            if object.write_value_key(key, value.clone()) {
6084                return Ok(());
6085            }
6086        }
6087        // Step 2: hand the store to the prototype, with `object` as the receiver.
6088        if let Some(proto) = object.proto() {
6089            let receiver = Value::Object(object.clone());
6090            let accepted =
6091                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6092            return if accepted {
6093                Ok(())
6094            } else {
6095                match on_failure {
6096                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6097                    DeleteFailure::Ignore => Ok(()),
6098                }
6099            };
6100        }
6101        // Step 3: create one, and a non-extensible object cannot.
6102        if !object.is_extensible() {
6103            return match on_failure {
6104                DeleteFailure::Throw => Err(self.type_error(format!(
6105                    "cannot add property {key}, object is not extensible"
6106                ))),
6107                DeleteFailure::Ignore => Ok(()),
6108            };
6109        }
6110        object.define_data_key(key, value);
6111        Ok(())
6112    }
6113
6114    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6115    ///
6116    /// The distinction the fast path above does not need: it is called with the store's
6117    /// receiver already being the object it writes to. Here `object` is the one whose
6118    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6119    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6120    /// and not a write to `object`.
6121    ///
6122    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6123    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6124    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6125    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6126    /// descriptor on the prototype refuses instead, which is the same rule that keeps
6127    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6128    ///
6129    /// Answers `false` where the spec says `false`; the caller turns that into the
6130    /// strict-mode `TypeError` or the sloppy-mode silence.
6131    fn ordinary_set_with_receiver(
6132        &mut self,
6133        object: &Gc<JsObject>,
6134        receiver: &Value,
6135        key: &PropertyKey,
6136        value: Value,
6137        on_failure: DeleteFailure,
6138    ) -> JsResult<bool> {
6139        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6140        if object.proxy_state().is_some() {
6141            return Ok(self
6142                .proxy_set(object, key, value, receiver)?
6143                .unwrap_or(true));
6144        }
6145        // A host class decides for itself, with the receiver the caller named.
6146        if let Some(exotic) = object.exotic()
6147            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6148        {
6149            return Ok(accepted);
6150        }
6151        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6152        // rather than the receiver, but the receiver may still *be* the view:
6153        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6154        // itself as receiver, and then the first half applies — convert `V` once, store
6155        // if the index is valid, answer `true` either way. The conversion is the observable
6156        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6157        //
6158        // Only the second half, a view that is *not* the receiver, skips the conversion
6159        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6160        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6161        // below with the value still unconverted.
6162        if object.typed_array_element_type().is_some()
6163            && let Some(numeric) = canonical_numeric_index(key)
6164        {
6165            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6166                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6167                return Ok(true);
6168            }
6169            if !typed_array_index_is_valid(object, numeric) {
6170                return Ok(true);
6171            }
6172        }
6173        let own = self.object_get_own_property(object, key)?;
6174        if let Some(own) = own {
6175            if own.is_accessor() {
6176                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6177                    Some(setter) => {
6178                        self.call_value(setter, receiver.clone(), vec![value])?;
6179                        Ok(true)
6180                    }
6181                    None => Ok(false),
6182                };
6183            }
6184            // A non-writable data descriptor refuses, own or inherited. Either way the
6185            // receiver must not gain a shadowing property.
6186            if !own.writable {
6187                return Ok(false);
6188            }
6189            // Step 1.d: the *receiver's* own descriptor decides whether it can be
6190            // created or written, and it is created as an ordinary data property.
6191            let Some(receiver_object) = receiver.as_object().cloned() else {
6192                return Ok(false);
6193            };
6194            return match self.object_get_own_property(&receiver_object, key)? {
6195                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6196                Some(existing) => self.object_define_own_property(
6197                    &receiver_object,
6198                    key,
6199                    Property {
6200                        value: Some(value),
6201                        ..existing
6202                    },
6203                ),
6204                None => {
6205                    self.object_define_own_property(&receiver_object, key, Property::data(value))
6206                }
6207            };
6208        }
6209        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6210        if let Some(proto) = object.proto() {
6211            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6212        }
6213        // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6214        // *default* data descriptor here, so control falls into step 2 exactly as if the
6215        // target had owned a writable property — which means the **receiver's** own
6216        // descriptor is asked for before the write. Skipping that question went straight to
6217        // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6218        // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6219        // exactly those calls).
6220        let Some(receiver_object) = receiver.as_object().cloned() else {
6221            return Ok(false);
6222        };
6223        match self.object_get_own_property(&receiver_object, key)? {
6224            Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6225            Some(existing) => self.object_define_own_property(
6226                &receiver_object,
6227                key,
6228                Property {
6229                    value: Some(value),
6230                    ..existing
6231                },
6232            ),
6233            None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6234        }
6235    }
6236
6237    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6238    ///
6239    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6240    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6241    /// a virtual accessor gets its setter run without implementing `set_property` at all.
6242    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6243    /// the prototype, so the walk resumes above the object.
6244    fn lookup_for_write(
6245        &mut self,
6246        object: &Gc<JsObject>,
6247        key: &PropertyKey,
6248    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6249        let Some(exotic) = object.exotic() else {
6250            return Ok(lookup_key(object, key));
6251        };
6252        Ok(match exotic.get_own_property(self, object, key)? {
6253            Some(Some(property)) => Some((object.clone(), property)),
6254            Some(None) => lookup_key_above(object, key),
6255            None => lookup_key(object, key),
6256        })
6257    }
6258
6259    /// Delete `object[key]`.
6260    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6261        self.delete_property_key(object, &PropertyKey::from(key))
6262    }
6263
6264    /// [`Interp::delete_property`] with a key that may be a symbol.
6265    pub fn delete_property_key(
6266        &mut self,
6267        object: &Gc<JsObject>,
6268        key: &PropertyKey,
6269    ) -> JsResult<bool> {
6270        // A proxy decides for itself, and may even throw; the invariant checks live in
6271        // `proxy_delete`.
6272        if let Some(answer) = self.proxy_delete(object, key)? {
6273            return Ok(answer);
6274        }
6275        // A host class's `delete_property` trap decides; `false` is a refusal, which the
6276        // caller reports as a failed delete.
6277        if let Some(exotic) = object.exotic()
6278            && let Some(answer) = exotic.delete_property(self, object, key)?
6279        {
6280            return Ok(answer);
6281        }
6282        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6283        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6284        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6285        // one answers `false` because the elements are non-configurable. The prototype
6286        // chain is not consulted either, which is what makes a throwing getter on
6287        // `TypedArray.prototype["-1"]` stay unrun.
6288        if object.typed_array_parts().is_some()
6289            && object.proxy_state().is_none()
6290            && let Some(numeric) = canonical_numeric_index(key)
6291        {
6292            return Ok(!typed_array_index_is_valid(object, numeric));
6293        }
6294        let mapped_index = key.as_str().and_then(array_index);
6295        if let Some(index) = mapped_index
6296            && let Some(length) = object.array_length()
6297            && (index as usize) < length
6298        {
6299            // An accessor defined on an index lives in the property table rather than the
6300            // element vector, so both have to be cleared: `delete` after
6301            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6302            object.delete_key(key);
6303            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6304            // index stops answering `in`.
6305            if object.element_is_undeletable(index) {
6306                return Ok(false);
6307            }
6308            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6309            // so a later `defineProperty(arguments, "0", {value})` writes to the object
6310            // and no longer through to the parameter. A refused delete leaves the
6311            // mapping alone.
6312            object.drop_mapped_argument(index as usize);
6313            object.array_set(self.heap, index as usize, Value::Hole);
6314            return Ok(true);
6315        }
6316        // An array's `length` is a non-configurable own property that lives outside the
6317        // property table, so `delete_key` finds nothing and reports success — `Reflect
6318        // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6319        // §10.4.4.1 step 3 refuses it.
6320        if key.as_str() == Some("length") && object.array_length().is_some() {
6321            return Ok(false);
6322        }
6323        // The same for an object that is not an array: only a delete that actually
6324        // removed the property ends the alias.
6325        let deleted = object.delete_key(key);
6326        if deleted && let Some(index) = mapped_index {
6327            object.drop_mapped_argument(index as usize);
6328        }
6329        Ok(deleted)
6330    }
6331
6332    // -- proxy traps --------------------------------------------------------
6333    //
6334    // A proxy's internal methods all look the same: ask the handler for the trap, call it
6335    // with the target and the operation's own arguments, then check the answer against
6336    // the target. The checks are not decoration — they are what stops a proxy from
6337    // reporting a `non-configurable` property as missing, which would let a frozen object
6338    // be rewritten by standing in front of it.
6339
6340    /// The target and handler of `object`, or `None` when it is not a proxy.
6341    ///
6342    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6343    /// one has to fail: the slots the traps would have been read from are gone.
6344    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6345        let Some(state) = object.proxy_state() else {
6346            return Ok(None);
6347        };
6348        let state = state.borrow();
6349        match (&state.target, &state.handler) {
6350            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6351            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6352        }
6353    }
6354
6355    /// Call `handler[name]`, or answer `None` when the trap is absent.
6356    ///
6357    /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6358    /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6359    /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6360    /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6361    /// one per trap plus the `target-is-proxy` variants.
6362    ///
6363    /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6364    /// this cannot simply be "any non-callable means no trap".
6365    fn proxy_trap(
6366        &mut self,
6367        handler: &Value,
6368        name: &str,
6369        args: Vec<Value>,
6370    ) -> JsResult<Option<Value>> {
6371        let Value::Object(table) = handler else {
6372            return Err(self.type_error("proxy handler is not an object"));
6373        };
6374        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6375        match trap {
6376            Value::Undefined | Value::Null => Ok(None),
6377            Value::Object(function) if function.is_callable() => {
6378                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6379                Ok(Some(answer))
6380            }
6381            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6382        }
6383    }
6384
6385    /// Whether the target's own property `key` is one it refuses to lose.
6386    ///
6387    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6388    /// its value behind the target's back.
6389    ///
6390    /// A **method**, not a free function, because §10.5.1's invariants say
6391    /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6392    /// property table directly finds nothing (a proxy's table is empty by design), so every
6393    /// invariant check silently passed for a proxy target. That is what
6394    /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6395    /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6396    /// where an array's elements and its `length` — both fixed, both outside the table —
6397    /// are covered.
6398    fn fixed_property(
6399        &mut self,
6400        target: &Gc<JsObject>,
6401        key: &PropertyKey,
6402    ) -> JsResult<Option<Property>> {
6403        Ok(self
6404            .object_get_own_property(target, key)?
6405            .filter(|property| !property.configurable))
6406    }
6407
6408    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6409    fn proxy_get(
6410        &mut self,
6411        object: &Gc<JsObject>,
6412        receiver: &Value,
6413        key: &PropertyKey,
6414    ) -> JsResult<Option<Value>> {
6415        let Some((target, handler)) = self.proxy_parts(object)? else {
6416            return Ok(None);
6417        };
6418        let key_value = self.key_value(key);
6419        let Some(result) = self.proxy_trap(
6420            &handler,
6421            "get",
6422            vec![Value::Object(target.clone()), key_value, receiver.clone()],
6423        )?
6424        else {
6425            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6426            // inherited getter still sees the proxy.
6427            return Ok(Some(
6428                self.get_property_key_for(&target, Some(receiver), key)?
6429                    .unwrap_or(Value::Undefined),
6430            ));
6431        };
6432        if let Some(fixed) = self.fixed_property(&target, key)? {
6433            if fixed.is_accessor() {
6434                // A fixed accessor with no getter must read as `undefined`.
6435                let has_getter = fixed
6436                    .getter
6437                    .as_ref()
6438                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
6439                if !has_getter && !matches!(result, Value::Undefined) {
6440                    return Err(self.type_error(format!(
6441                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
6442                    )));
6443                }
6444            } else if !fixed.writable {
6445                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6446                if !fixed_value.same_value(&result) {
6447                    return Err(self.type_error(format!(
6448                        "proxy 'get' disagrees with the non-configurable property '{key}'"
6449                    )));
6450                }
6451            }
6452        }
6453        Ok(Some(result))
6454    }
6455
6456    /// `[[Set]]` on a proxy.
6457    ///
6458    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6459    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6460    /// read-only store has.
6461    fn proxy_set(
6462        &mut self,
6463        object: &Gc<JsObject>,
6464        key: &PropertyKey,
6465        value: Value,
6466        receiver: &Value,
6467    ) -> JsResult<Option<bool>> {
6468        let Some((target, handler)) = self.proxy_parts(object)? else {
6469            return Ok(None);
6470        };
6471        let key_value = self.key_value(key);
6472        let Some(result) = self.proxy_trap(
6473            &handler,
6474            "set",
6475            vec![
6476                Value::Object(target.clone()),
6477                key_value,
6478                value.clone(),
6479                receiver.clone(),
6480            ],
6481        )?
6482        else {
6483            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6484            // given — not the target. `OrdinarySet` step 3 is
6485            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6486            // object whose prototype is a typed array has to reach the proxy's own
6487            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6488            // calls and expects exactly one. Storing on the target instead put the value
6489            // in the target and never consulted the trap.
6490            let accepted = self.ordinary_set_with_receiver(
6491                &target,
6492                receiver,
6493                key,
6494                value,
6495                DeleteFailure::Ignore,
6496            )?;
6497            return Ok(Some(accepted));
6498        };
6499        if !result.to_boolean() {
6500            return Ok(Some(false));
6501        }
6502        if let Some(fixed) = self.fixed_property(&target, key)? {
6503            if fixed.is_accessor() {
6504                let has_setter = fixed
6505                    .setter
6506                    .as_ref()
6507                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
6508                if !has_setter {
6509                    return Err(self.type_error(format!(
6510                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6511                    )));
6512                }
6513            } else if !fixed.writable {
6514                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6515                if !fixed_value.same_value(&value) {
6516                    return Err(self.type_error(format!(
6517                        "proxy 'set' changed the non-configurable property '{key}'"
6518                    )));
6519                }
6520            }
6521        }
6522        // A new property cannot appear on a target that refuses new properties.
6523        if self.object_get_own_property(&target, key)?.is_none()
6524            && !self.object_is_extensible(&target)?
6525        {
6526            return Err(self.type_error(format!(
6527                "proxy 'set' added '{key}' to a non-extensible target"
6528            )));
6529        }
6530        Ok(Some(true))
6531    }
6532
6533    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6534    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6535        let Some((target, handler)) = self.proxy_parts(object)? else {
6536            return Ok(None);
6537        };
6538        let key_value = self.key_value(key);
6539        let Some(result) = self.proxy_trap(
6540            &handler,
6541            "has",
6542            vec![Value::Object(target.clone()), key_value],
6543        )?
6544        else {
6545            return Ok(Some(self.has_own_or_inherited(&target, key)?));
6546        };
6547        if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6548            return Err(self.type_error(format!(
6549                "proxy 'has' denied the non-configurable property '{key}'"
6550            )));
6551        }
6552        // A non-extensible target cannot grow, so every own property it *has* is fixed.
6553        if !result.to_boolean()
6554            && !self.object_is_extensible(&target)?
6555            && self.object_get_own_property(&target, key)?.is_some()
6556        {
6557            return Err(self.type_error(format!(
6558                "proxy 'has' denied the own property '{key}' of a non-extensible target"
6559            )));
6560        }
6561        Ok(Some(result.to_boolean()))
6562    }
6563
6564    /// `[[Delete]]` on a proxy.
6565    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6566        let Some((target, handler)) = self.proxy_parts(object)? else {
6567            return Ok(None);
6568        };
6569        let key_value = self.key_value(key);
6570        let Some(result) = self.proxy_trap(
6571            &handler,
6572            "deleteProperty",
6573            vec![Value::Object(target.clone()), key_value],
6574        )?
6575        else {
6576            return Ok(Some(self.delete_property_key(&target, key)?));
6577        };
6578        if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6579            return Err(self.type_error(format!(
6580                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6581            )));
6582        }
6583        if result.to_boolean()
6584            && !self.object_is_extensible(&target)?
6585            && self.object_get_own_property(&target, key)?.is_some()
6586        {
6587            return Err(self.type_error(format!(
6588                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6589            )));
6590        }
6591        Ok(Some(result.to_boolean()))
6592    }
6593
6594    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6595    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6596        let Some((target, handler)) = self.proxy_parts(object)? else {
6597            return Ok(None);
6598        };
6599        let Some(result) =
6600            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6601        else {
6602            // No trap: the target's own keys, already in the order an object reports.
6603            return Ok(Some(self.object_own_property_keys(&target)?));
6604        };
6605        // `CreateListFromArrayLike` with the string-or-symbol restriction.
6606        let list = self.list_from_array_like(&result, true)?;
6607        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6608        for value in list {
6609            let key = self.propkey(&value)?;
6610            if keys.contains(&key) {
6611                return Err(self.type_error(format!(
6612                    "proxy 'ownKeys' returned the duplicate key '{key}'"
6613                )));
6614            }
6615            keys.push(key);
6616        }
6617        // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
6618        // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
6619        // table is empty, which made every check below vacuous.
6620        let target_keys = self.object_own_property_keys(&target)?;
6621        let extensible = self.object_is_extensible(&target)?;
6622        for key in &target_keys {
6623            if keys.contains(key) {
6624                continue;
6625            }
6626            if self.fixed_property(&target, key)?.is_some() {
6627                return Err(self.type_error(format!(
6628                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6629                )));
6630            }
6631            if !extensible {
6632                return Err(self.type_error(format!(
6633                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6634                )));
6635            }
6636        }
6637        if !extensible {
6638            // §10.5.11 step 12: the lists must match one for one, in any order.
6639            if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
6640            {
6641                return Err(
6642                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6643                );
6644            }
6645        }
6646        Ok(Some(keys))
6647    }
6648
6649    /// `[[GetOwnProperty]]` on a proxy.
6650    fn proxy_get_own_property(
6651        &mut self,
6652        object: &Gc<JsObject>,
6653        key: &PropertyKey,
6654    ) -> JsResult<Option<Option<Property>>> {
6655        let Some((target, handler)) = self.proxy_parts(object)? else {
6656            return Ok(None);
6657        };
6658        let key_value = self.key_value(key);
6659        let Some(result) = self.proxy_trap(
6660            &handler,
6661            "getOwnPropertyDescriptor",
6662            vec![Value::Object(target.clone()), key_value],
6663        )?
6664        else {
6665            // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
6666            // property table. Two things ride on that choice: a target that is itself a
6667            // proxy has to re-dispatch (its own table is empty, so reading it reported
6668            // `undefined` for every key, `Object.keys` then dropped them all), and an array's
6669            // indices and `length` live outside the table and need the ordinary synthesis.
6670            // `object_get_own_property` does both.
6671            return Ok(Some(self.object_get_own_property(&target, key)?));
6672        };
6673        // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
6674        // `ToPropertyDescriptor` runs, because that operation would box the primitive
6675        // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
6676        // empty descriptor instead of refusing.
6677        if !matches!(result, Value::Undefined | Value::Object(_)) {
6678            return Err(self.type_error(
6679                "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
6680            ));
6681        }
6682        let target_desc = self.object_get_own_property(&target, key)?;
6683        let extensible = self.object_is_extensible(&target)?;
6684        let Some(descriptor) = (match result {
6685            Value::Undefined => None,
6686            _ => Some(self.property_from_descriptor(&result)?),
6687        }) else {
6688            // Steps 12.a–12.d: reporting absent is allowed only when the target's own
6689            // descriptor is configurable *and* the target can still grow back.
6690            if let Some(target_desc) = &target_desc {
6691                if !target_desc.configurable {
6692                    return Err(self.type_error(format!(
6693                        "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6694                    )));
6695                }
6696                if !extensible {
6697                    return Err(self.type_error(format!(
6698                        "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
6699                    )));
6700                }
6701            }
6702            return Ok(Some(None));
6703        };
6704        // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
6705        // which is a stronger requirement than "the target is not contradicting it" — the
6706        // four branches below are each one test262 case.
6707        if !descriptor.configurable {
6708            let Some(target_desc) = &target_desc else {
6709                return Err(self.type_error(format!(
6710                    "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
6711                )));
6712            };
6713            if target_desc.configurable {
6714                return Err(self.type_error(format!(
6715                    "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
6716                )));
6717            }
6718            let target_is_data = !target_desc.is_accessor();
6719            let result_is_data = !descriptor.is_accessor();
6720            if result_is_data && !target_is_data {
6721                return Err(self.type_error(format!(
6722                    "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6723                )));
6724            }
6725            if target_is_data && !target_desc.writable {
6726                if !result_is_data {
6727                    return Err(self.type_error(format!(
6728                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6729                    )));
6730                }
6731                if descriptor.writable {
6732                    return Err(self.type_error(format!(
6733                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6734                    )));
6735                }
6736                let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6737                let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6738                if !fixed_value.same_value(&reported) {
6739                    return Err(self.type_error(format!(
6740                        "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6741                    )));
6742                }
6743            }
6744            // Step 16.d: a reported *read-only* data property needs a real read-only data
6745            // property behind it. Missing this let a trap bolt a frozen property onto a
6746            // writable target intent (`resultdesc-is-not-configurable-not-writable-
6747            // targetdesc-is-writable`).
6748            if result_is_data && !descriptor.writable {
6749                if !target_is_data {
6750                    return Err(self.type_error(format!(
6751                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6752                    )));
6753                }
6754                if target_desc.writable {
6755                    return Err(self.type_error(format!(
6756                        "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
6757                    )));
6758                }
6759            }
6760            if descriptor.is_accessor() {
6761                // Step 16.e: a getter the target does not have may not be invented, and
6762                // vice versa.
6763                let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6764                    (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6765                    (Some(a), Some(b)) => a.same_value(b),
6766                    _ => false,
6767                };
6768                if !same(&target_desc.getter, &descriptor.getter)
6769                    || !same(&target_desc.setter, &descriptor.setter)
6770                {
6771                    return Err(self.type_error(format!(
6772                        "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6773                    )));
6774                }
6775            }
6776        }
6777        // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
6778        // where the target's own is locked. Without it a handler could advertise
6779        // `{value: 1, configurable: true}` for a non-configurable property, and a caller
6780        // that believed it would try to redefine something it cannot.
6781        if descriptor.configurable
6782            && let Some(target_desc) = &target_desc
6783            && !target_desc.configurable
6784        {
6785            return Err(self.type_error(format!(
6786                "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6787            )));
6788        }
6789        // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
6790        // through the trap either, however well-formed the descriptor is. This is the
6791        // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
6792        // the frozen target does not own.
6793        if !extensible {
6794            let Some(target_desc) = &target_desc else {
6795                return Err(self.type_error(format!(
6796                    "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
6797                )));
6798            };
6799            if target_desc.is_accessor() == descriptor.is_accessor() {
6800                let target_is_data = !target_desc.is_accessor();
6801                let result_is_data = !descriptor.is_accessor();
6802                if target_is_data && !target_desc.writable && descriptor.writable {
6803                    return Err(self.type_error(format!(
6804                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6805                    )));
6806                }
6807                if !result_is_data && !target_is_data {
6808                    let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6809                        (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6810                        (Some(a), Some(b)) => a.same_value(b),
6811                        _ => false,
6812                    };
6813                    if !same(&target_desc.getter, &descriptor.getter)
6814                        || !same(&target_desc.setter, &descriptor.setter)
6815                    {
6816                        return Err(self.type_error(format!(
6817                            "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6818                        )));
6819                    }
6820                }
6821            }
6822        }
6823        Ok(Some(Some(descriptor)))
6824    }
6825
6826    /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
6827    ///
6828    /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
6829    /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
6830    /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
6831    /// for a data property. `Property` cannot express "this field is absent", so the whole
6832    /// property path is skipped and the descriptor is assembled here field by field.
6833    ///
6834    /// `current` is the property the trap reported, used only to tell a data property from
6835    /// an accessor.
6836    pub fn proxy_seal_property(
6837        &mut self,
6838        object: &Gc<JsObject>,
6839        key: &PropertyKey,
6840        frozen: bool,
6841        current: &Property,
6842    ) -> JsResult<bool> {
6843        let Some((_target, handler)) = self.proxy_parts(object)? else {
6844            return Err(self.type_error("not a proxy"));
6845        };
6846        let descriptor = self.new_object(None);
6847        descriptor.define_data("configurable", Value::Bool(false));
6848        if frozen && !current.is_accessor() {
6849            descriptor.define_data("writable", Value::Bool(false));
6850        }
6851        let key_value = self.key_value(key);
6852        let target = object
6853            .proxy_state()
6854            .and_then(|state| state.borrow().target.clone());
6855        let Some(target) = target else {
6856            return Err(self.type_error("cannot use a proxy that has been revoked"));
6857        };
6858        let Some(result) = self.proxy_trap(
6859            &handler,
6860            "defineProperty",
6861            vec![Value::Object(target), key_value, Value::Object(descriptor)],
6862        )?
6863        else {
6864            // No trap means the definition belongs to the target; `false` is its answer.
6865            return Ok(false);
6866        };
6867        Ok(result.to_boolean())
6868    }
6869
6870    /// `[[DefineOwnProperty]]` on a proxy.
6871    fn proxy_define_property(
6872        &mut self,
6873        object: &Gc<JsObject>,
6874        key: &PropertyKey,
6875        property: Property,
6876    ) -> JsResult<Option<bool>> {
6877        let Some((target, handler)) = self.proxy_parts(object)? else {
6878            return Ok(None);
6879        };
6880        let key_value = self.key_value(key);
6881        let descriptor = self.descriptor_from_property(&property);
6882        let Some(result) = self.proxy_trap(
6883            &handler,
6884            "defineProperty",
6885            vec![Value::Object(target.clone()), key_value, descriptor],
6886        )?
6887        else {
6888            // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
6889            // going" answer and `object_define_own_property` turns it into exactly that
6890            // forwarding — see the note there. (Reading it as "not a proxy" would define
6891            // the property on the proxy object itself, whose table is empty and which no
6892            // read ever consults.)
6893            return Ok(None);
6894        };
6895        if !result.to_boolean() {
6896            return Ok(Some(false));
6897        }
6898        // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
6899        // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
6900        // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
6901        // and treating them alike made four cases pass a descriptor the target contradicts.
6902        let target_desc = self.object_get_own_property(&target, key)?;
6903        let extensible = self.object_is_extensible(&target)?;
6904        let named = property
6905            .descriptor_fields
6906            .unwrap_or(crate::object::DescriptorFields {
6907                value: false,
6908                writable: false,
6909                enumerable: false,
6910                configurable: false,
6911                get: false,
6912                set: false,
6913            });
6914        if named.configurable && !property.configurable {
6915            let Some(target_desc) = &target_desc else {
6916                return Err(self.type_error(format!(
6917                    "proxy 'defineProperty' invented the non-configurable '{key}'"
6918                )));
6919            };
6920            if target_desc.configurable {
6921                return Err(self.type_error(format!(
6922                    "proxy 'defineProperty' made '{key}' non-configurable"
6923                )));
6924            }
6925        }
6926        // Step 11's other half: reporting that a property was made *configurable* needs a
6927        // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
6928        // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
6929        // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
6930        // target`).
6931        if named.configurable
6932            && property.configurable
6933            && let Some(target_desc) = &target_desc
6934            && !target_desc.configurable
6935        {
6936            return Err(
6937                self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
6938            );
6939        }
6940        // Step 12: a property cannot be reported *made writable* when the target's copy is
6941        // read-only. Note the `Some` — an absent target property is *not* a contradiction:
6942        // the trap is allowed to claim a definition it did not perform, as long as the
6943        // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
6944        // legal, and refusing it broke the commonest way to seed a proxy).
6945        if named.writable
6946            && property.writable
6947            && let Some(target_desc) = &target_desc
6948            && !target_desc.writable
6949        {
6950            return Err(self.type_error(format!(
6951                "proxy 'defineProperty' made the read-only '{key}' writable"
6952            )));
6953        }
6954        // Step 13: making a property read-only needs an existing read-only property.
6955        if named.writable
6956            && !property.writable
6957            && let Some(target_desc) = &target_desc
6958            && !target_desc.is_accessor()
6959            && target_desc.writable
6960        {
6961            return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
6962        }
6963        // Step 14: a non-writable, non-configurable property's value is fixed.
6964        if named.value
6965            && let Some(target_desc) = &target_desc
6966            && !target_desc.is_accessor()
6967            && !target_desc.writable
6968            && !target_desc.configurable
6969        {
6970            let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6971            let reported = property.value.clone().unwrap_or(Value::Undefined);
6972            if !fixed_value.same_value(&reported) {
6973                return Err(self.type_error(format!(
6974                    "proxy 'defineProperty' changed the value of '{key}'"
6975                )));
6976            }
6977        }
6978        // Step 15: a non-extensible target cannot grow.
6979        if target_desc.is_none() && !extensible {
6980            return Err(self.type_error(format!(
6981                "proxy 'defineProperty' added '{key}' to a non-extensible target"
6982            )));
6983        }
6984        Ok(Some(true))
6985    }
6986
6987    /// `[[GetPrototypeOf]]` on a proxy.
6988    fn proxy_get_prototype_of(
6989        &mut self,
6990        object: &Gc<JsObject>,
6991    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6992        let Some((target, handler)) = self.proxy_parts(object)? else {
6993            return Ok(None);
6994        };
6995        let Some(result) = self.proxy_trap(
6996            &handler,
6997            "getPrototypeOf",
6998            vec![Value::Object(target.clone())],
6999        )?
7000        else {
7001            // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7002            // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7003            // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7004            // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7005            // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7006            return Ok(Some(self.object_prototype_of(&target)?));
7007        };
7008        let proto = match &result {
7009            Value::Null => None,
7010            Value::Object(proto) => Some(proto.clone()),
7011            _ => {
7012                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7013            }
7014        };
7015        if !self.object_is_extensible(&target)? {
7016            let actual = self.object_prototype_of(&target)?;
7017            if !same_proto(proto.as_ref(), actual.as_ref()) {
7018                return Err(self.type_error(
7019                    "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7020                ));
7021            }
7022        }
7023        Ok(Some(proto))
7024    }
7025
7026    /// `[[SetPrototypeOf]]` on a proxy.
7027    fn proxy_set_prototype_of(
7028        &mut self,
7029        object: &Gc<JsObject>,
7030        proto: Option<Gc<JsObject>>,
7031    ) -> JsResult<Option<bool>> {
7032        let Some((target, handler)) = self.proxy_parts(object)? else {
7033            return Ok(None);
7034        };
7035        let proto_value = match &proto {
7036            Some(proto) => Value::Object(proto.clone()),
7037            None => Value::Null,
7038        };
7039        let Some(result) = self.proxy_trap(
7040            &handler,
7041            "setPrototypeOf",
7042            vec![Value::Object(target.clone()), proto_value],
7043        )?
7044        else {
7045            // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7046            // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7047            // its stored prototype overwritten behind its back.
7048            return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7049        };
7050        if result.to_boolean()
7051            && !self.object_is_extensible(&target)?
7052            && !same_proto(
7053                Some(&proto).and_then(|p| p.clone()).as_ref(),
7054                self.object_prototype_of(&target)?.as_ref(),
7055            )
7056        {
7057            return Err(self.type_error(
7058                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7059            ));
7060        }
7061        Ok(Some(result.to_boolean()))
7062    }
7063
7064    /// `[[IsExtensible]]` on a proxy.
7065    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7066        let Some((target, handler)) = self.proxy_parts(object)? else {
7067            return Ok(None);
7068        };
7069        let Some(result) = self.proxy_trap(
7070            &handler,
7071            "isExtensible",
7072            vec![Value::Object(target.clone())],
7073        )?
7074        else {
7075            return Ok(Some(self.object_is_extensible(&target)?));
7076        };
7077        // The answer is not the proxy's to invent: it must agree with the target, or a
7078        // script could learn `false` while the target keeps accepting new properties.
7079        if result.to_boolean() != self.object_is_extensible(&target)? {
7080            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7081        }
7082        Ok(Some(result.to_boolean()))
7083    }
7084
7085    /// `[[PreventExtensions]]` on a proxy.
7086    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7087        let Some((target, handler)) = self.proxy_parts(object)? else {
7088            return Ok(None);
7089        };
7090        let Some(result) = self.proxy_trap(
7091            &handler,
7092            "preventExtensions",
7093            vec![Value::Object(target.clone())],
7094        )?
7095        else {
7096            // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7097            // its answer can be `false`.
7098            return Ok(Some(self.object_prevent_extensions(&target)?));
7099        };
7100        if result.to_boolean() && self.object_is_extensible(&target)? {
7101            return Err(self.type_error(
7102                "proxy 'preventExtensions' reported success but the target is still extensible",
7103            ));
7104        }
7105        Ok(Some(result.to_boolean()))
7106    }
7107
7108    /// `[[Call]]` on a proxy, through the `apply` trap.
7109    fn proxy_apply(
7110        &mut self,
7111        object: &Gc<JsObject>,
7112        this: Value,
7113        args: Vec<Value>,
7114    ) -> JsResult<Option<Value>> {
7115        let Some((target, handler)) = self.proxy_parts(object)? else {
7116            return Ok(None);
7117        };
7118        // The trap gets the arguments as one array, which is the shape the spec passes
7119        // and the shape `apply` traps are written against (`args[0]` is the first one).
7120        let arguments = self.new_array(args.clone());
7121        let this_for_trap = this.clone();
7122        let Some(result) = self.proxy_trap(
7123            &handler,
7124            "apply",
7125            vec![
7126                Value::Object(target.clone()),
7127                this_for_trap,
7128                Value::Object(arguments),
7129            ],
7130        )?
7131        else {
7132            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7133        };
7134        Ok(Some(result))
7135    }
7136
7137    /// `[[Construct]]` on a proxy, through the `construct` trap.
7138    fn proxy_construct(
7139        &mut self,
7140        object: &Gc<JsObject>,
7141        args: Vec<Value>,
7142        new_target: &Value,
7143    ) -> JsResult<Option<Value>> {
7144        let Some((target, handler)) = self.proxy_parts(object)? else {
7145            return Ok(None);
7146        };
7147        if !target.is_callable() {
7148            return Err(self.type_error("proxy target is not a constructor"));
7149        }
7150        let arguments = self.new_array(args.clone());
7151        let Some(result) = self.proxy_trap(
7152            &handler,
7153            "construct",
7154            vec![
7155                Value::Object(target.clone()),
7156                Value::Object(arguments),
7157                new_target.clone(),
7158            ],
7159        )?
7160        else {
7161            return Ok(Some(self.construct(
7162                Value::Object(target),
7163                new_target.clone(),
7164                args,
7165            )?));
7166        };
7167        if !matches!(result, Value::Object(_)) {
7168            return Err(self.type_error("proxy 'construct' must return an object"));
7169        }
7170        Ok(Some(result))
7171    }
7172
7173    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7174    pub(crate) fn has_own_or_inherited(
7175        &mut self,
7176        object: &Gc<JsObject>,
7177        key: &PropertyKey,
7178    ) -> JsResult<bool> {
7179        // The object itself first: it may be a proxy, and then the answer is its trap's.
7180        if let Some(answer) = self.proxy_has(object, key)? {
7181            return Ok(answer);
7182        }
7183        // An integer-indexed exotic object answers a canonical numeric index from
7184        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7185        // prototype chain. That is observable twice: a view the buffer has been resized
7186        // away from has no indices, so `2 in view` is `false` even when
7187        // `Object.getPrototypeOf(view)[2]` exists (what
7188        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7189        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7190        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7191        // goes through here, which is why the same rule is repeated in `has_property_key`
7192        // rather than living only there.
7193        if object.typed_array_parts().is_some()
7194            && let Some(numeric) = canonical_numeric_index(key)
7195        {
7196            return Ok(typed_array_index_is_valid(object, numeric));
7197        }
7198        // A host class answers `in` for its own keys, which may live nowhere in a property
7199        // table — `"x" in point` is true because the class says so, not because a property
7200        // exists.
7201        if let Some(exotic) = object.exotic()
7202            && let Some(answer) = exotic.has_property(self, object, key)?
7203        {
7204            return Ok(answer);
7205        }
7206        // `has_own` rather than `own_property_key`: an array's elements and its derived
7207        // `length` are invisible to the property table, and `Array.prototype` is an array.
7208        // A host class's `get_own_property` counts too, because the reference's
7209        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7210        // lives — a class with only `get_own_property` answers `in` through it.
7211        if self.exotic_has_own(object, key)? {
7212            return Ok(true);
7213        }
7214        // A hole is *not* the end of the search: the chain may still have the key, which
7215        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7216        for ancestor in object.chain() {
7217            // A proxy further up the chain answers for itself.
7218            if let Some(answer) = self.proxy_has(&ancestor, key)? {
7219                return Ok(answer);
7220            }
7221            // Same for a host class: a prototype may be one, and `in` reaches it.
7222            if let Some(exotic) = ancestor.exotic()
7223                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7224            {
7225                return Ok(answer);
7226            }
7227            if self.exotic_has_own(&ancestor, key)? {
7228                return Ok(true);
7229            }
7230        }
7231        Ok(false)
7232    }
7233
7234    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7235    /// trap included.
7236    ///
7237    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7238    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7239    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7240        if let Some(exotic) = object.exotic()
7241            && let Some(answer) = exotic.get_own_property(self, object, key)?
7242        {
7243            return Ok(answer.is_some());
7244        }
7245        Ok(has_own(object, key))
7246    }
7247
7248    /// `CreateListFromArrayLike`, optionally restricted to property keys.
7249    ///
7250    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7251    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7252    /// `TypeError` instead of a property named `"1.5"`.
7253    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7254        let object = self.object_from(value)?;
7255        let length = self
7256            .get_property(&object, "length")?
7257            .map(|value| value.to_number())
7258            .unwrap_or(0.0);
7259        if !length.is_finite() || length < 0.0 {
7260            return Err(self.type_error("invalid array-like length"));
7261        }
7262        let length = length as usize;
7263        let mut items = Vec::with_capacity(length.min(1024));
7264        for index in 0..length {
7265            let item = self
7266                .get_property(&object, &index.to_string())?
7267                .unwrap_or(Value::Undefined);
7268            if keys_only && matches!(&item, Value::Symbol(_)) {
7269                items.push(item);
7270                continue;
7271            }
7272            if keys_only && !matches!(&item, Value::String(_)) {
7273                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7274            }
7275            items.push(item);
7276        }
7277        Ok(items)
7278    }
7279
7280    /// A `Property` from the descriptor object a trap returned.
7281    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7282        let object = self.object_from(value)?;
7283        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7284            interp.get_property(&object, name)
7285        };
7286        let getter = field(self, "get")?;
7287        let setter = field(self, "set")?;
7288        let accessor = getter.is_some() || setter.is_some();
7289        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7290            Ok(interp
7291                .get_property(&object, name)?
7292                .is_some_and(|value| value.to_boolean()))
7293        };
7294        let enumerable = boolean(self, "enumerable")?;
7295        let configurable = boolean(self, "configurable")?;
7296        if accessor {
7297            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7298                return Err(
7299                    self.type_error("a descriptor cannot be both a data property and an accessor")
7300                );
7301            }
7302            Ok(Property {
7303                getter: getter.or(Some(Value::Undefined)),
7304                setter: setter.or(Some(Value::Undefined)),
7305                enumerable,
7306                configurable,
7307                writable: false,
7308                value: None,
7309                descriptor_fields: None,
7310            })
7311        } else {
7312            Ok(Property {
7313                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7314                writable: boolean(self, "writable")?,
7315                enumerable,
7316                configurable,
7317                getter: None,
7318                setter: None,
7319                descriptor_fields: None,
7320            })
7321        }
7322    }
7323
7324    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7325    fn descriptor_from_property(&mut self, property: &Property) -> Value {
7326        let object = self.new_object(None);
7327        // A partial descriptor names only some fields, and the trap must see exactly those:
7328        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7329        // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7330        // case, where every field is present.
7331        let fields = property.descriptor_fields;
7332        let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7333            fields.is_none_or(|fields| field(&fields))
7334        };
7335        if property.is_accessor() {
7336            let getter = property.getter.clone().unwrap_or(Value::Undefined);
7337            let setter = property.setter.clone().unwrap_or(Value::Undefined);
7338            object.define_data("get", getter);
7339            object.define_data("set", setter);
7340        } else {
7341            if names(|fields| fields.value) {
7342                let value = property.value.clone().unwrap_or(Value::Undefined);
7343                object.define_data("value", value);
7344            }
7345            if names(|fields| fields.writable) {
7346                object.define_data("writable", Value::Bool(property.writable));
7347            }
7348        }
7349        if names(|fields| fields.enumerable) {
7350            object.define_data("enumerable", Value::Bool(property.enumerable));
7351        }
7352        if names(|fields| fields.configurable) {
7353            object.define_data("configurable", Value::Bool(property.configurable));
7354        }
7355        Value::Object(object)
7356    }
7357
7358    // -- calling ------------------------------------------------------------
7359
7360    /// Call `callee` with `this` and `args`.
7361    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7362        let Value::Object(function) = &callee else {
7363            // `typeof x === "function"` is not enough to make `x()` legal: only a
7364            // callable object is. `null` and `undefined` need no special wording
7365            // here — their `ToString` already reads the way the reference's does.
7366            let what = format!("{} is not a function", callee.to_js_string());
7367            return Err(Signal::Throw(self.make_error("TypeError", &what)));
7368        };
7369        // A proxy of a function is called through its `apply` trap. It has no
7370        // `ObjectKind::Function` of its own, so this has to come before the dispatch
7371        // below, and a proxy of a non-function has nothing to forward to.
7372        if function.proxy_state().is_some() {
7373            return match self.proxy_apply(function, this, args)? {
7374                Some(result) => Ok(result),
7375                None => Err(Signal::Throw(
7376                    self.make_error("TypeError", "proxy target is not callable"),
7377                )),
7378            };
7379        }
7380        let callable = function.with(|data| match &data.kind {
7381            ObjectKind::Function(callable) => match callable {
7382                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7383                // The `Rc` is cloned out so the borrow of this object's data is released
7384                // before the closure runs: the closure may touch the same object.
7385                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7386                Callable::Bound {
7387                    target,
7388                    this,
7389                    args: leading,
7390                } => Some(NativeCall::Bound {
7391                    target: target.clone(),
7392                    this: this.clone(),
7393                    leading: leading.clone(),
7394                }),
7395                Callable::Bytecode { code, env } => {
7396                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
7397                }
7398                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7399                Callable::PromiseResolve(promise) => {
7400                    Some(NativeCall::PromiseResolve(promise.clone()))
7401                }
7402                Callable::PromiseReject(promise) => {
7403                    Some(NativeCall::PromiseReject(promise.clone()))
7404                }
7405                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7406                    state: state.clone(),
7407                }),
7408                Callable::ThenShim {
7409                    handler,
7410                    resolve,
7411                    reject,
7412                    fulfilled,
7413                } => Some(NativeCall::ThenShim {
7414                    handler: handler.clone(),
7415                    resolve: resolve.clone(),
7416                    reject: reject.clone(),
7417                    fulfilled: *fulfilled,
7418                }),
7419                Callable::AwaitResume {
7420                    coroutine,
7421                    promise,
7422                    kind,
7423                } => Some(NativeCall::AwaitResume {
7424                    coroutine: coroutine.clone(),
7425                    promise: promise.clone(),
7426                    kind: *kind,
7427                }),
7428                Callable::CombinatorSettle {
7429                    state,
7430                    index,
7431                    fulfilled,
7432                } => Some(NativeCall::CombinatorSettle {
7433                    state: state.clone(),
7434                    index: *index,
7435                    fulfilled: *fulfilled,
7436                }),
7437                Callable::FinallyShim {
7438                    callback,
7439                    fulfilled,
7440                    constructor,
7441                } => Some(NativeCall::FinallyShim {
7442                    callback: callback.clone(),
7443                    fulfilled: *fulfilled,
7444                    constructor: constructor.clone(),
7445                }),
7446                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7447                Callable::CompletedReturn {
7448                    generator,
7449                    promise,
7450                    rejected,
7451                } => Some(NativeCall::CompletedReturn {
7452                    generator: generator.clone(),
7453                    promise: promise.clone(),
7454                    rejected: *rejected,
7455                }),
7456                Callable::YieldResult {
7457                    generator,
7458                    promise,
7459                    done,
7460                } => Some(NativeCall::YieldResult {
7461                    generator: generator.clone(),
7462                    promise: promise.clone(),
7463                    done: *done,
7464                }),
7465                Callable::DisposeStep {
7466                    remaining,
7467                    promise,
7468                    error,
7469                    rejected,
7470                } => Some(NativeCall::DisposeStep {
7471                    remaining: remaining.clone(),
7472                    promise: promise.clone(),
7473                    error: error.clone(),
7474                    rejected: *rejected,
7475                }),
7476                Callable::GeneratorResume {
7477                    generator,
7478                    promise,
7479                    kind,
7480                } => Some(NativeCall::GeneratorResume {
7481                    generator: generator.clone(),
7482                    promise: promise.clone(),
7483                    kind: *kind,
7484                }),
7485                Callable::SettlePromise {
7486                    promise,
7487                    value,
7488                    rejected,
7489                } => Some(NativeCall::SettlePromise {
7490                    promise: promise.clone(),
7491                    value: value.clone(),
7492                    rejected: *rejected,
7493                }),
7494            },
7495            _ => None,
7496        });
7497        match callable {
7498            Some(NativeCall::Host(func)) => {
7499                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7500                // function by name rather than stopping at the caller.
7501                let frame_less = function
7502                    .own_property("_frame_less")
7503                    .and_then(|property| property.value)
7504                    .is_some_and(|value| value.to_boolean());
7505                let outer = if frame_less {
7506                    None
7507                } else {
7508                    self.native_frames
7509                        .push((function.clone(), self.frames.len()));
7510                    Some(self.current_native.replace(function.clone()))
7511                };
7512                let result = {
7513                    let mut body = func.borrow_mut();
7514                    body(self, this, &args)
7515                };
7516                if !frame_less {
7517                    self.native_frames.pop();
7518                    self.current_native = outer.flatten();
7519                }
7520                result
7521            }
7522            Some(NativeCall::Native(func)) => {
7523                // A function marked `_frame_less` is one the reference implements
7524                // without a call frame — `eval` is the only one so far.
7525                let frame_less = function
7526                    .own_property("_frame_less")
7527                    .and_then(|property| property.value)
7528                    .is_some_and(|value| value.to_boolean());
7529                let outer = if frame_less {
7530                    None
7531                } else {
7532                    self.native_frames
7533                        .push((function.clone(), self.frames.len()));
7534                    Some(self.current_native.replace(function.clone()))
7535                };
7536                let result = func(self, this, &args);
7537                if !frame_less {
7538                    self.native_frames.pop();
7539                    self.current_native = outer.flatten();
7540                }
7541                result
7542            }
7543            Some(NativeCall::Revoker(slots)) => {
7544                // Idempotent: revoking twice answers `undefined` again rather than
7545                // complaining, which is what the spec says and what a `finally` block
7546                // relies on.
7547                let mut state = slots.borrow_mut();
7548                state.target = None;
7549                state.handler = None;
7550                Ok(Value::Undefined)
7551            }
7552            Some(NativeCall::PromiseResolve(promise)) => {
7553                // One-shot: a second call is silently ignored, which
7554                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7555                let value = args.first().cloned().unwrap_or(Value::Undefined);
7556                self.resolve_promise_with(&promise, value)?;
7557                Ok(Value::Undefined)
7558            }
7559            Some(NativeCall::PromiseReject(promise)) => {
7560                let reason = args.first().cloned().unwrap_or(Value::Undefined);
7561                self.reject_promise(&promise, reason);
7562                Ok(Value::Undefined)
7563            }
7564            Some(NativeCall::ThenShim {
7565                handler,
7566                resolve,
7567                reject,
7568                fulfilled,
7569            }) => {
7570                // `PerformPromiseThen` with a capability: run the handler, then settle
7571                // through the capability's own pair. A throw from the handler is the
7572                // rejection, and a throw from the capability's `resolve` is not caught —
7573                // exactly the spec's `?`.
7574                let value = args.first().cloned().unwrap_or(Value::Undefined);
7575                match handler {
7576                    Some(handler) => {
7577                        match self.call_value(handler, Value::Undefined, vec![value]) {
7578                            Ok(result) => {
7579                                self.call_value(resolve, Value::Undefined, vec![result])?;
7580                            }
7581                            Err(Signal::Throw(reason)) => {
7582                                self.call_value(reject, Value::Undefined, vec![reason])?;
7583                            }
7584                            Err(signal) => return Err(signal),
7585                        }
7586                    }
7587                    None => {
7588                        let handler = if fulfilled { resolve } else { reject };
7589                        self.call_value(handler, Value::Undefined, vec![value])?;
7590                    }
7591                }
7592                Ok(Value::Undefined)
7593            }
7594            Some(NativeCall::CapabilityExecutor { state }) => {
7595                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7596                // slot holds a value yet. The test is on the *values*, not on a call count —
7597                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7598                // called-twice`'s first case does exactly that), while a second call after a
7599                // real pair is the `TypeError`.
7600                let defined = |name: &str| {
7601                    state
7602                        .own_property(name)
7603                        .and_then(|property| property.value)
7604                        .is_some_and(|value| !matches!(value, Value::Undefined))
7605                };
7606                if defined("resolve") || defined("reject") {
7607                    return Err(self.type_error("promise capability executor called twice"));
7608                }
7609                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7610                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7611                state.define_data("resolve", resolve);
7612                state.define_data("reject", reject);
7613                Ok(Value::Undefined)
7614            }
7615            Some(NativeCall::CombinatorSettle {
7616                state,
7617                index,
7618                fulfilled,
7619            }) => {
7620                let value = args.first().cloned().unwrap_or(Value::Undefined);
7621                self.settle_combinator(&state, index, fulfilled, value)?;
7622                Ok(Value::Undefined)
7623            }
7624            Some(NativeCall::AwaitResume {
7625                coroutine,
7626                promise,
7627                kind,
7628            }) => {
7629                // Resume *inline*, in the reaction that delivered the value. Deferring it
7630                // by another job inserts a tick between every `await` and its
7631                // continuation, which reorders `await` against unrelated `then` chains —
7632                // `f().then(g)` then runs before `f`'s own next statement.
7633                self.drive_async(
7634                    &coroutine,
7635                    &promise,
7636                    kind,
7637                    args.first().cloned().unwrap_or(Value::Undefined),
7638                )
7639                .map(|()| Value::Undefined)
7640            }
7641            Some(NativeCall::FinallyShim {
7642                callback,
7643                fulfilled,
7644                constructor,
7645            }) => {
7646                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
7647                // that settles with the *original* outcome once the callback's result has
7648                // settled. The callback's own value is discarded — that is the whole
7649                // difference between `finally` and `then`.
7650                let original = args.first().cloned().unwrap_or(Value::Undefined);
7651                let result = match &callback {
7652                    Some(callback) => {
7653                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7654                    }
7655                    None => Value::Undefined,
7656                };
7657                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
7658                // already a promise of this constructor is reused rather than rewrapped.
7659                let resolved = self.promise_resolve_for(&constructor, result)?;
7660                let Value::Object(resolved) = resolved else {
7661                    return Ok(original);
7662                };
7663                // The wait is a chained promise rather than a bare return, so a callback
7664                // that returns a slow promise really does delay the continuation.
7665                let waiting = self.new_promise();
7666                let pass = JsObject::function(
7667                    self.heap,
7668                    Some(self.realm.function_proto.clone()),
7669                    Callable::SettlePromise {
7670                        promise: waiting.clone(),
7671                        value: original,
7672                        rejected: !fulfilled,
7673                    },
7674                );
7675                let pass = Value::Object(pass);
7676                // Whichever way the callback's promise settles, the original outcome wins.
7677                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
7678                Ok(Value::Object(waiting))
7679            }
7680            Some(NativeCall::DisposeStep {
7681                remaining,
7682                promise,
7683                error,
7684                rejected,
7685            }) => {
7686                let error = if rejected {
7687                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
7688                    self.merge_dispose_error(reason, error)
7689                } else {
7690                    error
7691                };
7692                self.dispose_step(&remaining, &promise, error)?;
7693                Ok(Value::Undefined)
7694            }
7695            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7696            Some(NativeCall::CompletedReturn {
7697                generator,
7698                promise,
7699                rejected,
7700            }) => {
7701                let value = args.first().cloned().unwrap_or(Value::Undefined);
7702                let outcome = if rejected {
7703                    AsyncOutcome::Error(value)
7704                } else {
7705                    AsyncOutcome::Value(self.iterator_result(value, true)?)
7706                };
7707                self.settle_async_request(&generator, &promise, outcome)?;
7708                Ok(Value::Undefined)
7709            }
7710            Some(NativeCall::YieldResult {
7711                generator,
7712                promise,
7713                done,
7714            }) => {
7715                let value = args.first().cloned().unwrap_or(Value::Undefined);
7716                let result = self.iterator_result(value, done)?;
7717                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7718                Ok(Value::Undefined)
7719            }
7720            Some(NativeCall::GeneratorResume {
7721                generator,
7722                promise,
7723                kind,
7724            }) => {
7725                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7726                // tick and reorders the generator against other chains.
7727                self.step_async_generator(
7728                    &generator,
7729                    &promise,
7730                    kind,
7731                    args.first().cloned().unwrap_or(Value::Undefined),
7732                )
7733                .map(|()| Value::Undefined)
7734            }
7735            Some(NativeCall::SettlePromise {
7736                promise,
7737                value,
7738                rejected,
7739            }) => {
7740                if rejected {
7741                    self.reject_promise(&promise, value);
7742                } else {
7743                    self.fulfill_promise(&promise, value);
7744                }
7745                Ok(Value::Undefined)
7746            }
7747            Some(NativeCall::Bound {
7748                target,
7749                this: bound_this,
7750                leading,
7751            }) => {
7752                let mut all = leading;
7753                all.extend(args);
7754                self.call_value(target, bound_this, all)
7755            }
7756            Some(NativeCall::Bytecode(code, env)) => {
7757                if code.code.kind.is_generator() {
7758                    return self.new_generator(callee, this, args);
7759                }
7760                if code.code.kind.is_async() {
7761                    // Same coroutine machinery as a generator; the difference is only in
7762                    // what the completion does — see `new_async_function`.
7763                    return self.new_async_function(callee, this, args);
7764                }
7765                self.execute(code, env, this, args, callee)
7766            }
7767            None => Err(Signal::Throw(
7768                self.make_error("TypeError", "not a function"),
7769            )),
7770        }
7771    }
7772
7773    /// Give a freshly built function its own `prototype` object.
7774    ///
7775    /// Every function that can be used with `new` carries one, and its
7776    /// `constructor` points back at the function — a reference cycle, which is
7777    /// exactly what the collector's cycle pass exists to reclaim.
7778    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7779        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
7780        let constructor = Value::Object(function.clone());
7781        prototype.define(
7782            "constructor",
7783            Property::with_attributes(constructor, true, false),
7784        );
7785        let value = Value::Object(prototype);
7786        function.define("prototype", Property::prototype_of(value, true));
7787    }
7788
7789    /// A getter or setter that reads or writes the reference cell behind a mapped
7790    /// `arguments` index.
7791    ///
7792    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
7793    /// count — which is what the collector treats as "a reference from outside the
7794    /// heap". The closure therefore keeps the cell alive for exactly as long as the
7795    /// accessor is reachable, which is the same lifetime the arguments object has.
7796    ///
7797    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
7798    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
7799    /// parameter value and the arguments object reaches the closure, never the other
7800    /// way round. Nothing the collector has to see is hidden.
7801    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
7802        let name = if is_setter { "set" } else { "get" };
7803        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
7804            if is_setter {
7805                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
7806                Ok(Value::Undefined)
7807            } else {
7808                Ok(cell.get())
7809            }
7810        };
7811        self.new_host_function(name, 1, Box::new(func))
7812    }
7813
7814    /// The object `special_object` builds.
7815    ///
7816    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
7817    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
7818    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
7819    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
7820    /// write through `arguments` does not reach the parameter.
7821    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
7822        match magic {
7823            0 | 1 => {
7824                let args = self.frame().passed().to_vec();
7825                let proto = self.realm.object_proto.clone();
7826                let object = self.new_object(Some(proto));
7827                // The marker `Object.prototype.toString` needs: an arguments object is an
7828                // ordinary object apart from reporting `[object Arguments]`, and that has
7829                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
7830                // show up ahead of them in a key listing anyway — it is non-enumerable.
7831                self.internal_set(&object, "_class", self.string("Arguments"));
7832                // `length` is writable and configurable but neither enumerable nor a
7833                // plain data property: `Object.keys(arguments)` lists the indices only,
7834                // which is how `{...arguments}` copies them without the length.
7835                object.define(
7836                    "length",
7837                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
7838                );
7839                // `magic == 1` is sloppy mode, where each index is *mapped* to the
7840                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
7841                // change `a`, and assigning `a` has to change `arguments[0]`.
7842                //
7843                // The shared storage is the parameter's reference cell. The compiler
7844                // gives every parameter of such a function one (see
7845                // `provide_body_arguments`), and the cell outlives the frame, so this
7846                // keeps working after the arguments object escapes.
7847                //
7848                // The index becomes an accessor rather than a data property. A mapped
7849                // index reports as a plain writable/enumerable data property through
7850                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
7851                // the getter/setter pair is only the plumbing underneath.
7852                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
7853                    let frame = self.frame();
7854                    frame
7855                        .code
7856                        .arg_cell
7857                        .iter()
7858                        .map(|cell| {
7859                            (*cell >= 0)
7860                                .then(|| frame.cells.get(*cell as usize).cloned())
7861                                .flatten()
7862                        })
7863                        .collect()
7864                } else {
7865                    Vec::new()
7866                };
7867                // Tell the object which indices are mapped, so
7868                // `Object.getOwnPropertyDescriptor` can report them as the data
7869                // properties the spec describes instead of the accessors that
7870                // implement the aliasing.
7871                if magic == 1 {
7872                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
7873                    for cell in &mapped_cells {
7874                        table.push(cell.clone());
7875                    }
7876                    object.set_mapped_arguments(table);
7877                }
7878                for (index, value) in args.into_iter().enumerate() {
7879                    match mapped_cells.get(index).cloned().flatten() {
7880                        Some(cell) => {
7881                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
7882                            let setter = self.new_mapped_arguments_accessor(cell, true);
7883                            object.define(
7884                                &index.to_string(),
7885                                Property::accessor_with(
7886                                    Some(Value::Object(getter)),
7887                                    Some(Value::Object(setter)),
7888                                    true,
7889                                ),
7890                            );
7891                        }
7892                        None => object.define_data(&index.to_string(), value),
7893                    }
7894                }
7895                // §10.4.4.6: an *unmapped* (strict) arguments object gets a
7896                // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
7897                // non-enumerable and non-configurable. It is not a nicety — it is the only
7898                // documented way to reach `%ThrowTypeError%`:
7899                //
7900                //     Object.getOwnPropertyDescriptor(function(){"use strict";
7901                //         return arguments;}(), "callee").get
7902                //
7903                // and the whole `ThrowTypeError/` directory is written against that
7904                // expression. Without it 13 cases failed with `cannot read property 'get'
7905                // of undefined`, which reads like a test harness bug rather than a missing
7906                // accessor.
7907                //
7908                // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
7909                // writable data property holding the function being called, and
7910                // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
7911                // `hasOwnProperty("callee")` hold there.
7912                if magic == 1 {
7913                    let callee = self.frame().callee.clone();
7914                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
7915                    object.define("callee", Property::with_attributes(callee, true, false));
7916                } else if let Some(thrower) = self.realm.throw_type_error.clone()
7917                    && object.own_property("callee").is_none()
7918                {
7919                    object.define(
7920                        "callee",
7921                        Property {
7922                            getter: Some(Value::Object(thrower.clone())),
7923                            setter: Some(Value::Object(thrower)),
7924                            enumerable: false,
7925                            configurable: false,
7926                            ..Property::default()
7927                        },
7928                    );
7929                }
7930                // An arguments object is iterable: `[...arguments]` and
7931                // `for (const a of arguments)` both work, through the *array* iterator
7932                // because the object is array-like. Without this the whole spread form
7933                // reported "not iterable".
7934                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
7935                let values = self
7936                    .realm
7937                    .array_proto
7938                    .own_property("values")
7939                    .and_then(|property| property.value);
7940                if let Some(values) = values {
7941                    object.define_key(
7942                        &iterator_key,
7943                        Property::with_attributes(values, true, false),
7944                    );
7945                }
7946                Ok(Value::Object(object))
7947            }
7948            // `this.active_func`: the constructor `super()` resolves against.
7949            //
7950            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
7951            // own, so it inherits this from the function it was written in along with `this`
7952            // — and that is a lexical relationship, not a stack one: an arrow that escaped
7953            // the constructor and is called back later (`iter.return = () => super()`) has
7954            // the constructor nowhere on the stack. The compiler therefore reads it out of
7955            // a closure variable of the enclosing function, exactly as the reference does
7956            // with its `this_active_func` local.
7957            2 => Ok(self
7958                .current_callee()
7959                .map_or(Value::Undefined, Value::Object)),
7960            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
7961            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
7962            // its own either, so the lookup walks out to the nearest non-arrow frame for
7963            // the same reason as `this.active_func` above — without that, `super()` inside
7964            // an arrow passed `undefined` as the new target and the parent constructor was
7965            // then rejected for being invoked without `new`.
7966            3 => Ok(self
7967                .eval_new_target
7968                .clone()
7969                .unwrap_or_else(|| self.frame().new_target.clone())),
7970            // `[[HomeObject]]` of the function being run: what `super` is relative to.
7971            // An arrow has none of its own, so the lookup walks out to the enclosing
7972            // method — which is why `super` works inside an arrow inside a method.
7973            4 => Ok(self
7974                .frames
7975                .iter()
7976                .rev()
7977                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7978                .map_or(Value::Undefined, Value::Object)),
7979            // `import.meta`: the innermost module body's meta object. Outside a module
7980            // the compiler never emits this, so an empty fallback is unreachable rather
7981            // than permissive.
7982            6 => {
7983                let name = self.module_stack.last().cloned();
7984                let meta = name
7985                    .and_then(|name| self.modules.get(&name).cloned())
7986                    .and_then(|module| module.with(|r| r.import_meta.clone()));
7987                Ok(meta.map_or(Value::Undefined, Value::Object))
7988            }
7989            other => Err(Signal::Throw(self.make_error(
7990                "InternalError",
7991                &format!("special_object {other} is not implemented yet"),
7992            ))),
7993        }
7994    }
7995
7996    /// `[[HomeObject]]` of the innermost function that has one, if any.
7997    ///
7998    /// An arrow has none, so the search walks out to the enclosing method — the same
7999    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8000    /// inside a method.
8001    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8002        self.frames
8003            .iter()
8004            .rev()
8005            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8006    }
8007
8008    /// The dispose method a `using` declaration should snapshot, or an error.
8009    ///
8010    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8011    /// is what makes a resource that only knows the synchronous protocol usable in both
8012    /// forms.
8013    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8014        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8015        if value.is_nullish() {
8016            return Ok(Value::Undefined);
8017        }
8018        let Some(object) = value.as_object() else {
8019            return Err(self.type_error("not an object"));
8020        };
8021        let mut method = if await_form {
8022            let found = self.get_property_key(
8023                object,
8024                &self.realm.well_known_key(WellKnown::AsyncDisposable),
8025            )?;
8026            match found {
8027                Some(found) if !found.is_nullish() => Some(found),
8028                _ => self
8029                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8030            }
8031        } else {
8032            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8033        };
8034        let Some(found) = method.take() else {
8035            return Err(self.type_error("value is not disposable"));
8036        };
8037        if found.is_nullish() {
8038            return Err(self.type_error("value is not disposable"));
8039        }
8040        let callable = found.as_object().is_some_and(|object| object.is_callable());
8041        if !callable {
8042            return Err(self.type_error("dispose method is not a function"));
8043        }
8044        Ok(found)
8045    }
8046
8047    /// Call one resource's disposer, folding a failure into `error_state`.
8048    ///
8049    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8050    /// because a captured `using` binding lives in its reference cell and the local slot is
8051    /// stale — a closure over the resource is legal and must not change what is disposed.
8052    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8053        let value = self.get_loc(slot);
8054        let method = self.get_loc(slot + 1);
8055        // A resource that was never initialised — its declaration threw — or that is
8056        // `null`/`undefined` has nothing to dispose.
8057        if value.is_nullish() || matches!(value, Value::Uninitialized) {
8058            return Ok(error_state);
8059        }
8060        if matches!(method, Value::Undefined | Value::Uninitialized) {
8061            return Ok(error_state);
8062        }
8063        match self.call_value(method, value, Vec::new()) {
8064            Ok(_) => Ok(error_state),
8065            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8066            Err(other) => Err(other),
8067        }
8068    }
8069
8070    /// Combine a disposal failure with whatever was already going wrong.
8071    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8072        if matches!(error_state, Value::Uninitialized) {
8073            return new_error;
8074        }
8075        self.new_suppressed_error(new_error, error_state)
8076    }
8077
8078    /// A `SuppressedError` instance built straight from its prototype.
8079    ///
8080    /// Not through the constructor: a script that rewrites
8081    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8082    /// error wrapping.
8083    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8084        let proto = self
8085            .realm
8086            .suppressed_error_proto
8087            .clone()
8088            .unwrap_or_else(|| self.realm.error_proto.clone());
8089        let object = self.new_object(Some(proto));
8090        object.define("error", Property::with_attributes(error, true, true));
8091        object.define(
8092            "suppressed",
8093            Property::with_attributes(suppressed, true, true),
8094        );
8095        object.define(
8096            "message",
8097            Property::with_attributes(self.string("SuppressedError"), true, true),
8098        );
8099        self.internal_set(&object, "_class", self.string("Error"));
8100        self.add_stack(&object);
8101        Value::Object(object)
8102    }
8103
8104    /// Call `callee`, or push its frame and let the main loop run it.
8105    ///
8106    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8107    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8108    /// continues, so `function f(){ return f() }` costs heap and stops at
8109    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8110    /// is entered directly, and natives do not re-enter JavaScript in this
8111    /// milestone.
8112    ///
8113    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8114    /// because the returning frame will.
8115    /// The elements of an array-like value, as a call argument list.
8116    ///
8117    /// `apply` accepts any array-like, not only a real array: the reference reads
8118    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8119    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8120        let Some(object) = value.as_object().cloned() else {
8121            if value.is_nullish() {
8122                // `f.apply(this, null)` passes no arguments at all.
8123                return Ok(Vec::new());
8124            }
8125            return Err(self.type_error("createListFromArrayLike called on non-object"));
8126        };
8127        let length = match self.get_property(&object, "length")? {
8128            Some(length) => length.to_number(),
8129            None => 0.0,
8130        };
8131        if !length.is_finite() || length <= 0.0 {
8132            return Ok(Vec::new());
8133        }
8134        let length = (length as usize).min(1_000_000);
8135        let mut args = Vec::with_capacity(length);
8136        for index in 0..length {
8137            let element = self.get_property(&object, &index.to_string())?;
8138            args.push(element.unwrap_or(Value::Undefined));
8139        }
8140        Ok(args)
8141    }
8142
8143    /// Turn a call to a generator function into a generator object.
8144    ///
8145    /// The frame is built exactly as an ordinary call would build it, then detached and
8146    /// stored in the generator before any body instruction runs — which is what makes
8147    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8148    /// is `initial_yield`, the first instruction of every suspending body.
8149    pub fn new_generator(
8150        &mut self,
8151        function: Value,
8152        this: Value,
8153        args: Vec<Value>,
8154    ) -> JsResult<Value> {
8155        let Some(object) = function.as_object().cloned() else {
8156            return Err(self.type_error("not a generator function"));
8157        };
8158        let Some((code, env)) = bytecode_of(&object) else {
8159            return Err(self.type_error("not a generator function"));
8160        };
8161        let is_async = code.code.kind.is_async();
8162        self.push_frame(code, env, this, args, function)?;
8163        let frame = self.frames.pop().expect("push_frame just pushed it");
8164        // A fresh generator is *suspended at start*: the body has not run, so a
8165        // `return`/`throw` on it finishes without executing anything.
8166        let mut state = GeneratorState {
8167            frame: Some(frame),
8168            phase: GeneratorPhase::SuspendedStart,
8169            parked_on_await: false,
8170            parked_on_yield_star: false,
8171            requests: std::collections::VecDeque::new(),
8172            async_busy: false,
8173        };
8174        // Run to the first suspension. For a generator that is `initial_yield`, so no
8175        // body code runs; for a malformed body it would be the first `yield`.
8176        // An `async function*` answers an async generator: same coroutine, but its
8177        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8178        let proto = if is_async {
8179            self.realm
8180                .async_generator_proto
8181                .clone()
8182                .unwrap_or_else(|| self.realm.generator_proto.clone())
8183        } else {
8184            self.realm.generator_proto.clone()
8185        };
8186        let generator = self.new_object(Some(proto));
8187        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8188            Ok(_) => {}
8189            Err(error) => return Err(error),
8190        }
8191        generator.with_mut(|data| {
8192            data.kind = ObjectKind::Generator(Box::new(state));
8193        });
8194        Ok(Value::Object(generator))
8195    }
8196
8197    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8198    ///
8199    /// Returns the `{value, done}` object itself rather than the pair, because a
8200    /// `yield*` suspension already has one — the inner iterator's own result — and the
8201    /// protocol says to hand that straight through rather than nest it.
8202    /// Advance a generator and report *why* it parked.
8203    ///
8204    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8205    /// "hand this value to the caller" — but an async generator does: an `await` has to
8206    /// settle before it can answer, while a `yield` is the answer.
8207    fn resume_generator_detailed(
8208        &mut self,
8209        generator: &Gc<JsObject>,
8210        kind: ResumeKind,
8211        value: Value,
8212    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8213        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8214            ObjectKind::Generator(state) => Some(std::mem::replace(
8215                state.as_mut(),
8216                GeneratorState {
8217                    frame: None,
8218                    phase: GeneratorPhase::Executing,
8219                    parked_on_await: false,
8220                    parked_on_yield_star: false,
8221                    requests: std::collections::VecDeque::new(),
8222                    async_busy: false,
8223                },
8224            )),
8225            _ => None,
8226        }) else {
8227            return Err(self.type_error("not a generator"));
8228        };
8229        let result = self.step_generator(&mut state, kind, value);
8230        generator.with_mut(|data| {
8231            data.kind = ObjectKind::Generator(Box::new(state));
8232        });
8233        result
8234    }
8235
8236    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8237    ///
8238    /// Returns the `{value, done}` object itself rather than the pair, because a
8239    /// `yield*` suspension already has one — the inner iterator's own result — and the
8240    /// protocol says to hand that straight through rather than nest it.
8241    pub fn resume_generator(
8242        &mut self,
8243        generator: &Gc<JsObject>,
8244        kind: ResumeKind,
8245        value: Value,
8246    ) -> JsResult<Value> {
8247        let (value, done, ready, _reason) =
8248            self.resume_generator_detailed(generator, kind, value)?;
8249        if ready {
8250            return Ok(value);
8251        }
8252        self.iterator_result(value, done)
8253    }
8254
8255    /// `next`/`return`/`throw` on an async generator, which answer a promise.
8256    ///
8257    /// The body is the same coroutine a sync generator runs; what changes is that an
8258    /// `await` inside it has to settle before the method can answer, so the step is
8259    /// driven off the job queue rather than returning inline.
8260    pub fn resume_async_generator(
8261        &mut self,
8262        generator: &Gc<JsObject>,
8263        kind: ResumeKind,
8264        value: Value,
8265    ) -> JsResult<Value> {
8266        let promise = self.new_promise();
8267        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8268        // that order, and the second value must reach the *second* `yield`.
8269        let idle = generator.with_mut(|data| match &mut data.kind {
8270            ObjectKind::Generator(state) => {
8271                state.requests.push_back(AsyncRequest {
8272                    kind,
8273                    value,
8274                    promise: promise.clone(),
8275                });
8276                !state.async_busy
8277            }
8278            _ => false,
8279        });
8280        if idle {
8281            self.next_async_request(generator)?;
8282        }
8283        Ok(Value::Object(promise))
8284    }
8285
8286    /// Serve the front queued request, if the generator is free to run one.
8287    ///
8288    /// A finished generator answers from the queue without running anything:
8289    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8290    /// first, and `throw(e)` rejects.
8291    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8292        enum Front {
8293            Idle,
8294            Run(ResumeKind, Value, Gc<JsObject>),
8295            Finished(ResumeKind, Value, Gc<JsObject>),
8296        }
8297        let front = generator.with_mut(|data| match &mut data.kind {
8298            ObjectKind::Generator(state) => {
8299                let Some(request) = state.requests.front() else {
8300                    return Front::Idle;
8301                };
8302                // Busy means a request is still in flight — awaiting inside the body, not
8303                // finished. Serving another now would interleave two requests.
8304                if state.async_busy && state.phase != GeneratorPhase::Completed {
8305                    return Front::Idle;
8306                }
8307                let kind = request.kind;
8308                let value = request.value.clone();
8309                let promise = request.promise.clone();
8310                state.async_busy = true;
8311                if state.phase == GeneratorPhase::Completed {
8312                    Front::Finished(kind, value, promise)
8313                } else {
8314                    Front::Run(kind, value, promise)
8315                }
8316            }
8317            _ => Front::Idle,
8318        });
8319        match front {
8320            Front::Idle => Ok(()),
8321            Front::Run(kind, value, promise) => {
8322                self.step_async_generator(generator, &promise, kind, value)
8323            }
8324            Front::Finished(kind, value, promise) => match kind {
8325                ResumeKind::Throw => {
8326                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8327                }
8328                ResumeKind::Next | ResumeKind::Start => {
8329                    let result = self.iterator_result(Value::Undefined, true)?;
8330                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8331                }
8332                ResumeKind::Return => {
8333                    // `js_async_generator_completed_return`: the value is awaited before it
8334                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8335                    // finished generator answers `1`, not a promise.
8336                    let resolved = match self.promise_resolve_value(value) {
8337                        Ok(resolved) => resolved,
8338                        Err(Signal::Throw(reason)) => {
8339                            return self.settle_async_request(
8340                                generator,
8341                                &promise,
8342                                AsyncOutcome::Error(reason),
8343                            );
8344                        }
8345                        Err(other) => return Err(other),
8346                    };
8347                    let done = JsObject::function(
8348                        self.heap,
8349                        Some(self.realm.function_proto.clone()),
8350                        Callable::CompletedReturn {
8351                            generator: generator.clone(),
8352                            promise: promise.clone(),
8353                            rejected: false,
8354                        },
8355                    );
8356                    let failed = JsObject::function(
8357                        self.heap,
8358                        Some(self.realm.function_proto.clone()),
8359                        Callable::CompletedReturn {
8360                            generator: generator.clone(),
8361                            promise: promise.clone(),
8362                            rejected: true,
8363                        },
8364                    );
8365                    let Value::Object(resolved) = resolved else {
8366                        return self.settle_async_request(
8367                            generator,
8368                            &promise,
8369                            AsyncOutcome::Error(Value::Undefined),
8370                        );
8371                    };
8372                    self.perform_then(
8373                        &resolved,
8374                        Some(Value::Object(done)),
8375                        Some(Value::Object(failed)),
8376                    )?;
8377                    Ok(())
8378                }
8379            },
8380        }
8381    }
8382
8383    /// Settle the front request and start the next one.
8384    ///
8385    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
8386    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
8387    /// generator would strand every later request.
8388    fn settle_async_request(
8389        &mut self,
8390        generator: &Gc<JsObject>,
8391        promise: &Gc<JsObject>,
8392        outcome: AsyncOutcome,
8393    ) -> JsResult<()> {
8394        let settled = generator.with_mut(|data| match &mut data.kind {
8395            ObjectKind::Generator(state) => {
8396                let front = state.requests.front();
8397                debug_assert!(
8398                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8399                    "a request settled outside its turn"
8400                );
8401                state.requests.pop_front();
8402                state.async_busy = false;
8403                true
8404            }
8405            _ => false,
8406        });
8407        if settled {
8408            match outcome {
8409                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8410                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8411            }
8412        }
8413        self.next_async_request(generator)
8414    }
8415
8416    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8417    ///
8418    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8419    /// disposer runs **synchronously** — the reference starts it before returning, which
8420    /// a test can observe by logging after the call — and the rest follow once their
8421    /// predecessor settles.
8422    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8423        let promise = self.new_promise();
8424        let mut pairs = Vec::with_capacity(resources.len());
8425        for (value, method) in resources {
8426            let pair = self.new_array(vec![value, method]);
8427            pairs.push(Value::Object(pair));
8428        }
8429        let remaining = self.new_array(pairs);
8430        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
8431        Ok(Value::Object(promise))
8432    }
8433
8434    /// One link of the `disposeAsync` chain.
8435    ///
8436    /// Loops while the disposers finish synchronously, and parks on the first thenable it
8437    /// meets — pushing itself back in as the continuation, with the accumulated error
8438    /// carried along so a later failure can still be folded into the `SuppressedError`.
8439    fn dispose_step(
8440        &mut self,
8441        remaining: &Gc<JsObject>,
8442        promise: &Gc<JsObject>,
8443        mut error: Value,
8444    ) -> JsResult<()> {
8445        loop {
8446            let length = remaining.array_length().unwrap_or(0);
8447            if length == 0 {
8448                if matches!(error, Value::Uninitialized) {
8449                    self.fulfill_promise(promise, Value::Undefined);
8450                } else {
8451                    self.reject_promise(promise, error);
8452                }
8453                return Ok(());
8454            }
8455            let Some(Value::Object(pair)) = remaining
8456                .array_get(length - 1)
8457                .filter(|v| !matches!(v, Value::Hole))
8458            else {
8459                remaining.array_truncate(self.heap, length - 1);
8460                continue;
8461            };
8462            remaining.array_truncate(self.heap, length - 1);
8463            let value = pair.array_get(0).unwrap_or(Value::Undefined);
8464            let Some(Value::Object(method)) = pair.array_get(1) else {
8465                continue;
8466            };
8467            if !method.is_callable() {
8468                continue;
8469            }
8470            match self.call_value(Value::Object(method), value, Vec::new()) {
8471                Ok(result) => {
8472                    if !self.is_thenable(&result)? {
8473                        // Finished synchronously; the next disposer is the next iteration.
8474                        continue;
8475                    }
8476                    let awaited = match self.promise_resolve_value(result) {
8477                        Ok(awaited) => awaited,
8478                        Err(Signal::Throw(reason)) => {
8479                            self.reject_promise(promise, reason);
8480                            return Ok(());
8481                        }
8482                        Err(other) => return Err(other),
8483                    };
8484                    let Value::Object(awaited) = awaited else {
8485                        continue;
8486                    };
8487                    let ok = JsObject::function(
8488                        self.heap,
8489                        Some(self.realm.function_proto.clone()),
8490                        Callable::DisposeStep {
8491                            remaining: remaining.clone(),
8492                            promise: promise.clone(),
8493                            error: error.clone(),
8494                            rejected: false,
8495                        },
8496                    );
8497                    let failed = JsObject::function(
8498                        self.heap,
8499                        Some(self.realm.function_proto.clone()),
8500                        Callable::DisposeStep {
8501                            remaining: remaining.clone(),
8502                            promise: promise.clone(),
8503                            error,
8504                            rejected: true,
8505                        },
8506                    );
8507                    self.perform_then(
8508                        &awaited,
8509                        Some(Value::Object(ok)),
8510                        Some(Value::Object(failed)),
8511                    )?;
8512                    return Ok(());
8513                }
8514                Err(Signal::Throw(thrown)) => {
8515                    error = self.merge_dispose_error(thrown, error);
8516                }
8517                Err(other) => return Err(other),
8518            }
8519        }
8520    }
8521
8522    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8523    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8524        let Value::Object(object) = value else {
8525            return Ok(false);
8526        };
8527        Ok(matches!(
8528            self.get_property(object, "then")?,
8529            Some(Value::Object(then)) if then.is_callable()
8530        ))
8531    }
8532
8533    /// One step of an async generator, settling `promise` with an `{value, done}` result.
8534    fn step_async_generator(
8535        &mut self,
8536        generator: &Gc<JsObject>,
8537        promise: &Gc<JsObject>,
8538        kind: ResumeKind,
8539        value: Value,
8540    ) -> JsResult<()> {
8541        let stepped = self.resume_generator_detailed(generator, kind, value);
8542        let (value, done, ready, reason) = match stepped {
8543            Ok(stepped) => stepped,
8544            Err(Signal::Throw(reason)) => {
8545                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8546            }
8547            Err(other) => return Err(other),
8548        };
8549        // Only an `await` has to wait before the method can answer.
8550        if !done && reason == Some(SuspendKind::Await) {
8551            let awaited = match self.promise_resolve_value(value) {
8552                Ok(awaited) => awaited,
8553                Err(Signal::Throw(reason)) => {
8554                    return self.settle_async_request(
8555                        generator,
8556                        promise,
8557                        AsyncOutcome::Error(reason),
8558                    );
8559                }
8560                Err(other) => return Err(other),
8561            };
8562            let Value::Object(awaited) = awaited else {
8563                return Ok(());
8564            };
8565            let resumed = JsObject::function(
8566                self.heap,
8567                Some(self.realm.function_proto.clone()),
8568                Callable::GeneratorResume {
8569                    generator: generator.clone(),
8570                    promise: promise.clone(),
8571                    kind: ResumeKind::Next,
8572                },
8573            );
8574            let raised = JsObject::function(
8575                self.heap,
8576                Some(self.realm.function_proto.clone()),
8577                Callable::GeneratorResume {
8578                    generator: generator.clone(),
8579                    promise: promise.clone(),
8580                    kind: ResumeKind::Throw,
8581                },
8582            );
8583            self.perform_then(
8584                &awaited,
8585                Some(Value::Object(resumed)),
8586                Some(Value::Object(raised)),
8587            )?;
8588            return Ok(());
8589        }
8590        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8591        // completes it — both arrive as the settled value rather than as the promise
8592        // object. A plain value skips the round trip, which is also what keeps `yield 1`
8593        // from costing an extra tick.
8594        let awaits_value = self.is_thenable(&value)?;
8595        if awaits_value {
8596            let awaited = match self.promise_resolve_value(value) {
8597                Ok(awaited) => awaited,
8598                Err(Signal::Throw(reason)) => {
8599                    return self.settle_async_request(
8600                        generator,
8601                        promise,
8602                        AsyncOutcome::Error(reason),
8603                    );
8604                }
8605                Err(other) => return Err(other),
8606            };
8607            let Value::Object(awaited) = awaited else {
8608                return Ok(());
8609            };
8610            // A rejected yield throws *at the yield* inside the body, so the rejection
8611            // resumes the generator rather than the method's promise.
8612            let answer = JsObject::function(
8613                self.heap,
8614                Some(self.realm.function_proto.clone()),
8615                Callable::YieldResult {
8616                    generator: generator.clone(),
8617                    promise: promise.clone(),
8618                    done,
8619                },
8620            );
8621            let raise = JsObject::function(
8622                self.heap,
8623                Some(self.realm.function_proto.clone()),
8624                Callable::GeneratorResume {
8625                    generator: generator.clone(),
8626                    promise: promise.clone(),
8627                    kind: ResumeKind::Throw,
8628                },
8629            );
8630            self.perform_then(
8631                &awaited,
8632                Some(Value::Object(answer)),
8633                Some(Value::Object(raise)),
8634            )?;
8635            return Ok(());
8636        }
8637        let result = if ready {
8638            // `yield*` handed back the inner iterator's own result object.
8639            value
8640        } else {
8641            self.iterator_result(value, done)?
8642        };
8643        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8644    }
8645
8646    /// The `{value, done}` object an iterator method answers with.
8647    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8648        let result = self.new_object(Some(self.realm.object_proto.clone()));
8649        result.define_data("value", value);
8650        result.define_data("done", Value::Bool(done));
8651        Ok(Value::Object(result))
8652    }
8653
8654    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8655    fn step_generator(
8656        &mut self,
8657        state: &mut GeneratorState,
8658        kind: ResumeKind,
8659        value: Value,
8660    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8661        match state.phase {
8662            GeneratorPhase::Executing => {
8663                return Err(self.type_error("cannot invoke a running generator"));
8664            }
8665            GeneratorPhase::Completed => {
8666                // A finished generator answers every resumption without running.
8667                return Ok(match kind {
8668                    ResumeKind::Throw => return Err(Signal::Throw(value)),
8669                    ResumeKind::Return => (value, true, false, None),
8670                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8671                });
8672            }
8673            GeneratorPhase::SuspendedStart => {
8674                if kind != ResumeKind::Next && kind != ResumeKind::Start {
8675                    // The body never started, so there is nothing to unwind or return
8676                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8677                    state.frame = None;
8678                    state.phase = GeneratorPhase::Completed;
8679                    return Ok(match kind {
8680                        ResumeKind::Throw => return Err(Signal::Throw(value)),
8681                        _ => (value, true, false, None),
8682                    });
8683                }
8684            }
8685            GeneratorPhase::SuspendedYield => {}
8686        }
8687
8688        let Some(mut frame) = state.frame.take() else {
8689            return Ok((Value::Undefined, true, false, None));
8690        };
8691        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
8692        // number that says which method resumed it; the emitted `if_false` branches on
8693        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
8694        let mut raised = None;
8695        match kind {
8696            ResumeKind::Next | ResumeKind::Start => {
8697                if state.phase == GeneratorPhase::SuspendedYield {
8698                    frame.stack.push(value);
8699                    // An `await` resumes with its value alone; only a `yield` gets the
8700                    // magic number that says which of `next`/`return` resumed it.
8701                    if !state.parked_on_await {
8702                        frame.stack.push(Value::Int(RESUME_NEXT));
8703                    }
8704                }
8705            }
8706            ResumeKind::Return => {
8707                // A `return` on a not-yet-started generator is handled above, so this is
8708                // always a real resumption.
8709                frame.stack.push(value);
8710                frame.stack.push(Value::Int(RESUME_RETURN));
8711            }
8712            ResumeKind::Throw => {
8713                // At a `yield*` the exception is *data* for the delegation: the compiled
8714                // code resumes with the value and magic `2` and calls the inner iterator's
8715                // `throw`. Everywhere else it is raised at the suspension point, so the
8716                // body's own handler sees it.
8717                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
8718                    frame.stack.push(value);
8719                    frame.stack.push(Value::Int(RESUME_THROW));
8720                } else {
8721                    raised = Some(value);
8722                }
8723            }
8724        }
8725        state.phase = GeneratorPhase::Executing;
8726
8727        let depth = self.frames.len();
8728        self.frames.push(frame);
8729        // A `throw` unwinds from where the frame parked, exactly as if the exception had
8730        // happened at the `yield`.
8731        if let Some(exception) = raised {
8732            if self.catch_here(exception.clone()).is_none() {
8733                self.pop_frame();
8734                state.phase = GeneratorPhase::Completed;
8735                return Err(Signal::Throw(exception));
8736            }
8737        }
8738
8739        // Only the generator's *own* frame ends the generator. The body may call ordinary
8740        // functions, and those push frames of their own: a `Step::Return` from one of them
8741        // is a nested call finishing, not the generator completing. Miscounting that is
8742        // silent — the generator reports the callee's value as its own result and marks
8743        // itself done — so the depth comparison is load-bearing, not defensive.
8744        let own_frame = depth + 1;
8745        loop {
8746            match self.step() {
8747                Ok(Step::Continue) => {}
8748                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
8749                    let mut frame = self.frames.pop().expect("a frame is live");
8750                    // `yield` left the value on the stack; `initial_yield` left nothing.
8751                    let yielded = if reason == SuspendKind::Initial {
8752                        Value::Undefined
8753                    } else {
8754                        frame.stack.pop().unwrap_or(Value::Undefined)
8755                    };
8756                    state.frame = Some(frame);
8757                    state.parked_on_await = reason == SuspendKind::Await;
8758                    state.parked_on_yield_star =
8759                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
8760                    state.phase = if reason == SuspendKind::Initial {
8761                        GeneratorPhase::SuspendedStart
8762                    } else {
8763                        GeneratorPhase::SuspendedYield
8764                    };
8765                    // `yield*` hands the inner iterator's own result object straight
8766                    // back, so the caller sees one `{value, done}` rather than a nested
8767                    // one — which is why the third field says "already a result".
8768                    return Ok((
8769                        yielded,
8770                        false,
8771                        reason == SuspendKind::YieldStar,
8772                        Some(reason),
8773                    ));
8774                }
8775                Ok(Step::Suspend(_)) => {
8776                    // A `yield` in a frame other than the generator's would mean a
8777                    // generator body entered as an ordinary call, which
8778                    // `call_or_push` prevents.
8779                    self.unwind_to(depth);
8780                    state.phase = GeneratorPhase::Completed;
8781                    return Err(Signal::Throw(self.make_error(
8782                        "InternalError",
8783                        "a generator body ran as an ordinary call",
8784                    )));
8785                }
8786                Ok(Step::Return(value)) => {
8787                    self.pop_frame();
8788                    if self.frames.len() > depth {
8789                        // A nested call finished: hand the value back to its caller and
8790                        // keep running the generator body.
8791                        self.frames
8792                            .last_mut()
8793                            .expect("a caller is live")
8794                            .stack
8795                            .push(value);
8796                        continue;
8797                    }
8798                    state.phase = GeneratorPhase::Completed;
8799                    // The reference closes the generator's closure variables here; ours
8800                    // live in cells the frame owned, which the drop below releases.
8801                    return Ok((value, true, false, None));
8802                }
8803                Err(Signal::Throw(exception)) => {
8804                    // The frame that threw gets the first chance to catch, exactly as in
8805                    // the ordinary call loop; a frame above the generator's is popped and
8806                    // the exception carries on down.
8807                    let exception = exception;
8808                    loop {
8809                        if self.frames.len() <= depth {
8810                            // The generator's own frame is gone, so nothing here caught it.
8811                            state.phase = GeneratorPhase::Completed;
8812                            return Err(Signal::Throw(exception));
8813                        }
8814                        if self.catch_here(exception.clone()).is_some() {
8815                            break;
8816                        }
8817                        self.pop_frame();
8818                    }
8819                }
8820                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
8821            }
8822        }
8823    }
8824
8825    /// Pop frames until `depth` are left, keeping their buffers.
8826    fn unwind_to(&mut self, depth: usize) {
8827        while self.frames.len() > depth {
8828            self.pop_frame();
8829        }
8830    }
8831    fn call_or_push(
8832        &mut self,
8833        callee: Value,
8834        this: Value,
8835        args: Vec<Value>,
8836    ) -> JsResult<Option<Value>> {
8837        if let Value::Object(function) = &callee
8838            && let Some((code, env)) = bytecode_of(function)
8839        {
8840            // Calling a generator function does not run anything: it captures the
8841            // arguments in a frame and hands back the generator object.
8842            if code.code.kind.is_generator() {
8843                return self.new_generator(callee, this, args).map(Some);
8844            }
8845            // An async function answers a promise and runs its body as a coroutine, so it
8846            // takes the same path as a plain call into it.
8847            if code.code.kind.is_async() {
8848                return self.new_async_function(callee, this, args).map(Some);
8849            }
8850            self.push_frame(code, env, this, args, callee)?;
8851            return Ok(None);
8852        }
8853        self.call_value(callee, this, args).map(Some)
8854    }
8855
8856    /// `new callee(args)`.
8857    ///
8858    /// A constructor differs from a plain call in three ways: it gets a fresh object
8859    /// as `this` whose prototype is the constructor's `prototype` property, its
8860    /// return value is *replaced* by that object unless it returns an object itself,
8861    /// and a native constructor is expected to initialise the object it is given
8862    /// rather than build one.
8863    pub fn construct(
8864        &mut self,
8865        callee: Value,
8866        new_target: Value,
8867        args: Vec<Value>,
8868    ) -> JsResult<Value> {
8869        // `new` on a bound function constructs its *target*, prepending the arguments
8870        // the bind fixed and ignoring the bound `this` — a bound function is a
8871        // constructor only when its target is one, and `new` always makes a fresh
8872        // object of the target's prototype rather than reusing the bound receiver.
8873        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
8874        // ran the body with `this === null` and threw on `this.x = a`.
8875        let mut callee = callee;
8876        let mut new_target = new_target;
8877        let mut args = args;
8878        loop {
8879            let Some(object) = callee.as_object().cloned() else {
8880                return Err(Signal::Throw(
8881                    self.make_error("TypeError", "not a constructor"),
8882                ));
8883            };
8884            // A proxy of a function constructs through its `construct` trap, and the
8885            // trap's answer is the result directly — no fresh object is made here.
8886            if object.proxy_state().is_some() {
8887                return match self.proxy_construct(&object, args, &new_target)? {
8888                    Some(result) => Ok(result),
8889                    None => Err(Signal::Throw(
8890                        self.make_error("TypeError", "proxy target is not a constructor"),
8891                    )),
8892                };
8893            }
8894            // A generator function has no `[[Construct]]`, and the reference names it in
8895            // the message: `new (function* G(){})()` reports "G is not a constructor".
8896            if object.with(|data| match &data.kind {
8897                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
8898                    code.code.kind.is_generator()
8899                }
8900                _ => false,
8901            }) {
8902                let name = object
8903                    .own_property("name")
8904                    .and_then(|property| property.value)
8905                    .map(|value| value.to_js_string())
8906                    .unwrap_or_default();
8907                return Err(Signal::Throw(
8908                    self.make_error("TypeError", &format!("{name} is not a constructor")),
8909                ));
8910            }
8911            let bound = object.with(|data| match &data.kind {
8912                ObjectKind::Function(Callable::Bound {
8913                    target,
8914                    args: leading,
8915                    ..
8916                }) => Some((target.clone(), leading.clone())),
8917                _ => None,
8918            });
8919            let Some((target, leading)) = bound else {
8920                // Not a bound function, so this object is the callee. §7.2.4
8921                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
8922                // refusals above cover only the built-ins the reference also refuses by
8923                // name. Everything else — a method, an arrow, an async function — has no
8924                // `[[Construct]]` either, and answering "yes" here made
8925                // `new (Array.prototype.map)` build an object instead of throwing.
8926                if !object.is_constructor() {
8927                    let name = object
8928                        .own_property("name")
8929                        .and_then(|property| property.value)
8930                        .map(|value| value.to_js_string())
8931                        .unwrap_or_default();
8932                    return Err(Signal::Throw(
8933                        self.make_error("TypeError", &format!("{name} is not a constructor")),
8934                    ));
8935                }
8936                break;
8937            };
8938            let mut all = leading;
8939            all.extend(args);
8940            args = all;
8941            // A bound function that is its own `new.target` stands in for its target:
8942            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
8943            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
8944            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
8945                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
8946                _ => false,
8947            };
8948            if same_wrapper {
8949                new_target = target.clone();
8950            }
8951            callee = target;
8952        }
8953        let Value::Object(function) = &callee else {
8954            unreachable!("the loop above only breaks on an object");
8955        };
8956        // The fresh object's prototype comes from `new.target`, not from the callee: a
8957        // derived constructor reaches here through `super()`, and the instance must be a
8958        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
8959        // an object inheriting `D.prototype` rather than `C.prototype`.
8960        let prototype_source = match new_target.as_object() {
8961            Some(target) => target.clone(),
8962            None => function.clone(),
8963        };
8964        // A native constructor builds its own instance, through `new_ctor_instance`, once it
8965        // has validated its arguments. Pre-building one here would read
8966        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
8967        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
8968        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
8969        let is_native = function.native_creates_own_instance();
8970        let this = if is_native {
8971            Value::Undefined
8972        } else {
8973            let prototype = self.get_property(&prototype_source, "prototype")?;
8974            let prototype = match prototype {
8975                Some(Value::Object(proto)) => Some(proto),
8976                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
8977                // object, the answer is the realm's *intrinsic* prototype for this
8978                // constructor, not `%Object.prototype%`.
8979                _ => {
8980                    let fallback = self.get_property(function, "prototype")?;
8981                    match fallback {
8982                        Some(Value::Object(proto)) => Some(proto),
8983                        _ => Some(self.realm.object_proto.clone()),
8984                    }
8985                }
8986            };
8987            Value::Object(self.new_object(prototype))
8988        };
8989        // `new.target` inside the body is the constructor that was written, so a bound
8990        // function's target sees itself rather than the bound wrapper.
8991        //
8992        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
8993        // `?`, so assigning `None` after the call would be skipped and the failed
8994        // `new.target` would stay visible to every later native call. The symptom was a
8995        // native constructor refusing a plain call — `var s = Symbol(); new
8996        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
8997        // "FinalizationRegistry is not a constructor".
8998        let outer_new_target = self.pending_new_target.replace(new_target);
8999        let result = self.call_value(callee, this.clone(), args);
9000        self.pending_new_target = outer_new_target;
9001        let result = result?;
9002        // A constructor that returns an object overrides `this`; any other return
9003        // value (including `undefined`) is ignored.
9004        Ok(match result {
9005            Value::Object(_) => result,
9006            _ => this,
9007        })
9008    }
9009
9010    /// `new.target` for the call currently being made.
9011    ///
9012    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9013    /// it as `this`), but a *host* constructor that builds its own instance is handed
9014    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9015    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9016    /// it here.
9017    ///
9018    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9019    /// receives for a plain call.
9020    pub fn current_new_target(&self) -> Value {
9021        self.pending_new_target.clone().unwrap_or(Value::Undefined)
9022    }
9023
9024    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9025    ///
9026    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9027    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9028    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9029        let constructor = self.realm.errors.get("AggregateError").cloned();
9030        let Some(constructor) = constructor else {
9031            return self.make_error("AggregateError", message);
9032        };
9033        let list = self.new_array(errors);
9034        match self.construct(
9035            Value::Object(constructor.clone()),
9036            Value::Object(constructor),
9037            vec![Value::Object(list), self.string(message)],
9038        ) {
9039            Ok(value) => value,
9040            // A user could have replaced `AggregateError` with something that throws; the
9041            // engine still owes the caller a rejection, so it falls back rather than
9042            // turning `Promise.any`'s rejection into a throw.
9043            Err(_) => self.make_error("AggregateError", message),
9044        }
9045    }
9046
9047    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9048    ///
9049    /// The error classes themselves arrive with the builtins milestone; what
9050    /// matters here is that the thrown value stringifies the way a script printing
9051    /// the caught value expects.
9052    ///
9053    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9054    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9055    /// rely on when they print a caught value.
9056    pub fn make_error(&self, name: &str, message: &str) -> Value {
9057        let proto = self
9058            .realm
9059            .errors
9060            .get(name)
9061            .map(|constructor| self.prototype_of(constructor))
9062            .unwrap_or_else(|| self.realm.error_proto.clone());
9063        let error = self.new_object(Some(proto));
9064        // `name` and `message` are own properties of the instance, which is what
9065        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9066        // `Error`.
9067        error.define(
9068            "name",
9069            Property::with_attributes(self.string(name), true, false),
9070        );
9071        error.define(
9072            "message",
9073            Property::with_attributes(self.string(message), true, false),
9074        );
9075        // The internal class, which is what tells a printer this is an error rather than a
9076        // plain object with `name` and `message` properties. The constructor path sets it
9077        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9078        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9079        // literally `"Error"` in both places — the *name* is read from `name`, which is why
9080        // a `RangeError` still prints as `RangeError`.
9081        self.internal_set(&error, "_class", self.string("Error"));
9082        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9083        // answered `false` from `Error.isError` while a constructed one answered `true`,
9084        // because only the constructor set the slot. The reference answers `true` for both
9085        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9086        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9087        // tests `typeof stack === "string"` to decide on a trailing newline, so every
9088        // engine-thrown error lost its blank line.
9089        self.internal_set(&error, "_error_data", Value::Bool(true));
9090        // The trace is captured where the error is *made*, which is where the reference
9091        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9092        // way out, so a caught engine error already has its stack even if the handler
9093        // never rethrows it.
9094        self.add_stack(&error);
9095        Value::Object(error)
9096    }
9097
9098    /// Give an error object its `stack` property, from the current frame stack.
9099    ///
9100    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9101    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9102    /// `stack` a script set, is not rewritten.
9103    pub fn add_stack(&self, object: &Gc<JsObject>) {
9104        self.add_stack_skipping(object, 0);
9105    }
9106
9107    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9108    ///
9109    /// An `Error` constructor passes 1: the reference builds those traces with
9110    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9111    /// constructor itself, while a `RangeError` raised inside `toISOString` does
9112    /// report `at toISOString (native)`.
9113    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9114        if object.has_own("stack") {
9115            return;
9116        }
9117        // The trace is *captured* here but not installed as a property: `stack` is an
9118        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9119        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9120        // is kept in a hidden slot and the getter materialises it on first read.
9121        //
9122        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9123        // shows it — this is the same discipline `_error_data` and `_class` follow.
9124        let trace = self.stack_trace_skipping(skip);
9125        let text = self.string(trace);
9126        self.internal_set(object, "_stack_trace", text);
9127    }
9128
9129    /// The function object currently being called, if any.
9130    ///
9131    /// A native function is a bare `fn` pointer, so it cannot capture which class
9132    /// it belongs to; it reads that from the callee instead. This is also what a
9133    /// stack trace would use.
9134    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9135        match &self.frames.last()?.callee {
9136            Value::Object(object) => Some(object.clone()),
9137            _ => None,
9138        }
9139    }
9140
9141    /// The `prototype` property of a constructor, falling back to
9142    /// `Object.prototype` for anything that is not shaped like one.
9143    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9144        constructor
9145            .own_property("prototype")
9146            .and_then(|property| property.value)
9147            .and_then(|value| value.as_object().cloned())
9148            .unwrap_or_else(|| self.realm.object_proto.clone())
9149    }
9150
9151    /// Throw a `TypeError` carrying `message`.
9152    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9153        Signal::Throw(self.make_error("TypeError", message.as_ref()))
9154    }
9155
9156    /// Throw a `RangeError` carrying `message`.
9157    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9158        Signal::Throw(self.make_error("RangeError", message.as_ref()))
9159    }
9160
9161    /// The `ReferenceError` a read of an uninitialised binding raises.
9162    /// The name of the binding `slot` refers to, for an error message.
9163    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9164        match kind {
9165            VarSlot::Loc => self
9166                .frame()
9167                .code
9168                .code
9169                .vars
9170                .get(slot)
9171                .map(|v| v.name.clone()),
9172            VarSlot::Closure => self
9173                .frame()
9174                .code
9175                .code
9176                .closure_vars
9177                .get(slot)
9178                .map(|c| c.name.clone()),
9179        }
9180        .unwrap_or_default()
9181    }
9182
9183    /// Whether `slot` names a `const` binding, which rejects every store after its
9184    /// initialiser.
9185    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9186        match kind {
9187            VarSlot::Loc => self
9188                .frame()
9189                .code
9190                .code
9191                .vars
9192                .get(slot)
9193                .is_some_and(|v| v.is_const),
9194            VarSlot::Closure => self
9195                .frame()
9196                .code
9197                .code
9198                .closure_vars
9199                .get(slot)
9200                .is_some_and(|c| c.is_const),
9201        }
9202    }
9203
9204    /// The `TypeError` a store to a `const` binding raises.
9205    ///
9206    /// `const` is enforced here rather than at compile time because the binding can be
9207    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9208    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9209    /// both halves of what "checked store" means: the dead zone is over, and the
9210    /// binding is writable.
9211    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9212        let name = self.binding_name(slot, kind);
9213        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9214    }
9215
9216    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9217        let name = match kind {
9218            VarSlot::Loc => self
9219                .frame()
9220                .code
9221                .code
9222                .vars
9223                .get(slot)
9224                .map(|v| v.name.clone()),
9225            VarSlot::Closure => self
9226                .frame()
9227                .code
9228                .code
9229                .closure_vars
9230                .get(slot)
9231                .map(|c| c.name.clone()),
9232        }
9233        .unwrap_or_default();
9234        Signal::Throw(self.make_error(
9235            "ReferenceError",
9236            &format!("cannot access '{name}' before initialization"),
9237        ))
9238    }
9239
9240    fn throw_reference(&self, name: &str) -> Signal {
9241        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9242    }
9243
9244    // -- the instruction loop -----------------------------------------------
9245
9246    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9247    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9248    // measured at 16% of a tight arithmetic loop's total time.
9249    #[inline(always)]
9250    fn step(&mut self) -> JsResult<Step> {
9251        // The instruction is already decoded (see [`crate::insn`]), so this is an index
9252        // and a `Copy` read rather than a table lookup plus a width switch. Only the
9253        // borrow lives across the boundary; nothing is cloned.
9254        // **One** borrow of the frame: fetch the record, then advance in the same scope.
9255        // The obvious version borrowed it three times (`last` to read, `last_mut` to
9256        // write, and once more inside the handler), and each is a bounds check plus an
9257        // `Option` unwrap — on the one path every instruction takes.
9258        let Some((insn, next)) = ({
9259            let frame = self
9260                .frames
9261                .last_mut()
9262                .expect("step() is only called with a live frame");
9263            // Past the last instruction is a normal return: the compiler ends a function
9264            // with `return`, and a jump to the end of a block lands here.
9265            let insn = frame.insns().get(frame.pc).copied();
9266            match insn {
9267                None => None,
9268                Some(insn) => {
9269                    // A fused record stands for the next few instructions, so the next
9270                    // `pc` is its width ahead — the instructions it replaces are never
9271                    // dispatched. `at` is the byte offset a stack trace reports; it stays
9272                    // an offset because the line table is keyed by bytes.
9273                    frame.at = insn.offset as usize;
9274                    frame.pc += insn.width();
9275                    Some((insn, frame.pc))
9276                }
9277            }
9278        }) else {
9279            return Ok(Step::Return(Value::Undefined));
9280        };
9281        self.check_memory()?;
9282        self.check_interrupt()?;
9283        if insn.fused == crate::insn::Fused::None {
9284            self.execute_instruction(insn.op, insn.a, insn.b, next)
9285        } else {
9286            self.execute_fused(insn)
9287        }
9288    }
9289
9290    /// Run a fused instruction: several bytecode instructions in one dispatch.
9291    ///
9292    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
9293    /// it cannot throw and cannot allocate — and anything else falls back to the real
9294    /// instructions, in their real order, so an exception leaves the operand stack
9295    /// exactly as it would have been.
9296    #[inline]
9297    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
9298        use crate::insn::Fused;
9299        let slot = insn.a as usize;
9300        match insn.fused {
9301            // `x = k`: `push k; put_loc x`.
9302            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
9303            // `x += k`: `get_loc x; push k; add; put_loc x`.
9304            Fused::AddImmLoc => {
9305                let delta = insn.b as i32;
9306                match self.get_loc(slot) {
9307                    Value::Int(left) => {
9308                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
9309                        // that built two `Value`s, called a function, and matched on them
9310                        // again to reach this same `checked_add`. It is the innermost
9311                        // operation of every accumulator in every program.
9312                        let answer = match left.checked_add(delta) {
9313                            Some(sum) => Value::Int(sum),
9314                            None => Value::Float(left as f64 + delta as f64),
9315                        };
9316                        self.put_loc(slot, answer);
9317                    }
9318                    other => {
9319                        self.push(other);
9320                        self.push(Value::Int(delta));
9321                        self.binary_add()?;
9322                        let value = self.pop();
9323                        self.put_loc(slot, value);
9324                    }
9325                }
9326            }
9327            // `x += "literal"` and `x += y`: the two shapes that can append in place.
9328            Fused::AddAtomLoc => {
9329                let text = self.atom_wtf8(insn.b as usize);
9330                let right = self.string_wtf8(text);
9331                self.add_into_loc(slot, right)?;
9332            }
9333            Fused::AddLocLoc => {
9334                let source = (insn.a & 0xFFFF) as usize;
9335                let target = (insn.a >> 16) as usize;
9336                let right = self.get_loc(source);
9337                self.add_into_loc(target, right)?;
9338            }
9339            Fused::AddArgLoc => {
9340                let source = (insn.a & 0xFFFF) as usize;
9341                let target = (insn.a >> 16) as usize;
9342                let right = self.get_arg(source);
9343                self.add_into_loc(target, right)?;
9344            }
9345            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
9346            Fused::PostIncLoc => match self.get_loc(slot) {
9347                Value::Int(left) => {
9348                    let answer = match left.checked_add(1) {
9349                        Some(sum) => Value::Int(sum),
9350                        None => Value::Float(left as f64 + 1.0),
9351                    };
9352                    self.put_loc(slot, answer);
9353                }
9354                other => {
9355                    self.push(other);
9356                    let raw = self.pop();
9357                    let (old, updated) = self.advance_numeric(raw, true)?;
9358                    self.push(old);
9359                    self.push(updated);
9360                    let value = self.pop();
9361                    self.put_loc(slot, value);
9362                    self.pop();
9363                }
9364            },
9365            // `if (!(x < arg)) goto target`: a loop header.
9366            //
9367            // The comparison is computed rather than replayed on the operand stack. That
9368            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
9369            // that throws: the effects happen in the same order, and a handler truncates
9370            // the stack down to its marker, so the intermediate values are unobservable.
9371            Fused::LtLocArgJump => {
9372                let loc = (insn.a >> 16) as usize;
9373                let arg = (insn.a & 0xFFFF) as usize;
9374                let left = self.get_loc(loc);
9375                let right = self.get_arg(arg);
9376                let taken = match (&left, &right) {
9377                    (Value::Int(left), Value::Int(right)) => !(left < right),
9378                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9379                };
9380                if taken {
9381                    self.frame_mut().pc = insn.b as usize;
9382                }
9383            }
9384            // `i < k` in a loop header, where `k` is an integer literal.
9385            Fused::LtLocImmJump => {
9386                let left = self.get_loc(insn.a as usize);
9387                let right = Value::Int(insn.imm as i32);
9388                let taken = match &left {
9389                    Value::Int(left) => !(*left < insn.imm as i32),
9390                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9391                };
9392                if taken {
9393                    self.frame_mut().pc = insn.b as usize;
9394                }
9395            }
9396            Fused::None => unreachable!("only called for a fused record"),
9397        }
9398        Ok(Step::Continue)
9399    }
9400
9401    /// Run records that cannot call script, cannot throw and cannot change frames.
9402    ///
9403    /// Returns `Some(value)` when the function ran off the end of its instructions (a
9404    /// normal return), and `None` when it stopped in front of an instruction the slow path
9405    /// has to handle — `pc` is written back either way, so `step` resumes at the right
9406    /// place.
9407    ///
9408    /// **The invariant is the whole point.** Every arm here is restricted to work that
9409    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9410    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9411    /// that the memory limit has to see. An opcode whose operands turn out to need any of
9412    /// that **stops the loop** instead of trying, so the slow path gets the instruction
9413    /// untouched and with its operands still on the stack. That is why the fallback is a
9414    /// `break` and not a duplicated slow arm: a second implementation of the same
9415    /// semantics is how a wrong answer gets in with no test noticing.
9416    ///
9417    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9418    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9419    fn run_fast(&mut self) -> JsResult<Option<Value>> {
9420        use crate::insn::Fused;
9421        // The outer loop exists only so a `Call` can come back through here: once a
9422        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9423        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9424        // frame. Re-entering re-reads both from whichever frame is now on top. Every
9425        // other exit from the inner loop returns, so this costs one loop per call.
9426        'outer: loop {
9427            // One reference-count bump per *slow* instruction (a call, an allocation, a
9428            // property access), never one per instruction — that distinction is worth
9429            // two orders of magnitude and was measured as such.
9430            let (code, mut pc) = {
9431                let frame = self.frame();
9432                (frame.code.clone(), frame.pc)
9433            };
9434            let insns = &code.insns;
9435            loop {
9436                let Some(insn) = insns.get(pc).copied() else {
9437                    self.frame_mut().pc = pc;
9438                    return Ok(Some(Value::Undefined));
9439                };
9440                match insn.fused {
9441                    // `x = k`
9442                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9443                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9444                    // object — stops the loop so `binary_add` can decide.
9445                    Fused::AddImmLoc => {
9446                        let slot = insn.a as usize;
9447                        let delta = insn.b as i32;
9448                        let Value::Int(left) = self.get_loc(slot) else {
9449                            return Ok(self.stop(pc));
9450                        };
9451                        let sum = match left.checked_add(delta) {
9452                            Some(sum) => Value::Int(sum),
9453                            None => Value::Float(left as f64 + delta as f64),
9454                        };
9455                        self.put_loc(slot, sum);
9456                    }
9457                    // `x += "literal"` / `x += y`: the operand is a string, so the append
9458                    // either allocates one or grows one. Both are the slow path's business;
9459                    // the fusion's job is only to make the *slot* the sole owner, which is what
9460                    // `execute_fused` needs and what `get_loc` alone destroys.
9461                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9462                        return Ok(self.stop(pc));
9463                    }
9464                    // `x++` on an integer, old value dropped.
9465                    Fused::PostIncLoc => {
9466                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9467                        // value is read in place and overwritten in place, so the reference
9468                        // count it held is released by the same assignment that stores the
9469                        // new one. `get_loc` plus `put_loc` did two borrows, two table
9470                        // lookups and a clone, and this arm is the whole body of a counting
9471                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9472                        let slot = insn.a as usize;
9473                        let frame = self.frames.last_mut().expect("a frame is live");
9474                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9475                        let target = if cell < 0 {
9476                            frame.locals.get_mut(slot)
9477                        } else {
9478                            None
9479                        };
9480                        let Some(target) = target else {
9481                            return Ok(self.stop(pc));
9482                        };
9483                        let Value::Int(left) = *target else {
9484                            return Ok(self.stop(pc));
9485                        };
9486                        *target = match left.checked_add(1) {
9487                            Some(sum) => Value::Int(sum),
9488                            None => Value::Float(left as f64 + 1.0),
9489                        };
9490                    }
9491                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
9492                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9493                    // bound stayed small integers.
9494                    Fused::LtLocArgJump => {
9495                        let loc = (insn.a >> 16) as usize;
9496                        let arg = (insn.a & 0xFFFF) as usize;
9497                        // One borrow for both slots: this arm *is* the whole loop of a
9498                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
9499                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
9500                        // `dispatch:empty-loop`.
9501                        let (left, right) = {
9502                            let frame = self.frame();
9503                            (frame.read_loc(loc), frame.read_arg(arg))
9504                        };
9505                        // Heavily measured: the bound is very often a `Float` even when the
9506                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9507                        // `JSON.parse` or a division is one — so requiring both sides to be
9508                        // `Int` sent every iteration of those loops down the slow path. The
9509                        // comparison below is the same one `relational` makes for two numbers.
9510                        if !is_number(&left) || !is_number(&right) {
9511                            return Ok(self.stop(pc));
9512                        }
9513                        // `if_false` branches on the comparison being false, which is **not**
9514                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9515                        // `>=` is also false and would keep it running forever. Clippy wants the
9516                        // negation folded; that would be a wrong answer.
9517                        let ordered = left.to_number() < right.to_number();
9518                        let take_branch = !ordered;
9519                        if take_branch {
9520                            pc = insn.b as usize;
9521                            continue;
9522                        }
9523                    }
9524                    // The same header with a literal bound: `if (!(x < k)) goto target`.
9525                    // The bound is an immediate, so only the counter needs a type test.
9526                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
9527                    Fused::LtLocImmJump => {
9528                        let left = self.get_loc(insn.a as usize);
9529                        if !is_number(&left) {
9530                            return Ok(self.stop(pc));
9531                        }
9532                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9533                        if take_branch {
9534                            pc = insn.b as usize;
9535                            continue;
9536                        }
9537                    }
9538                    Fused::None => match insn.op {
9539                        // -- branches ---------------------------------------------------
9540                        // A jump is an assignment now, because the target is an instruction
9541                        // index. No arithmetic, no resolution table.
9542                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9543                            let target = insn.a as usize;
9544                            // A **back-edge** is a loop, and it is the only place an
9545                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
9546                            // to a jump to itself and never leaves this loop, so the
9547                            // per-instruction checks in `step` never run. That is exactly the
9548                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
9549                            // nothing to a `for(;;){}` until it did, which is what
9550                            // `tests/c/embed.c` is for.
9551                            //
9552                            // Polling here rather than on every instruction in this loop is
9553                            // also the reference's choice (`OP_goto` calls
9554                            // `js_poll_interrupts`), and it costs one compare per branch
9555                            // instead of one decrement per instruction.
9556                            if target <= pc {
9557                                self.frame_mut().pc = target;
9558                                self.check_memory()?;
9559                                self.check_interrupt()?;
9560                            }
9561                            pc = target;
9562                            continue;
9563                        }
9564                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9565                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9566                            let taken = self.pop().to_boolean();
9567                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9568                            if taken == want {
9569                                pc = insn.a as usize;
9570                                continue;
9571                            }
9572                        }
9573                        // -- slot access -------------------------------------------------
9574                        // A load's slot is already an operand (see `insn::implicit_operand`);
9575                        // a captured one goes through its cell, which runs no script.
9576                        Opcode::GetLoc
9577                        | Opcode::GetLoc8
9578                        | Opcode::GetLoc0
9579                        | Opcode::GetLoc1
9580                        | Opcode::GetLoc2
9581                        | Opcode::GetLoc3 => {
9582                            let value = self.get_loc(insn.a as usize);
9583                            self.push(value);
9584                        }
9585                        Opcode::PutLoc
9586                        | Opcode::PutLoc8
9587                        | Opcode::PutLoc0
9588                        | Opcode::PutLoc1
9589                        | Opcode::PutLoc2
9590                        | Opcode::PutLoc3 => {
9591                            let value = self.pop();
9592                            self.put_loc(insn.a as usize, value);
9593                        }
9594                        Opcode::GetArg
9595                        | Opcode::GetArg0
9596                        | Opcode::GetArg1
9597                        | Opcode::GetArg2
9598                        | Opcode::GetArg3 => {
9599                            let value = self.get_arg(insn.a as usize);
9600                            self.push(value);
9601                        }
9602                        Opcode::PutArg
9603                        | Opcode::PutArg0
9604                        | Opcode::PutArg1
9605                        | Opcode::PutArg2
9606                        | Opcode::PutArg3 => {
9607                            let value = self.pop();
9608                            self.put_arg(insn.a as usize, value);
9609                        }
9610                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
9611                        // for why a non-hole own element is exactly the slow path's answer.
9612                        // The two operands are *peeked*, so a miss leaves the stack as the
9613                        // slow path expects to find it.
9614                        Opcode::GetArrayEl => {
9615                            // One lookup, not two. The guard used `if …is_some()` and the arm
9616                            // then called it again to get the value — two `peek`s, two
9617                            // `array_get`s and two `Value` clones for one element.
9618                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
9619                            // double call was the first version of the `get_field` fast path.
9620                            let Some(value) = self.fast_array_get() else {
9621                                return Ok(self.stop(pc));
9622                            };
9623                            // `a[i]` consumes both operands and leaves the element in their
9624                            // place: one `truncate` and one write, no `pop`/`push` pair.
9625                            let frame = self.frame_mut();
9626                            frame.stack.truncate(frame.stack.len() - 2);
9627                            frame.stack.push(value);
9628                        }
9629                        // `a[i] = v` on a dense array with an integer index: see
9630                        // `fast_array_set` for why the whole store is one step.
9631                        Opcode::PutArrayEl if self.fast_array_set() => {}
9632                        // `o.x` resolved from the inline cache without leaving the loop.
9633                        //
9634                        // The cache is keyed by `(receiver identity, atom, site)` and a
9635                        // monomorphic read re-validates the same chain every iteration, so
9636                        // each one used to cost a `stop(pc)` — a write of `pc` into the
9637                        // frame, a return out of this loop, a re-dispatch through `step` and
9638                        // a re-entry. `property:monomorphic` spent 18% in
9639                        // `read_field_cached` and 21% in `push`, both across that boundary.
9640                        //
9641                        // The site is `pc + width`, which is exactly the `next` the slow arm
9642                        // passes — the two must agree or every fast lookup misses and
9643                        // re-records the same entry forever.
9644                        //
9645                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9646                        // slow arm finds the receiver where it expects it.
9647                        // `name` resolved from the global-variable cache inside the loop.
9648                        //
9649                        // Same shape as `get_field` above and for the same reason: `get_var`
9650                        // was not in the fast loop, so reading a global — which `fib` does
9651                        // once per recursive call, for its own name — cost a `stop(pc)`, a
9652                        // return out of the loop, a `step` re-dispatch and a re-entry, before
9653                        // `get_global` even started its `scopes_are_plain` checks.
9654                        //
9655                        // Everything here is exactly `get_global`'s first branch: not lexical,
9656                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
9657                        // and lets the slow arm decide.
9658                        Opcode::GetVar => {
9659                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9660                                return Ok(self.stop(pc));
9661                            };
9662                            self.push(value);
9663                        }
9664                        Opcode::GetField | Opcode::GetField2 => {
9665                            let Some(value) =
9666                                self.fast_field_get(insn.a as usize, pc + insn.width())
9667                            else {
9668                                return Ok(self.stop(pc));
9669                            };
9670                            if insn.op == Opcode::GetField2 {
9671                                // `get_field2` keeps the receiver for the `call_method` that
9672                                // follows.
9673                                self.push(value);
9674                            } else {
9675                                // `get_field` replaces the receiver, so this is one store over
9676                                // the top slot rather than a `pop` and a `push`: the length
9677                                // never changes, so neither `Vec` arm has a capacity check or a
9678                                // drop to run beyond the one the overwrite itself does.
9679                                let frame = self.frame_mut();
9680                                match frame.stack.last_mut() {
9681                                    Some(slot) => *slot = value,
9682                                    None => return Ok(self.stop(pc)),
9683                                }
9684                            }
9685                        }
9686                        // -- constants ---------------------------------------------------
9687                        Opcode::PushMinus1
9688                        | Opcode::Push0
9689                        | Opcode::Push1
9690                        | Opcode::Push2
9691                        | Opcode::Push3
9692                        | Opcode::Push4
9693                        | Opcode::Push5
9694                        | Opcode::Push6
9695                        | Opcode::Push7
9696                        | Opcode::PushI8
9697                        | Opcode::PushI16
9698                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
9699                        // -- stack shuffling ---------------------------------------------
9700                        Opcode::Drop => {
9701                            self.pop();
9702                        }
9703                        // -- arithmetic on two integers ----------------------------------
9704                        //
9705                        // The operands are *looked at* before they are popped, so a non-integer
9706                        // pair leaves the stack exactly as the slow path expects to find it.
9707                        Opcode::Add if self.numeric_pair() => {
9708                            let right = self.pop();
9709                            let left = self.pop();
9710                            // Exactly [`add_numbers`], which is what the slow arm reaches.
9711                            let answer = match (&left, &right) {
9712                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9713                                    Some(sum) => Value::Int(sum),
9714                                    None => Value::Float(*a as f64 + *b as f64),
9715                                },
9716                                _ => Value::Float(left.to_number() + right.to_number()),
9717                            };
9718                            self.push(answer);
9719                        }
9720                        Opcode::Sub
9721                        | Opcode::And
9722                        | Opcode::Or
9723                        | Opcode::Xor
9724                        | Opcode::Shl
9725                        | Opcode::Sar
9726                        | Opcode::Shr
9727                            if self.numeric_pair() =>
9728                        {
9729                            let right = self.pop();
9730                            let left = self.pop();
9731                            let answer =
9732                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
9733                            self.push(answer);
9734                        }
9735                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
9736                            if self.numeric_pair() =>
9737                        {
9738                            let right = self.pop();
9739                            let left = self.pop();
9740                            let answer = self
9741                                .relational(insn.op, left, right)
9742                                .expect("numbers cannot throw");
9743                            self.push(answer);
9744                        }
9745                        // -- calls -------------------------------------------------------
9746                        //
9747                        // A plain call: `callee(arg0, …, argN) -> result`.
9748                        //
9749                        // This arm exists because of one measurement. `call:recursion` had
9750                        // **20.4% of its profile in `execute_instruction`** — the *slow*
9751                        // executor — and `fib`'s recursive call is the only thing in that
9752                        // function which is not a fast arm. Every call therefore left this
9753                        // loop via `stop()`, went through `step()`'s dispatch and
9754                        // `execute_instruction`'s match over every opcode, and came back here
9755                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
9756                        //
9757                        // Two things make it safe to do here rather than only in the slow path:
9758                        //
9759                        // * the caller's `pc` is stored *before* the call, which is what
9760                        //   `step` does too — so when the callee returns, the caller resumes
9761                        //   after the call and not at it;
9762                        // * `check_memory` runs, because `step` calls it once per instruction
9763                        //   and a call allocates a frame, its locals and its cells. Skipping
9764                        //   the checkpoint here would let a `--memory-limit` script overshoot
9765                        //   by one call per instruction.
9766                        Opcode::Call
9767                        | Opcode::Call0
9768                        | Opcode::Call1
9769                        | Opcode::Call2
9770                        | Opcode::Call3 => {
9771                            let argc = self.argc_operand(insn.op, insn.a);
9772                            let next = pc + insn.width();
9773                            {
9774                                let frame = self
9775                                    .frames
9776                                    .last_mut()
9777                                    .expect("run_fast() is only called with a live frame");
9778                                // `at` is what a stack trace reports for this frame, so a throw
9779                                // inside the callee has to see the call site and not whatever
9780                                // the last `stop()` left there.
9781                                frame.at = insn.offset as usize;
9782                                frame.pc = next;
9783                            }
9784                            self.check_memory()?;
9785                            self.check_interrupt()?;
9786                            let args = self.pop_n(argc);
9787                            let callee = self.pop();
9788                            // A plain call has no receiver; the callee decides what to do with
9789                            // `undefined` (a sloppy function substitutes the global object).
9790                            if let Some(result) =
9791                                self.call_or_push(callee, Value::Undefined, args)?
9792                            {
9793                                // Native, host, generator, async, bound — no frame was pushed,
9794                                // so this loop is still describing the right function. `pc`
9795                                // is advanced by the loop tail like every other arm; only the
9796                                // frame's copy had to be written here, and it already was.
9797                                self.push(result);
9798                            } else {
9799                                // A bytecode callee: its frame is on top now, and `insns` and
9800                                // `pc` both belong to the caller. Start over on the new frame.
9801                                continue 'outer;
9802                            }
9803                        }
9804                        // -- return ------------------------------------------------------
9805                        Opcode::Return => {
9806                            let value = self.pop();
9807                            self.frame_mut().pc = pc + insn.width();
9808                            return Ok(Some(value));
9809                        }
9810                        Opcode::ReturnUndef => {
9811                            self.frame_mut().pc = pc + insn.width();
9812                            return Ok(Some(Value::Undefined));
9813                        }
9814                        // Everything else needs the slow path.
9815                        _ => return Ok(self.stop(pc)),
9816                    },
9817                }
9818                pc += insn.width();
9819            }
9820        }
9821    }
9822
9823    /// Whether the top two operand-stack values are both numbers.
9824    ///
9825    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
9826    /// cannot run script, so the arm may not throw and may not change frames.
9827    fn numeric_pair(&self) -> bool {
9828        is_number(&self.peek(0)) && is_number(&self.peek(1))
9829    }
9830
9831    /// `a[i]` for a dense array and an integer index, without the string round trip.
9832    ///
9833    /// The slow path answers this by turning `i` into a string (`propkey` →
9834    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
9835    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
9836    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
9837    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
9838    /// without even the cheap `Int` formatting.
9839    ///
9840    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
9841    /// unambiguously the one the slow path would give:
9842    ///
9843    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
9844    ///   `2^32-1` is the length, not an index),
9845    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
9846    ///   typed array or an ordinary object, all of which have their own rules),
9847    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
9848    ///   starts walking the prototype chain, and `a[i]` on a hole must find
9849    ///   `Array.prototype[i]` if it exists rather than `undefined`.
9850    ///
9851    /// The last condition is the one that makes this safe rather than merely fast: an own
9852    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
9853    /// `get_var` answered from the global-variable cache, or `None`.
9854    ///
9855    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
9856    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
9857    /// records nothing — the slow arm is about to walk the chain and record it.
9858    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
9859        let frame = self.frame();
9860        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
9861        // "Lexical" is presence in the realm's table, not the closure var's flag: a
9862        // `GlobalRef` forwarded through a nested function has its flags cleared.
9863        if self.realm.globals.contains_key(name) {
9864            return None;
9865        }
9866        if !self.scopes_are_plain() {
9867            return None;
9868        }
9869        let object = &self.realm.global;
9870        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
9871        let cached = self.global_cache[site].as_ref()?;
9872        if !object.upgrades_to(&cached.object) {
9873            return None;
9874        }
9875        object.data_property_at(cached.index, name)
9876    }
9877
9878    /// `o.x` answered entirely from the inline cache, or `None`.
9879    ///
9880    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
9881    /// about to do exactly that and recording it twice would rebuild the chain for every
9882    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
9883    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
9884    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
9885        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
9886        // an object receiver is a reference-count bump that the answer never needs.
9887        let frame = self.frame();
9888        let object = frame.stack.last()?;
9889        let Value::Object(target) = object else {
9890            return None;
9891        };
9892        // A proxy traps the lookup, so no cache entry ever describes it.
9893        if target.proxy_state().is_some() {
9894            return None;
9895        }
9896        let key = frame.code.atom_keys.get(atom)?;
9897        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
9898        if cached.key != *key {
9899            return None;
9900        }
9901        Self::cached_hit(target, cached)
9902    }
9903
9904    fn fast_array_get(&self) -> Option<Value> {
9905        let Value::Int(index) = self.peek(0) else {
9906            return None;
9907        };
9908        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
9909        // set for an `i32`.
9910        if index < 0 {
9911            return None;
9912        }
9913        let Value::Object(object) = self.peek(1) else {
9914            return None;
9915        };
9916        match object.array_get(index as usize) {
9917            Some(value) if !matches!(value, Value::Hole) => Some(value),
9918            _ => None,
9919        }
9920    }
9921
9922    /// `a[i] = v` on a dense array with an integer index, as one store.
9923    ///
9924    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
9925    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
9926    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
9927    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
9928    /// reference at the time it was measured (14.7x).
9929    ///
9930    /// Every condition here is one the slow path would also have to satisfy before
9931    /// storing into the element vector:
9932    ///
9933    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
9934    ///   accepts as an index;
9935    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
9936    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
9937    ///   one inside a recorded descriptor, reports `false` and the caller stops.
9938    ///
9939    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
9940    /// writes the own element too once `array_set` says it did.
9941    fn fast_array_set(&mut self) -> bool {
9942        // Every test runs *before* anything is popped: a refusal has to leave the stack
9943        // exactly as the slow path expects to find it. Popping first and reporting the
9944        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
9945        // then ran the slow path with nothing to write.
9946        let Value::Int(index) = self.peek(1) else {
9947            return false;
9948        };
9949        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
9950        if index < 0 {
9951            return false;
9952        }
9953        // Only a real array: a typed array's elements live in its buffer, a string-like
9954        // object has no element vector, and `array_set` on either does nothing.
9955        let Value::Object(object) = self.peek(2) else {
9956            return false;
9957        };
9958        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
9959            return false;
9960        }
9961        // A non-extensible array reports `false` here, but the *slow* path has to decide
9962        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
9963        // that with the key and the stack still intact.
9964        if !object.is_extensible() {
9965            return false;
9966        }
9967        // Inside the logical length, so the store cannot change `length`. Combined with
9968        // extensibility above, the only growth left for `array_set` is filling a hole in
9969        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
9970        // shape this fast path exists for. A store past the length would grow the array,
9971        // and whether that is allowed is the slow path's question.
9972        if index as usize >= object.array_length().unwrap_or(0) {
9973            return false;
9974        }
9975        // Only an *own element* can take the inline store. A hole is not an own property,
9976        // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
9977        // trap or a setter decides, and where `new Array(1)` with a proxy above it must
9978        // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
9979        // the one case this path used to swallow.
9980        //
9981        // The cost is small: `array:indexed` only reads after a 64-element fill, and
9982        // `array:push` appends past the length, which this path already refused.
9983        if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
9984        {
9985            return false;
9986        }
9987        // The bound `array_set` refuses past. Checking it here keeps that arm from having
9988        // to report a failure after the operands are gone.
9989        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
9990            return false;
9991        }
9992        let value = self.pop();
9993        self.pop();
9994        self.pop();
9995        object.array_store(self.heap, index as usize, value)
9996    }
9997
9998    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
9999    fn stop(&mut self, pc: usize) -> Option<Value> {
10000        self.frame_mut().pc = pc;
10001        None
10002    }
10003
10004    fn push(&mut self, value: Value) {
10005        self.frame_mut().stack.push(value);
10006    }
10007
10008    fn pop(&mut self) -> Value {
10009        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10010    }
10011
10012    fn pop_n(&mut self, count: usize) -> Vec<Value> {
10013        let frame = self.frame_mut();
10014        let start = frame.stack.len().saturating_sub(count);
10015        frame.stack.split_off(start)
10016    }
10017
10018    fn peek(&self, back: usize) -> Value {
10019        let frame = self.frame();
10020        frame
10021            .stack
10022            .get(frame.stack.len().wrapping_sub(1 + back))
10023            .cloned()
10024            .unwrap_or(Value::Undefined)
10025    }
10026
10027    #[allow(clippy::too_many_lines)]
10028    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10029        use Opcode::*;
10030        match op {
10031            // -- constants and stack shuffling -----------------------------
10032            Nop => {}
10033            PushMinus1 => self.push(Value::Int(-1)),
10034            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10035                let value = match op {
10036                    Push0 => 0,
10037                    Push1 => 1,
10038                    Push2 => 2,
10039                    Push3 => 3,
10040                    Push4 => 4,
10041                    Push5 => 5,
10042                    Push6 => 6,
10043                    _ => 7,
10044                };
10045                self.push(Value::Int(value));
10046            }
10047            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10048            PushBigintI32 => {
10049                // The immediate form of a `BigInt` literal; the reference has the same
10050                // split between this and a constant-pool entry.
10051                let value = crate::bigint::BigInt::from_i64(a as i64);
10052                self.push(self.bigint(value));
10053            }
10054            PushTrue => self.push(Value::Bool(true)),
10055            PushFalse => self.push(Value::Bool(false)),
10056            PushEmptyString => self.push(self.string("")),
10057            Undefined => self.push(Value::Undefined),
10058            Null => self.push(Value::Null),
10059            Object => {
10060                let proto = self.realm.object_proto.clone();
10061                self.push(Value::Object(self.new_object(Some(proto))));
10062            }
10063            PushThis => {
10064                let this = self.frame().this.clone();
10065                self.push(this);
10066            }
10067            PushConst | PushConst8 => {
10068                let value = self.constant(a as usize)?;
10069                self.push(value);
10070            }
10071            PushAtomValue => {
10072                let text = self.atom_wtf8(a as usize);
10073                self.push(self.string_wtf8(text));
10074            }
10075            Dup => {
10076                let value = self.peek(0);
10077                self.push(value);
10078            }
10079            Dup2 => {
10080                // `a b -> a b a b`
10081                let b = self.peek(0);
10082                let a = self.peek(1);
10083                self.push(a);
10084                self.push(b);
10085            }
10086            Dup3 => {
10087                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10088                // prototype and key while reading the current value through them.
10089                let c = self.peek(0);
10090                let b = self.peek(1);
10091                let a = self.peek(2);
10092                self.push(a);
10093                self.push(b);
10094                self.push(c);
10095            }
10096            Swap => {
10097                // `a b -> b a`
10098                let bottom = self.pop();
10099                let top = self.pop();
10100                self.push(bottom);
10101                self.push(top);
10102            }
10103            Perm3 => {
10104                // `a b c -> b a c`, the reference's reordering for a spread method
10105                // call: `obj func array` becomes the `func this array` that `apply`
10106                // takes.
10107                let c = self.pop();
10108                let b = self.pop();
10109                let a = self.pop();
10110                self.push(b);
10111                self.push(a);
10112                self.push(c);
10113            }
10114            Dup1 => {
10115                let value = self.peek(1);
10116                self.push(value);
10117            }
10118            Drop => {
10119                self.pop();
10120            }
10121            Nip => {
10122                // `a b -> b`
10123                let top = self.pop();
10124                self.pop();
10125                self.push(top);
10126            }
10127            Perm4 => {
10128                // `obj prop a b -> a obj prop b`, the reference's reordering for a
10129                // postfix update of a computed element: it puts the *old* value
10130                // underneath the receiver and key so `put_array_el` can consume them
10131                // and leave the old value as the expression's result.
10132                let d = self.pop();
10133                let c = self.pop();
10134                let b = self.pop();
10135                let a = self.pop();
10136                self.push(c);
10137                self.push(a);
10138                self.push(b);
10139                self.push(d);
10140            }
10141            Insert2 => {
10142                // `obj a -> a obj a`
10143                let value = self.pop();
10144                let object = self.pop();
10145                self.push(value.clone());
10146                self.push(object);
10147                self.push(value);
10148            }
10149            Insert3 => {
10150                // `obj prop a -> a obj prop a`
10151                let value = self.pop();
10152                let key = self.pop();
10153                let object = self.pop();
10154                self.push(value.clone());
10155                self.push(object);
10156                self.push(key);
10157                self.push(value);
10158            }
10159            Insert4 => {
10160                // `this obj prop a -> a this obj prop a`
10161                //
10162                // `put_super_value` consumes all four and yields nothing, so the copy
10163                // underneath is what leaves the assignment an expression value.
10164                let value = self.pop();
10165                let key = self.pop();
10166                let object = self.pop();
10167                let receiver = self.pop();
10168                self.push(value.clone());
10169                self.push(receiver);
10170                self.push(object);
10171                self.push(key);
10172                self.push(value);
10173            }
10174            Swap2 => {
10175                // `a b c d -> c d a b`
10176                let d = self.pop();
10177                let c = self.pop();
10178                let b = self.pop();
10179                let a = self.pop();
10180                self.push(c);
10181                self.push(d);
10182                self.push(a);
10183                self.push(b);
10184            }
10185            Rot3l => {
10186                // `x a b -> a b x`
10187                let b = self.pop();
10188                let a = self.pop();
10189                let x = self.pop();
10190                self.push(a);
10191                self.push(b);
10192                self.push(x);
10193            }
10194            Rot3r => {
10195                // `a b c -> c a b`
10196                let c = self.pop();
10197                let b = self.pop();
10198                let a_value = self.pop();
10199                self.push(c);
10200                self.push(a_value);
10201                self.push(b);
10202            }
10203
10204            Rest => {
10205                // `...rest` in a parameter list: the arguments from index `a` on, as a
10206                // real array. It takes nothing off the stack — the arguments are in the
10207                // frame, not on it.
10208                let frame = self.frame();
10209                let from = a as usize;
10210                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10211                let array = self.new_array(collected);
10212                self.push(Value::Object(array));
10213            }
10214
10215            // -- slots ------------------------------------------------------
10216            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10217                let slot = self.slot_operand(op, a);
10218                let value = self.get_loc(slot);
10219                self.push(value);
10220            }
10221            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10222                let slot = self.slot_operand(op, a);
10223                let value = self.pop();
10224                self.put_loc(slot, value);
10225            }
10226            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10227                let slot = self.slot_operand(op, a);
10228                let value = self.pop();
10229                self.put_loc(slot, value.clone());
10230                self.push(value);
10231            }
10232            // The `_check` forms are the temporal dead zone: they throw when the
10233            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10234            // *reads*, so only the two writes may pop — mishandling that quietly
10235            // consumes the value the caller pushed just before.
10236            GetLocCheck => {
10237                let slot = self.slot_operand(op, a);
10238                let value = self.get_loc(slot);
10239                if matches!(value, Value::Uninitialized) {
10240                    return Err(self.dead_zone(slot, VarSlot::Loc));
10241                }
10242                self.push(value);
10243            }
10244            PutLocCheck | SetLocCheck => {
10245                let slot = self.slot_operand(op, a);
10246                let value = self.pop();
10247                if matches!(value, Value::Uninitialized) {
10248                    return Err(self.dead_zone(slot, VarSlot::Loc));
10249                }
10250                // The initialiser goes through `put_loc`, not this, so any store that
10251                // reaches here is a later assignment — which a `const` refuses.
10252                if self.is_read_only(slot, VarSlot::Loc) {
10253                    return Err(self.read_only(slot, VarSlot::Loc));
10254                }
10255                if op == SetLocCheck {
10256                    self.put_loc(slot, value.clone());
10257                    self.push(value);
10258                } else {
10259                    self.put_loc(slot, value);
10260                }
10261            }
10262            PutLocCheckInit => {
10263                // The one store that *initialises* a lexical slot: `this` in a derived
10264                // constructor, which only exists after `super()` has run. A second
10265                // initialisation is the error the reference reports as
10266                // "'this' can be initialized only once".
10267                let slot = self.slot_operand(op, a);
10268                let value = self.pop();
10269                if !matches!(self.get_loc(slot), Value::Uninitialized) {
10270                    return Err(Signal::Throw(self.make_error(
10271                        "ReferenceError",
10272                        "'this' can be initialized only once",
10273                    )));
10274                }
10275                self.put_loc(slot, value);
10276            }
10277            CheckCtor => {
10278                // A class constructor may only run under `new`, which is what makes
10279                // `class A {}; A()` a TypeError.
10280                if matches!(self.frame().new_target, Value::Undefined) {
10281                    return Err(Signal::Throw(self.make_error(
10282                        "TypeError",
10283                        "class constructors must be invoked with 'new'",
10284                    )));
10285                }
10286            }
10287            InitCtor => {
10288                // The body a derived class gets when it declares no constructor:
10289                // forward every argument to the parent constructor, keeping `new.target`.
10290                if matches!(self.frame().new_target, Value::Undefined) {
10291                    return Err(Signal::Throw(self.make_error(
10292                        "TypeError",
10293                        "class constructors must be invoked with 'new'",
10294                    )));
10295                }
10296                let Some(callee) = self.current_callee() else {
10297                    return Err(Signal::Throw(
10298                        self.make_error("TypeError", "no constructor to inherit from"),
10299                    ));
10300                };
10301                let parent = callee.proto().map_or(Value::Null, Value::Object);
10302                let new_target = self.frame().new_target.clone();
10303                let args = self.frame().passed().to_vec();
10304                let result = self.construct(parent, new_target, args)?;
10305                self.push(result);
10306            }
10307            SetLocUninitialized => {
10308                let slot = self.slot_operand(op, a);
10309                self.put_loc(slot, Value::Uninitialized);
10310            }
10311            CloseLoc => {
10312                // "Close" a binding: give it a *fresh* cell holding the current
10313                // value. Closures created before this point keep the old cell and the
10314                // ones created after see the new one, which is what makes every
10315                // iteration of `for (let i ...)` capture its own `i`, and what freezes
10316                // a block-scoped binding when the block ends.
10317                //
10318                // Clearing the slot instead (which this used to do) broke both: a
10319                // closure over a captured block variable read `undefined`, and a loop
10320                // terminated after one iteration.
10321                let slot = self.slot_operand(op, a);
10322                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
10323                if index >= 0 {
10324                    let current = self.frame().cells[index as usize].get();
10325                    let fresh = self.new_cell(current);
10326                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
10327                        *cell = fresh;
10328                    }
10329                }
10330            }
10331            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
10332                let slot = self.slot_operand(op, a);
10333                let value = self.get_arg(slot);
10334                self.push(value);
10335            }
10336            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
10337                let slot = self.slot_operand(op, a);
10338                let value = self.pop();
10339                self.put_arg(slot, value);
10340            }
10341            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
10342                let slot = self.slot_operand(op, a);
10343                let value = self.pop();
10344                self.put_arg(slot, value.clone());
10345                self.push(value);
10346            }
10347
10348            // -- closure variables ------------------------------------------
10349            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
10350                let slot = self.slot_operand(op, a);
10351                // A name a direct `eval` created shadows the binding the compiler chose.
10352                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
10353                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
10354                // and only a runtime lookup can know that.
10355                if let Some(cell) = self.eval_created_local(slot) {
10356                    self.push(cell.get());
10357                    return self.step();
10358                }
10359                let value = self.cell_value(slot)?;
10360                self.push(value);
10361            }
10362            GetVarRefCheck => {
10363                let slot = self.slot_operand(op, a);
10364                let value = self.cell_value(slot)?;
10365                if matches!(value, Value::Uninitialized) {
10366                    return Err(self.dead_zone(slot, VarSlot::Closure));
10367                }
10368                self.push(value);
10369            }
10370            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
10371                let slot = self.slot_operand(op, a);
10372                let value = self.pop();
10373                if let Some(cell) = self.eval_created_local(slot) {
10374                    cell.set(value);
10375                    return self.step();
10376                }
10377                // Same rule as `PutLocCheck`: a checked store to a captured binding
10378                // refuses a `const` once its initialiser has run.
10379                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
10380                    return Err(self.read_only(slot, VarSlot::Closure));
10381                }
10382                self.set_cell(slot, value)?;
10383            }
10384            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
10385                let slot = self.slot_operand(op, a);
10386                let value = self.pop();
10387                if let Some(cell) = self.eval_created_local(slot) {
10388                    cell.set(value.clone());
10389                    self.push(value);
10390                    return self.step();
10391                }
10392                self.set_cell(slot, value.clone())?;
10393                self.push(value);
10394            }
10395
10396            // -- globals ----------------------------------------------------
10397            GetVar => {
10398                let value = self.get_global(a as usize)?;
10399                self.push(value);
10400            }
10401            GetVarUndef => {
10402                let value = self
10403                    .get_global(a as usize)
10404                    .or_else(|_| Ok(Value::Undefined))?;
10405                self.push(value);
10406            }
10407            DeleteVar => {
10408                // `delete name` for a name that is not a declared binding. A lexical
10409                // global lives in the reference table and cannot be deleted; anything
10410                // reachable only as a property of the global object is *implicit* —
10411                // `x = 1` with no declaration — and goes away if it is configurable,
10412                // which is what `delete` on an implicit global answers.
10413                let name = self.atom_text(a as usize);
10414                let global = self.realm.global.clone();
10415                let deleted = if self.realm.globals.contains_key(&name) {
10416                    false
10417                } else if global.own_property(&name).is_some() {
10418                    self.delete_property(&global, &name)?
10419                } else {
10420                    true
10421                };
10422                self.push(Value::Bool(deleted));
10423            }
10424            PutVar => {
10425                let value = self.pop();
10426                self.put_global(a as usize, value)?;
10427            }
10428            PutVarInit => {
10429                let slot = a as usize;
10430                let value = self.pop();
10431                self.init_global(slot, value)?;
10432            }
10433
10434            // -- arithmetic -------------------------------------------------
10435            Add => self.binary_add()?,
10436            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10437                let raw_right = self.pop();
10438                let raw_left = self.pop();
10439                // BigInt arithmetic is a separate path, and not only for the type of the
10440                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10441                // rather than a silent conversion.
10442                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10443                    let left = self.primitive_of(raw_left)?;
10444                    let right = self.primitive_of(raw_right)?;
10445                    let value = self.bigint_arithmetic(op, left, right)?;
10446                    self.push(value);
10447                } else {
10448                    let right = self.numeric(raw_right)?;
10449                    let left = self.numeric(raw_left)?;
10450                    self.push(arithmetic(op, left, right)?);
10451                }
10452            }
10453            Neg => {
10454                let raw = self.pop();
10455                match raw {
10456                    // A bigint negates exactly, however wide it is.
10457                    Value::BigInt(big) => {
10458                        let negated = big.negate();
10459                        self.push(self.bigint(negated));
10460                    }
10461                    other => {
10462                        let value = self.numeric(other)?;
10463                        self.push(negate(value));
10464                    }
10465                }
10466            }
10467            Plus => {
10468                let value = self.pop();
10469                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10470                // unary plus is defined to produce a *number*, which a bigint cannot
10471                // become without loss. It used to fall through to `NaN`.
10472                if matches!(value, Value::BigInt(_)) {
10473                    return Err(self.type_error("cannot convert bigint to number"));
10474                }
10475                let numeric = self.numeric_of(value)?;
10476                self.push(numeric);
10477            }
10478            Inc => {
10479                let raw = self.pop();
10480                let (_, updated) = self.advance_numeric(raw, true)?;
10481                self.push(updated);
10482            }
10483            Dec => {
10484                let raw = self.pop();
10485                let (_, updated) = self.advance_numeric(raw, false)?;
10486                self.push(updated);
10487            }
10488            PostInc | PostDec => {
10489                // `x -> x x+1`: the *new* value ends up on top, so the store the
10490                // compiler emits right after (`put_var`) writes the incremented
10491                // one, while the old value stays underneath for the expression's
10492                // own result. Getting this backwards makes `i++` a no-op, which
10493                // turns `while (i < 3)` into an infinite loop.
10494                let raw = self.pop();
10495                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10496                self.push(old);
10497                self.push(updated);
10498            }
10499            Not => {
10500                let raw = self.pop();
10501                match raw {
10502                    // `~x` on a bigint is `-x - 1`, exact at any width.
10503                    Value::BigInt(big) => {
10504                        let inverted = big.bitnot();
10505                        self.push(self.bigint(inverted));
10506                    }
10507                    other => {
10508                        let value = self.numeric(other)?;
10509                        self.push(Value::Int(!value.to_int32()));
10510                    }
10511                }
10512            }
10513            Lnot => {
10514                let value = self.pop();
10515                self.push(Value::Bool(!value.to_boolean()));
10516            }
10517
10518            // -- comparison -------------------------------------------------
10519            Lt | Lte | Gt | Gte => {
10520                let right = self.pop();
10521                let left = self.pop();
10522                let answer = self.relational(op, left, right)?;
10523                self.push(answer);
10524            }
10525            Eq | Neq => {
10526                let right = self.pop();
10527                let left = self.pop();
10528                let equal = self.abstract_equals(left, right)?;
10529                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10530            }
10531            StrictEq => {
10532                let right = self.pop();
10533                let left = self.pop();
10534                self.push(Value::Bool(left.strict_equals(&right)));
10535            }
10536            StrictNeq => {
10537                let right = self.pop();
10538                let left = self.pop();
10539                self.push(Value::Bool(!left.strict_equals(&right)));
10540            }
10541            IsUndefined => {
10542                // `=== undefined`, which is what a destructuring default tests. It is
10543                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10544                let value = self.pop();
10545                self.push(Value::Bool(matches!(value, Value::Undefined)));
10546            }
10547            IsUndefinedOrNull => {
10548                let value = self.pop();
10549                self.push(Value::Bool(value.is_nullish()));
10550            }
10551            Typeof => {
10552                let value = self.pop();
10553                self.push(self.string(value.type_of()));
10554            }
10555            ToObject => {
10556                // A destructuring *object* pattern starts here, which is why
10557                // `var {} = null` throws. Only `undefined` and `null` are refused; a
10558                // primitive is boxed.
10559                let value = self.pop();
10560                let object = self.object_from(&value)?;
10561                self.push(Value::Object(object));
10562            }
10563            Instanceof => {
10564                let constructor = self.pop();
10565                let object = self.pop();
10566                let answer = self.instance_of(&object, &constructor)?;
10567                self.push(Value::Bool(answer));
10568            }
10569            In => {
10570                let object = self.pop();
10571                let key = self.pop();
10572                let answer = self.has_property(&key, &object)?;
10573                self.push(Value::Bool(answer));
10574            }
10575
10576            // -- control flow -----------------------------------------------
10577            Goto | Goto8 | Goto16 => {
10578                self.frame_mut().pc = a as usize;
10579            }
10580            IfTrue | IfTrue8 => {
10581                let value = self.pop();
10582                if value.to_boolean() {
10583                    self.frame_mut().pc = a as usize;
10584                }
10585            }
10586            IfFalse | IfFalse8 => {
10587                let value = self.pop();
10588                if !value.to_boolean() {
10589                    self.frame_mut().pc = a as usize;
10590                }
10591            }
10592            Catch => {
10593                // Pushes the handler target onto the value stack; `unwind` finds it.
10594                self.push(Value::CatchOffset(a));
10595            }
10596            Gosub => {
10597                self.push(Value::ReturnAddress(next as u32));
10598                self.frame_mut().pc = a as usize;
10599            }
10600            Ret => {
10601                let value = self.pop();
10602                match value {
10603                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10604                    _ => {
10605                        return Err(Signal::Throw(
10606                            self.make_error("InternalError", "invalid return address"),
10607                        ));
10608                    }
10609                }
10610            }
10611            NipCatch => {
10612                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10613                // including the marker, keeping the top value.
10614                let top = self.pop();
10615                loop {
10616                    match self.pop() {
10617                        Value::CatchOffset(_) | Value::Undefined => break,
10618                        _ => {}
10619                    }
10620                    if self.frame().stack.is_empty() {
10621                        break;
10622                    }
10623                }
10624                self.push(top);
10625            }
10626            Throw => {
10627                let value = self.pop();
10628                return Err(Signal::Throw(value));
10629            }
10630            ThrowError => {
10631                let name = self.atom_text(a as usize);
10632                let (class, message) = match b {
10633                    0 => ("TypeError", format!("'{name}' is read-only")),
10634                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10635                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
10636                    // `delete super.x` is a syntax-level mistake the reference reports
10637                    // with this wording, not a property-access failure.
10638                    3 => (
10639                        "ReferenceError",
10640                        "unsupported reference to 'super'".to_string(),
10641                    ),
10642                    4 => (
10643                        "TypeError",
10644                        "iterator does not have a throw method".to_string(),
10645                    ),
10646                    5 => (
10647                        "ReferenceError",
10648                        "invalid assignment left-hand side".to_string(),
10649                    ),
10650                    _ => ("TypeError", format!("invalid operation on '{name}'")),
10651                };
10652                return Err(Signal::Throw(self.make_error(class, &message)));
10653            }
10654            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10655            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10656            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10657            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10658            Await => return Ok(Step::Suspend(SuspendKind::Await)),
10659            ReturnAsync => {
10660                // The reference's `return_async` returns `undefined` and lets the resume
10661                // machinery pick the real value off `sp[-1]`, which is how it tells a
10662                // completion from a suspension. Carrying the value explicitly says the
10663                // same thing without the implicit stack slot.
10664                let value = self.pop();
10665                return Ok(Step::Return(value));
10666            }
10667            Return => {
10668                let value = self.pop();
10669                return Ok(Step::Return(value));
10670            }
10671            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10672
10673            // -- calls ------------------------------------------------------
10674            Call | Call0 | Call1 | Call2 | Call3 => {
10675                let argc = self.argc_operand(op, a);
10676                let args = self.pop_n(argc);
10677                let callee = self.pop();
10678                // A plain call has no receiver; the callee decides what to do with
10679                // `undefined` (a sloppy function substitutes the global object).
10680                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
10681                    self.push(result);
10682                }
10683            }
10684            CallConstructor => {
10685                // `constructor this_obj args… -> object`. The duplicated
10686                // constructor is `new.target`; this milestone does not expose it,
10687                // so the extra copy is simply consumed here.
10688                let argc = a as usize;
10689                let args = self.pop_n(argc);
10690                let new_target = self.pop();
10691                let callee = self.pop();
10692                let result = self.construct(callee, new_target, args)?;
10693                self.push(result);
10694            }
10695            CallMethod => {
10696                let argc = a as usize;
10697                let args = self.pop_n(argc);
10698                let callee = self.pop();
10699                let this = self.pop();
10700                if let Some(result) = self.call_or_push(callee, this, args)? {
10701                    self.push(result);
10702                }
10703            }
10704            Apply => {
10705                // `func this array -> result`, the spread-call form: the compiler
10706                // builds one array of arguments, and all that is left here is to
10707                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
10708                let array = self.pop();
10709                let this = self.pop();
10710                let callee = self.pop();
10711                let args = self.array_like_to_args(&array)?;
10712                if a & 1 != 0 {
10713                    let result = self.construct(callee, this, args)?;
10714                    self.push(result);
10715                } else if let Some(result) = self.call_or_push(callee, this, args)? {
10716                    self.push(result);
10717                }
10718            }
10719            TailCall | TailCallMethod => {
10720                // `tail_call` is `call` whose result is returned immediately — the
10721                // reference jumps straight to `done` instead of storing the value and
10722                // running on. The callee still gets its own frame, so deep tail
10723                // recursion hits the stack limit exactly like plain recursion does;
10724                // marking this frame lets the return path unwind without needing
10725                // instructions after the call.
10726                let argc = if op == TailCallMethod {
10727                    a as usize
10728                } else {
10729                    self.argc_operand(op, a)
10730                };
10731                let args = self.pop_n(argc);
10732                let callee = self.pop();
10733                let this = if op == TailCallMethod {
10734                    self.pop()
10735                } else {
10736                    Value::Undefined
10737                };
10738                if let Value::Object(function) = &callee
10739                    && let Some((code, env)) = bytecode_of(function)
10740                {
10741                    // A generator or async body is not run here at all: calling it only
10742                    // *creates* the generator/coroutine, so it must not inherit this
10743                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
10744                    // onto `f`'s frame, and the first `yield`/`await` then reported
10745                    // "a generator body ran as an ordinary call".
10746                    if code.code.kind.is_generator() || code.code.kind.is_async() {
10747                        let value = self.call_value(callee, this, args)?;
10748                        return Ok(Step::Return(value));
10749                    }
10750                    self.frame_mut().tail = true;
10751                    self.push_frame(code, env, this, args, callee)?;
10752                    return Ok(Step::Continue);
10753                }
10754                // A native callee has no frame to reuse, so its value is simply
10755                // returned.
10756                let value = self.call_value(callee, this, args)?;
10757                return Ok(Step::Return(value));
10758            }
10759
10760            // -- objects ----------------------------------------------------
10761            SpecialObject => {
10762                let value = self.special_object(a)?;
10763                self.push(value);
10764            }
10765            PrivateSymbol => {
10766                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
10767                // symbol each time it is evaluated, which is why the compiler evaluates it
10768                // once (at class definition) and stores it in a class-scope binding.
10769                let name = self.atom_text(a as usize);
10770                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
10771                self.push(Value::Symbol(symbol));
10772            }
10773            GetPrivateField => {
10774                // `obj symbol -> value`. A missing private field is a TypeError, which is what
10775                // makes `#x` inaccessible on any object not built by this class.
10776                let symbol = self.pop();
10777                let object = self.pop();
10778                let value = self.read_private_field(&object, &symbol)?;
10779                self.push(value);
10780            }
10781            PutPrivateField => {
10782                // `obj value symbol ->`, and the store is a plain assignment to a property the
10783                // class already created, so there is no setter to consult.
10784                let symbol = self.pop();
10785                let value = self.pop();
10786                let object = self.pop();
10787                self.write_private_field(&object, &symbol, value)?;
10788            }
10789            DefinePrivateField => {
10790                // `obj symbol value -> obj`: a field initialiser creates the property, and
10791                // redefining one is a TypeError ("already exists").
10792                let value = self.pop();
10793                let symbol = self.pop();
10794                let object = self.pop();
10795                self.define_private_field(&object, &symbol, value)?;
10796                self.push(object);
10797            }
10798            PrivateIn => {
10799                // `obj key -> bool`: `#x in o`. The second operand decides which question is
10800                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
10801                // is a field, so this is an own-property test; a *function* is a method or
10802                // accessor, so this is a brand check.
10803                let key = self.pop();
10804                let object = self.pop();
10805                let Some(target) = object.as_object() else {
10806                    return Err(Signal::Throw(
10807                        self.make_error("TypeError", "invalid 'in' operand"),
10808                    ));
10809                };
10810                let present = match &key {
10811                    Value::Object(_) => self.check_brand(target, &key)?,
10812                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
10813                };
10814                self.push(Value::Bool(present));
10815            }
10816            AddBrand => {
10817                // `obj home ->`: create the class brand on `home` if it has none, then give
10818                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
10819                // class definition: only the prototype's copy of the symbol is wanted.
10820                let home = self.pop();
10821                let object = self.pop();
10822                self.add_brand(&object, &home)?;
10823            }
10824            CheckBrand => {
10825                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
10826                // Both stay, because the caller needs them — `nip` halves a read into its
10827                // value and `call_method` uses the pair as receiver and callee.
10828                let function = self.peek(0);
10829                let object = self.peek(1);
10830                let Some(target) = object.as_object() else {
10831                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10832                };
10833                if !self.check_brand(target, &function)? {
10834                    return Err(Signal::Throw(
10835                        self.make_error("TypeError", "invalid brand on object"),
10836                    ));
10837                }
10838            }
10839            GetLength => {
10840                // `get_length` is the `.length` read; an array and a string answer
10841                // from their own length, anything else from the property.
10842                let target = self.pop();
10843                let value = match &target {
10844                    Value::Object(object) => match object.array_length() {
10845                        Some(length) => crate::object::length_value(length),
10846                        None => self.read_field(&target, "length")?,
10847                    },
10848                    Value::String(text) => Value::Int(text.utf16_len() as i32),
10849                    _ => self.read_field(&target, "length")?,
10850                };
10851                self.push(value);
10852            }
10853            GetField | GetField2 => {
10854                let object = self.pop();
10855                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
10856                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
10857                // just below is what lets the borrow outlive the `&mut self` the lookup
10858                // needs — one refcount bump instead of a key clone plus its drop, on the
10859                // hottest property path there is: every `o.x` and every `o.m()` receiver.
10860                let code = self.frame().code.clone();
10861                let key = &code.atom_keys[a as usize];
10862                let value = self.read_field_cached(&object, key, next)?;
10863                if op == GetField2 {
10864                    self.push(object);
10865                }
10866                self.push(value);
10867            }
10868            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
10869                let key = self.pop();
10870                let object = self.pop();
10871                let key = self.propkey(&key)?;
10872                let value = self.read_field_key(&object, &key)?;
10873                if matches!(op, GetArrayEl2 | GetArrayEl3) {
10874                    self.push(object);
10875                }
10876                if op == GetArrayEl3 {
10877                    // The key goes back in its *value* form, which the compiler stores
10878                    // into the target of a destructuring assignment.
10879                    self.push(match &key {
10880                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
10881                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
10882                    });
10883                }
10884                self.push(value);
10885            }
10886            PutField => {
10887                let value = self.pop();
10888                let object = self.pop();
10889                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
10890                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
10891                // only reads. `this.value = …` is the write half of the hottest loop in
10892                // `property:method-call`, and `own_property_key` was 4.8% of the case.
10893                let code = self.frame().code.clone();
10894                let key = &code.atom_keys[a as usize];
10895                self.write_field_key(&object, key, value)?;
10896            }
10897            PutArrayEl => {
10898                let value = self.pop();
10899                let key = self.pop();
10900                let object = self.pop();
10901                let key = self.propkey(&key)?;
10902                self.write_field_key(&object, &key, value)?;
10903            }
10904            DefineField => {
10905                let value = self.pop();
10906                let object = self.pop();
10907                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
10908                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
10909                // three U+FFFD — a property under a different name from the one
10910                // `o["\uD800"]` reads.
10911                let code = self.frame().code.clone();
10912                let key = code.atom_keys[a as usize].clone();
10913                // No naming here. `{m: function(){}}` is named by the *compiler*, which
10914                // emits `set_name` — and only where `NamedEvaluation` applies, so
10915                // `{m: (0, function(){})}` stays anonymous. Naming every function that
10916                // reaches a property definition got that case wrong, and the compiler is
10917                // the only place that can tell the two apart.
10918                if let Some(target) = object.as_object() {
10919                    // Only an *array* stores into the element vector. A numeric key
10920                    // on an ordinary object is an ordinary property, which is what
10921                    // makes `{1: 'a'}` iterate as a key rather than disappear.
10922                    let stored = target.is_array()
10923                        && key.as_str().and_then(array_index).is_some_and(|index| {
10924                            target.array_set(self.heap, index as usize, value.clone())
10925                        });
10926                    if !stored {
10927                        target.define_data_key(&key, value);
10928                    }
10929                }
10930                self.push(object);
10931            }
10932            DefineArrayEl => {
10933                // `obj key value -> obj key`. The *value* form of the key is what goes
10934                // back on the stack — the compiler stores it into the pattern's binding —
10935                // so the symbol is not stringified on the way through.
10936                let value = self.pop();
10937                let key_value = self.pop();
10938                let object = self.peek(0);
10939                let key = self.propkey(&key_value)?;
10940                self.write_field_key(&object, &key, value)?;
10941                self.push(key_value);
10942            }
10943            SetHomeObject => {
10944                // `obj func -> obj func`: records the object a method was defined on so
10945                // `super` inside it resolves against that object's prototype.
10946                let function = self.peek(0);
10947                let home = self.peek(1);
10948                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
10949                    function.set_home_object(Some(home.clone()));
10950                }
10951            }
10952            Regexp => {
10953                // `pattern flags -> regexp`. A literal compiles here rather than through the
10954                // constructor, which is both what the reference's dedicated opcode is for
10955                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
10956                let flags = self.pop();
10957                let pattern = self.pop();
10958                let pattern = self.to_js_string(&pattern)?;
10959                let flags = self.to_js_string(&flags)?;
10960                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
10961                self.push(Value::Object(object));
10962            }
10963            UsingDisposeInit => {
10964                // The error state a disposal accumulates into. Uninitialised means "no
10965                // failure yet"; anything else is the exception being propagated.
10966                self.push(Value::Uninitialized);
10967            }
10968            UsingCheck => {
10969                // `value -> value, method`: validate and snapshot the disposer now, so a
10970                // later change to `Symbol.dispose` cannot change what gets called, and so a
10971                // value that is not disposable fails before the body runs.
10972                let value = self.pop();
10973                let method = self.using_method_for(&value, a as u8 == 1)?;
10974                self.push(value);
10975                self.push(method);
10976            }
10977            UsingDispose => {
10978                // `error_state -> error_state'`: dispose the variable at `slot` — its value
10979                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
10980                // the pending error.
10981                let slot = self.slot_operand(op, a);
10982                let error_state = self.pop();
10983                let merged = self.using_dispose_once(slot, error_state)?;
10984                self.push(merged);
10985            }
10986            UsingDisposeMerge => {
10987                let new_error = self.pop();
10988                let error_state = self.pop();
10989                let merged = self.merge_dispose_error(new_error, error_state);
10990                self.push(merged);
10991            }
10992            UsingDisposeEnd => {
10993                // A disposal that failed replaces the block's normal completion, so the
10994                // error state becomes a real throw here rather than at the call site.
10995                let error_state = self.pop();
10996                if !matches!(error_state, Value::Uninitialized) {
10997                    return Err(Signal::Throw(error_state));
10998                }
10999            }
11000            UsingDisposeAsync => {
11001                // `await using` needs a promise to await and this runtime has no
11002                // `Promise` builtin, so the disposer is called synchronously and its result
11003                // discarded. That is correct for a disposer that returns nothing and is
11004                // reported as a gap rather than silently skipped.
11005                let slot = self.slot_operand(op, a);
11006                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11007                self.push(error_state);
11008            }
11009            GetSuper => {
11010                // `obj -> obj's prototype`: the starting point of a `super` lookup.
11011                let object = self.pop();
11012                let proto = match &object {
11013                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11014                    _ => Value::Null,
11015                };
11016                self.push(proto);
11017            }
11018            GetSuperValue => {
11019                // `receiver proto key -> value`, searching from `proto` but reporting to
11020                // `receiver`, which is what `super.g` must do for a getter to see `this`.
11021                //
11022                // Three values in, one out: the receiver is *consumed*, not left under the
11023                // result. Leaving it there was invisible for `super.x` in `return` or
11024                // statement position (the result is what gets popped) and corrupted the
11025                // frame everywhere else — `print(super.x)` left the class where the call
11026                // opcode looks for the receiver and called the class itself.
11027                let key = self.pop();
11028                let proto = self.pop();
11029                let receiver = self.pop();
11030                let value = self.super_read(&receiver, &proto, &key)?;
11031                self.push(value);
11032            }
11033            PutSuperValue => {
11034                // `receiver proto key value ->`: a store that starts at `proto` but
11035                // assigns to `receiver`.
11036                let value = self.pop();
11037                let key = self.pop();
11038                let proto = self.pop();
11039                let receiver = self.pop();
11040                self.super_write(&receiver, &proto, &key, value)?;
11041            }
11042            DefineClass => {
11043                // `parent ctor -> ctor proto`: the constructor becomes the class and a
11044                // fresh prototype object lands on top for the methods to go on.
11045                let name = self.atom_text(a as usize);
11046                let (ctor, proto) = self.define_class(&name, b)?;
11047                self.push(ctor);
11048                self.push(Value::Object(proto));
11049            }
11050            DefineClassComputed => {
11051                // `parent ctor key -> ctor proto key`: the computed name stays put so
11052                // `define_field`-style consumers can still read it.
11053                let key = self.pop();
11054                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11055                let (ctor, proto) = self.define_class(&name, b)?;
11056                self.push(ctor);
11057                self.push(Value::Object(proto));
11058                self.push(key);
11059            }
11060            DefineMethod => {
11061                let function = self.pop();
11062                let object = self.pop();
11063                // The exact key, like `define_field`: a quoted method key may hold an
11064                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11065                // that `o["\uD800"]` finds.
11066                let code = self.frame().code.clone();
11067                let key = code.atom_keys[a as usize].clone();
11068                // A method's `[[HomeObject]]` is the object it was defined on, which is
11069                // what `super` inside it resolves against.
11070                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11071                    function.set_home_object(Some(object.clone()));
11072                }
11073                if let Some(text) = key.as_wtf8() {
11074                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11075                } else {
11076                    self.set_function_name(
11077                        &function,
11078                        &key_with_accessor_prefix(&key.to_string(), b),
11079                    );
11080                }
11081                if let Some(array) = object.as_object() {
11082                    define_function_property(array, &key, function, b);
11083                }
11084                self.push(object);
11085            }
11086            DefineMethodComputed => {
11087                let function = self.pop();
11088                let key = self.pop();
11089                let object = self.pop();
11090                let key = self.propkey(&key)?;
11091                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11092                // the name: `super` inside a computed method resolves through it. Without
11093                // this, `class B extends A { [k]() { return super.m() } }` read the
11094                // home object as null and threw.
11095                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11096                    function.set_home_object(Some(object.clone()));
11097                }
11098                match key.as_wtf8() {
11099                    Some(text) => {
11100                        let name = accessor_prefixed(text, a);
11101                        self.set_function_name_wtf8(&function, &name);
11102                    }
11103                    None => self.set_function_name(
11104                        &function,
11105                        &key_with_accessor_prefix(&key.to_string(), a),
11106                    ),
11107                }
11108                if let Some(array) = object.as_object() {
11109                    define_function_property(array, &key, function, a);
11110                }
11111                self.push(object);
11112            }
11113            SetProto => {
11114                let proto = self.pop();
11115                let object = self.pop();
11116                if let Some(target) = object.as_object() {
11117                    target.set_proto(proto.as_object().cloned());
11118                }
11119                self.push(object);
11120            }
11121            CopyDataProperties => {
11122                let exclusion = self.pop();
11123                let source = self.pop();
11124                let target = self.peek(0);
11125                self.copy_properties(&target, &source, &exclusion)?;
11126                self.push(source);
11127                self.push(exclusion);
11128            }
11129            ToPropkey => {
11130                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11131                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11132                // ordinary `"Symbol(b)"` property.
11133                let value = self.pop();
11134                let key = match self.propkey(&value)? {
11135                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11136                    PropertyKey::String(text) => self.string_wtf8(text),
11137                };
11138                self.push(key);
11139            }
11140            SetName => {
11141                let function = self.peek(0);
11142                let name = self.atom_wtf8(a as usize);
11143                self.set_function_name_wtf8(&function, &name);
11144            }
11145            SetNameComputed => {
11146                let key = self.peek(1);
11147                let function = self.peek(0);
11148                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11149                self.set_function_name(&function, &name);
11150            }
11151
11152            // -- arrays -----------------------------------------------------
11153            ArrayFrom => {
11154                let count = a as usize;
11155                let elements = self.pop_n(count);
11156                let array = self.new_array(elements);
11157                self.push(Value::Object(array));
11158            }
11159            Append => {
11160                // `array index iterable -> array new_index`
11161                let iterable = self.pop();
11162                self.pop();
11163                let array = self.peek(0);
11164                let added = self.append_enumerate(&array, &iterable)?;
11165                self.push(Value::Int(added));
11166            }
11167
11168            // -- iteration --------------------------------------------------
11169            ForInStart => {
11170                let value = self.pop();
11171                let record = self.for_in_record(&value)?;
11172                self.push(Value::Object(record));
11173            }
11174            ForInNext => {
11175                // `record -> record key done`. The flag is *done*, not "found":
11176                // the compiler tests it with `if_false` to jump back into the body,
11177                // so reporting `true` while keys remain would end the loop at once.
11178                let record = self.peek(0);
11179                match self.for_in_advance(&record)? {
11180                    Some(key) => {
11181                        let text = self.string(key);
11182                        self.push(text);
11183                        self.push(Value::Bool(false));
11184                    }
11185                    None => {
11186                        self.push(Value::Undefined);
11187                        self.push(Value::Bool(true));
11188                    }
11189                }
11190            }
11191            ForOfStart => {
11192                let value = self.pop();
11193                let iterator = self.get_iterator(&value)?;
11194                self.push(iterator.object);
11195                self.push(iterator.next);
11196                self.push(Value::CatchOffset(0));
11197            }
11198            ForOfNext => {
11199                // `iter next catch_offset -> iter next catch_offset value done`.
11200                //
11201                // The operand is how many values sit *above* the iterator triple: a
11202                // destructuring rest element keeps its target array and running index
11203                // there while draining the iterator, so the triple is not at the top.
11204                let extra = a as usize;
11205                let iterator_slot = 2 + extra;
11206                // An exhausted iterator is replaced by `undefined` (see below), so a
11207                // second step must not call `next` again — `Array.from` and a
11208                // destructuring pattern both keep stepping past the end.
11209                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11210                    (Value::Undefined, true)
11211                } else {
11212                    let iterator = Iterator {
11213                        object: self.peek(iterator_slot),
11214                        next: self.peek(1 + extra),
11215                    };
11216                    self.iterator_step(&iterator)?
11217                };
11218                if done {
11219                    // The result's `value` is meaningless once the iterator is done:
11220                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11221                    // rather than binding the generator's return value.
11222                    let top = self.frame().stack.len() - 1 - iterator_slot;
11223                    self.frame_mut().stack[top] = Value::Undefined;
11224                    self.push(Value::Undefined);
11225                    self.push(Value::Bool(true));
11226                } else {
11227                    self.push(value);
11228                    self.push(Value::Bool(false));
11229                }
11230            }
11231            IteratorNext => {
11232                // `iter next catch val -> iter next catch val'`: replace the argument with
11233                // the result of `next(val)`. The triple below stays put, which is why the
11234                // three instructions of the `yield*` loop all address the stack the same way.
11235                let value = self.pop();
11236                let object = self.peek(2);
11237                let next = self.peek(1);
11238                let result = self.call_value(next, object, vec![value])?;
11239                self.push(result);
11240            }
11241            IteratorCall => {
11242                // `iter next catch val -> iter next catch val' flag`.
11243                //
11244                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11245                // The flag is `true` when the method was missing, which is how the
11246                // caller learns that the inner iterator cannot take part in the
11247                // unwinding.
11248                let value = self.pop();
11249                let object = self.peek(2);
11250                let key = if a & 1 != 0 { "throw" } else { "return" };
11251                let method = self.read_field(&object, key)?;
11252                if matches!(method, Value::Undefined | Value::Null) {
11253                    self.push(value);
11254                    self.push(Value::Bool(true));
11255                } else {
11256                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
11257                    let result = self.call_value(method, object, argument)?;
11258                    self.push(result);
11259                    self.push(Value::Bool(false));
11260                }
11261            }
11262            IteratorCheckObject => {
11263                if !matches!(self.peek(0), Value::Object(_)) {
11264                    return Err(Signal::Throw(
11265                        self.make_error("TypeError", "iterator must return an object"),
11266                    ));
11267                }
11268            }
11269            IteratorClose => {
11270                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
11271                // calling the iterator's `return` so it can release whatever it holds.
11272                //
11273                // The catch offset goes first, so an exception from `return` is not caught
11274                // by the loop being abandoned. This used to pop the three operands and call
11275                // nothing at all, which made `break` out of a `for of` invisible to an
11276                // iterator with a `return` method.
11277                self.pop();
11278                self.pop();
11279                let iterator = self.pop();
11280                if !matches!(iterator, Value::Undefined) {
11281                    let method = self.read_field(&iterator, "return")?;
11282                    if !matches!(method, Value::Undefined | Value::Null) {
11283                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
11284                        // §7.4.6: a `return` that answers a non-object is a TypeError.
11285                        if !matches!(result, Value::Object(_)) {
11286                            return Err(Signal::Throw(
11287                                self.make_error("TypeError", "iterator must return an object"),
11288                            ));
11289                        }
11290                    }
11291                }
11292            }
11293            Import => {
11294                // `import(specifier)`: the options slot is on top and is not read yet.
11295                let _options = self.pop();
11296                let specifier = self.pop();
11297                let promise = self.dynamic_import(specifier)?;
11298                self.push(promise);
11299            }
11300            ForAwaitOfStart => {
11301                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
11302                // `Symbol.iterator` fallback.
11303                let value = self.pop();
11304                let iterator = self.get_async_iterator(&value)?;
11305                self.push(iterator.object);
11306                self.push(iterator.next);
11307                self.push(Value::CatchOffset(0));
11308            }
11309            ForAwaitOfNext => {
11310                // `for await` steps the iterator and leaves the *result* wrapped in a
11311                // promise, so the `await` the compiler emits right after this can suspend
11312                // on it. Unwrapping happens in `iterator_get_value_done`.
11313                let extra = a as usize;
11314                let iterator_slot = 2 + extra;
11315                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
11316                    Value::Undefined
11317                } else {
11318                    let iterator = Iterator {
11319                        object: self.peek(iterator_slot),
11320                        next: self.peek(1 + extra),
11321                    };
11322                    let next = iterator.next.clone();
11323                    self.call_value(next, iterator.object, Vec::new())?
11324                };
11325                let promise = self.promise_resolve_value(result)?;
11326                self.push(promise);
11327            }
11328            IteratorGetValueDone => {
11329                // `result -> value done`. A missing result object means the iterator was
11330                // already exhausted, which the loop treats as `done`.
11331                let result = self.pop();
11332                let done = match &result {
11333                    Value::Object(object) => self
11334                        .get_property(object, "done")?
11335                        .is_some_and(|value| value.to_boolean()),
11336                    _ => true,
11337                };
11338                if done {
11339                    // Clear the iterator object so the `iterator_close` the loop emits on
11340                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
11341                    // on normal completion, and this is where a normal completion is
11342                    // recognised — the same trick `for_of_next` uses, which also replaces
11343                    // the slot with `undefined`.
11344                    //
11345                    // The layout is fixed because only `for await` emits this opcode:
11346                    // `iter next catch [result]`, so the iterator is three below the top.
11347                    let depth = self.frame().stack.len();
11348                    if depth >= 3 {
11349                        self.frame_mut().stack[depth - 3] = Value::Undefined;
11350                    }
11351                    self.push(Value::Undefined);
11352                    self.push(Value::Bool(true));
11353                } else {
11354                    let Value::Object(object) = &result else {
11355                        self.push(Value::Undefined);
11356                        self.push(Value::Bool(true));
11357                        return Ok(Step::Continue);
11358                    };
11359                    let value = self
11360                        .get_property(object, "value")?
11361                        .unwrap_or(Value::Undefined);
11362                    self.push(value);
11363                    self.push(Value::Bool(false));
11364                }
11365            }
11366
11367            Delete => {
11368                // `delete obj[key]`, where the key was just pushed. Deleting an array
11369                // index leaves a *hole* rather than closing the gap, and a
11370                // non-configurable property answers `false` and stays.
11371                let key = self.pop();
11372                let target = self.pop();
11373                let key = self.propkey(&key)?;
11374                let text_label = key.as_str().unwrap_or("").to_string();
11375                let deleted = match &target {
11376                    Value::Object(object) => {
11377                        let object = object.clone();
11378                        self.delete_property_key(&object, &key)?
11379                    }
11380                    // A string's `length` and its index properties are
11381                    // non-configurable, so deleting one answers `false`.
11382                    Value::String(text) => {
11383                        !(text_label == "length"
11384                            || array_index(&text_label)
11385                                .is_some_and(|index| (index as usize) < text.utf16_len()))
11386                    }
11387                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
11388                    // object to delete from, and only a *boxable* primitive has one.
11389                    Value::Undefined | Value::Null => {
11390                        return Err(Signal::Throw(
11391                            self.make_error("TypeError", "cannot convert to object"),
11392                        ));
11393                    }
11394                    // Any other primitive has no own properties; deleting nothing
11395                    // succeeds.
11396                    _ => true,
11397                };
11398                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
11399                // `TypeError` rather than a `false` result. Sloppy mode silently reports
11400                // the refusal, which is why the same statement throws here but not there.
11401                if !deleted && self.current_strict() {
11402                    return Err(Signal::Throw(
11403                        self.make_error("TypeError", "cannot delete property"),
11404                    ));
11405                }
11406                self.push(Value::Bool(deleted));
11407            }
11408
11409            // -- exceptions and bookkeeping ---------------------------------
11410            Fclosure | Fclosure8 => {
11411                let value = self.closure(a as usize)?;
11412                self.push(value);
11413            }
11414
11415            other => {
11416                let name = other.info().name;
11417                return Err(Signal::Throw(self.make_error(
11418                    "InternalError",
11419                    &format!("{name} is not implemented yet"),
11420                )));
11421            }
11422        }
11423        Ok(Step::Continue)
11424    }
11425
11426    // -- operand helpers ----------------------------------------------------
11427
11428    /// The slot index an operand names, taking short forms into account.
11429    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11430        use Opcode::*;
11431        match op {
11432            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11433            | SetVarRef0 => 0,
11434            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11435            | SetVarRef1 => 1,
11436            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11437            | SetVarRef2 => 2,
11438            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11439            | SetVarRef3 => 3,
11440            _ => a as usize,
11441        }
11442    }
11443
11444    /// The argument count of a call, taking `call0`…`call3` into account.
11445    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11446        use Opcode::*;
11447        match op {
11448            Call0 => 0,
11449            Call1 => 1,
11450            Call2 => 2,
11451            Call3 => 3,
11452            _ => a as usize,
11453        }
11454    }
11455
11456    /// The atom's name as a property key.
11457    ///
11458    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11459    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11460    /// `String::clone` was a heap allocation and a copy — per property access.
11461    /// The atom at `index`, as a property key.
11462    ///
11463    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11464    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11465    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11466    /// 5.3% of `property:monomorphic`.
11467    /// The atom's text, exactly — including an unpaired surrogate.
11468    ///
11469    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11470    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11471    /// `atom_text` below is for the other kind of use, where the atom is a key in the
11472    /// engine's own tables.
11473    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11474        self.frame()
11475            .code
11476            .code
11477            .atoms
11478            .get(index)
11479            .map(|atom| match atom {
11480                Atom::Str(text) => text.clone(),
11481                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11482                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11483                Atom::Null => crate::value::Wtf8::new(String::new()),
11484            })
11485            .unwrap_or_default()
11486    }
11487
11488    fn atom_text(&self, index: usize) -> String {
11489        self.frame()
11490            .code
11491            .code
11492            .atoms
11493            .get(index)
11494            .map(|atom| match atom {
11495                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11496                // compare it to an identifier, and a surrogate-bearing name is reachable
11497                // through `atom_wtf8` where it matters.
11498                Atom::Str(text) => text.to_string_lossy().into_owned(),
11499                Atom::Index(value) => value.to_string(),
11500                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11501                // `throw_error`, `delete super.x`) never read it.
11502                Atom::Null => String::new(),
11503            })
11504            .unwrap_or_default()
11505    }
11506
11507    fn constant(&mut self, index: usize) -> JsResult<Value> {
11508        let constant = self.frame().code.code.cpool.get(index).cloned();
11509        Ok(match &constant {
11510            Some(Constant::Number(number)) => Value::Float(*number),
11511            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11512            Some(Constant::BigInt { digits, radix }) => {
11513                match crate::bigint::BigInt::from_radix(digits, *radix) {
11514                    Some(big) => self.bigint(big),
11515                    // A literal the parser accepted is always parseable; a failure here
11516                    // would be a compiler bug, so it reads as an `InternalError`.
11517                    None => {
11518                        return Err(Signal::Throw(
11519                            self.make_error("InternalError", "unparseable bigint literal"),
11520                        ));
11521                    }
11522                }
11523            }
11524            Some(Constant::Function(_)) => {
11525                return Err(Signal::Throw(
11526                    self.make_error("InternalError", "a bare function constant"),
11527                ));
11528            }
11529            // A tagged template's call site: a frozen array of the cooked chunks with a
11530            // frozen `raw` array beside it, which is what `String.raw` reads back.
11531            Some(Constant::Template { cooked, raw }) => {
11532                let cooked_values: Vec<Value> = cooked
11533                    .iter()
11534                    .map(|chunk| match chunk {
11535                        Some(text) => self.string_wtf8(text.clone()),
11536                        None => Value::Undefined,
11537                    })
11538                    .collect();
11539                let raw_values: Vec<Value> =
11540                    raw.iter().map(|text| self.string(text.clone())).collect();
11541                let raw_array = self.new_array(raw_values);
11542                raw_array.set_extensible(false);
11543                let template = self.new_array(cooked_values);
11544                template.define(
11545                    "raw",
11546                    Property::with_attributes(Value::Object(raw_array), false, false),
11547                );
11548                template.set_extensible(false);
11549                Value::Object(template)
11550            }
11551            _ => Value::Undefined,
11552        })
11553    }
11554
11555    /// The reference cell a closure-variable slot names.
11556    ///
11557    /// Two kinds of binding share this addressing: a genuine closure variable
11558    /// (captured from an enclosing function) lives in this frame's environment,
11559    /// while a *declared global* lives in the realm so that a script, a function
11560    /// declaration and their uses all see one binding. A plain `Global` — an
11561    /// undeclared name that may be satisfied by the global object — has no cell at
11562    /// all, which is how `typeof x` still works for a name that does not exist.
11563    /// The reference cell a closure-variable slot names.
11564    ///
11565    /// The environment is resolved once, when the closure is built, and this is
11566    /// just the lookup afterwards. A *declared global* is in there too, pointing at
11567    /// the realm's cell, so a script, a hoisted function declaration and their uses
11568    /// all share one binding. A plain `Global` — a name the script never declared —
11569    /// is read and written through `get_var`/`put_var` by name instead, which is
11570    /// what lets the global object satisfy it.
11571    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11572        self.frame().env.cells.get(slot).cloned()
11573    }
11574
11575    /// Whether `slot` refers to a global binding through the reference table.
11576    ///
11577    /// A global's cell in the closure environment only exists so the slot has
11578    /// something to point at; the binding itself lives on the global object (a `var`)
11579    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11580    /// be routed, not performed on the placeholder.
11581    fn is_global_slot(&self, slot: usize) -> bool {
11582        self.frame()
11583            .code
11584            .code
11585            .closure_vars
11586            .get(slot)
11587            .is_some_and(|c| {
11588                // A module's declarations and imports are *not* globals: their cells are
11589                // the module environment's, filled by the host, so the placeholder routing
11590                // must not apply to them.
11591                matches!(
11592                    c.closure_type,
11593                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11594                )
11595            })
11596    }
11597
11598    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11599        if self.is_global_slot(slot) {
11600            return self.get_global(slot);
11601        }
11602        Ok(self
11603            .var_ref_cell(slot)
11604            .map(|cell| cell.get())
11605            .unwrap_or(Value::Undefined))
11606    }
11607
11608    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11609        // A function declaration is hoisted by storing into a global reference before
11610        // the body runs, so this path is also what puts it on the global object.
11611        if self.is_global_slot(slot) {
11612            return self.put_global(slot, value);
11613        }
11614        if let Some(cell) = self.var_ref_cell(slot) {
11615            cell.set(value);
11616        }
11617        Ok(())
11618    }
11619
11620    // -- closures -----------------------------------------------------------
11621
11622    /// Build the closure for the function constant `index`.
11623    ///
11624    /// Every entry in the child's closure table names where its binding lives in
11625    /// *this* frame: a local or argument slot that was marked captured, or a cell
11626    /// this frame is itself holding. That is how a variable three functions deep
11627    /// stays one binding.
11628    fn closure(&mut self, index: usize) -> JsResult<Value> {
11629        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11630        else {
11631            return Err(Signal::Throw(
11632                self.make_error("InternalError", "fclosure of a non-function"),
11633            ));
11634        };
11635        let mut cells = Vec::with_capacity(function.closure_vars.len());
11636        for closure_var in &function.closure_vars {
11637            let cell = match closure_var.closure_type {
11638                ClosureType::Arg => {
11639                    let slot = closure_var.var_idx as usize;
11640                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11641                }
11642                ClosureType::Local => {
11643                    let slot = closure_var.var_idx as usize;
11644                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11645                }
11646                ClosureType::Ref | ClosureType::GlobalRef => {
11647                    // A `Ref` names a cell in this frame's own closure table; a
11648                    // `GlobalRef` also starts there, then resolves by name below.
11649                    let slot = closure_var.var_idx as usize;
11650                    if let Some(cell) = self.frame().env.cells.get(slot) {
11651                        cells.push(cell.clone());
11652                        continue;
11653                    }
11654                    -1
11655                }
11656                _ => -1,
11657            };
11658            if cell >= 0 {
11659                let cell = self.frame().cells[cell as usize].clone();
11660                cells.push(cell);
11661                continue;
11662            }
11663            // A global: the cell is created on demand and shared through the realm,
11664            // so every function sees one binding.
11665            let name = closure_var.name.clone();
11666            let cell = match self.realm.globals.get(&name) {
11667                Some(cell) => cell.clone(),
11668                None => {
11669                    let cell = self.new_cell(Value::Undefined);
11670                    self.realm.globals.insert(name.clone(), cell.clone());
11671                    cell
11672                }
11673            };
11674            cells.push(cell);
11675        }
11676        let name = function.name.clone();
11677        // `.length` is the arity before any default or rest parameter, not the number
11678        // of slots a pattern parameter needs.
11679        let length = function.defined_args;
11680        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
11681        // function and an arrow function do not. A *method* also does not, but that is not
11682        // known here — the method is marked when the `[[HomeObject]]` is attached (see
11683        // `set_home_object`), which is the moment it becomes a method.
11684        let function_kind = function.kind;
11685        let constructible =
11686            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
11687        let code = Gc::new(self.heap, CompiledCode::new(*function));
11688        // A closure built inside an `eval` inherits the eval's view of the enclosing
11689        // bindings, so it can still read them once the eval has returned.
11690        let eval_scope = self
11691            .active_eval_scope
11692            .clone()
11693            .or_else(|| self.frame().env.eval_scope.clone());
11694        // A closure sees the variables a direct `eval` declared in the frame it was
11695        // created in — the ones declared before *and after* it, so the same object is
11696        // shared; only the phase bounds which of them are visible.
11697        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
11698        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
11699        let env = Gc::new(
11700            self.heap,
11701            ClosureEnv {
11702                cells,
11703                eval_scope,
11704                local_vars,
11705                local_phase,
11706            },
11707        );
11708        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
11709        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
11710        // the only thing that carries `Symbol.toStringTag`, so without it
11711        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
11712        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
11713        let proto = match function_kind {
11714            js_compile::bytecode::FunctionKind::AsyncGenerator => self
11715                .realm
11716                .async_generator_function_proto
11717                .clone()
11718                .or_else(|| self.realm.function_proto.clone().into()),
11719            js_compile::bytecode::FunctionKind::Generator => self
11720                .realm
11721                .generator_function_proto
11722                .clone()
11723                .or_else(|| self.realm.function_proto.clone().into()),
11724            js_compile::bytecode::FunctionKind::Async => self
11725                .realm
11726                .async_function_proto
11727                .clone()
11728                .or_else(|| self.realm.function_proto.clone().into()),
11729            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
11730        };
11731        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
11732        object.set_constructible(constructible);
11733        object.define(
11734            "length",
11735            Property::name_or_length(Value::Int(length as i32)),
11736        );
11737        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
11738        // that checks the own-property descriptor fails if the property is missing.
11739        object.define("name", Property::name_or_length(self.string(name)));
11740        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
11741        // when `[[Construct]]` is created, so a generator, an async function and an arrow
11742        // function have none of their own. Installing it unconditionally gave
11743        // `Array.fromAsync` (an async function) an own `prototype` property, which
11744        // `builtin.js` checks for absence.
11745        if constructible {
11746            self.install_function_prototype(&object);
11747        }
11748        Ok(Value::Object(object))
11749    }
11750
11751    // -- conversions used by the operators ----------------------------------
11752
11753    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
11754        // `+x` is `ToNumber`, which for a string parses it and for an object runs
11755        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
11756        // string, which then behaves differently in every later comparison.
11757        match value {
11758            Value::Int(_) | Value::Float(_) => Ok(value),
11759            other => Ok(Value::Float(self.to_js_number(&other)?)),
11760        }
11761    }
11762
11763    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
11764    ///
11765    /// Returns the *converted* old value and the new one, because the two callers need
11766    /// different halves: `++x` yields the new value, while `x++` yields the old one and
11767    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
11768    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
11769    /// boolean.
11770    ///
11771    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
11772    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
11773    /// a bigint algorithm then ran exactly once.
11774    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
11775        if let Value::BigInt(big) = &value {
11776            let one = crate::bigint::BigInt::from_i64(1);
11777            let next = if up { big.add(&one) } else { big.sub(&one) };
11778            return Ok((value, self.bigint(next)));
11779        }
11780        let old = self.numeric(value)?;
11781        let new = if up {
11782            increment(old.clone())
11783        } else {
11784            decrement(old.clone())
11785        };
11786        Ok((old, new))
11787    }
11788
11789    fn numeric(&mut self, value: Value) -> JsResult<Value> {
11790        // `ToNumber` on an object runs `ToPrimitive` first, which is how
11791        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
11792        // heard at all. Reading the object's own tag instead (`other.to_number()`)
11793        // turned the whole operand into `NaN` and swallowed the exception.
11794        match value {
11795            Value::Int(_) | Value::Float(_) => Ok(value),
11796            other => Ok(Value::Float(self.to_js_number(&other)?)),
11797        }
11798    }
11799
11800    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
11801    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
11802        match value {
11803            Value::BigInt(big) => Ok((**big).clone()),
11804            // The reference words this the same way for every operator, so a failing
11805            // script reads identically; the operator itself adds nothing a caller can use.
11806            _ => Err(Signal::Throw(
11807                self.make_error("TypeError", "cannot convert bigint to number"),
11808            )),
11809        }
11810    }
11811
11812    /// Arithmetic where at least one operand is a `BigInt`.
11813    ///
11814    /// The two numeric types never mix, so a bigint paired with anything else is an error
11815    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
11816    /// that the relational operators handle it separately.
11817    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11818        use Opcode::*;
11819        let a = self.bigint_operand(&left)?;
11820        let b = self.bigint_operand(&right)?;
11821        let result = match op {
11822            Add => a.add(&b),
11823            Sub => a.sub(&b),
11824            Mul => a.mul(&b),
11825            Div | Mod => {
11826                let Some((quotient, remainder)) = a.div_rem(&b) else {
11827                    return Err(Signal::Throw(
11828                        self.make_error("RangeError", "division by zero"),
11829                    ));
11830                };
11831                if op == Div { quotient } else { remainder }
11832            }
11833            Pow => {
11834                let Some(value) = a.pow(&b) else {
11835                    return Err(Signal::Throw(self.make_error(
11836                        "RangeError",
11837                        "BigInt exponent must be non-negative and not absurdly large",
11838                    )));
11839                };
11840                value
11841            }
11842            And => a.bitand(&b),
11843            Or => a.bitor(&b),
11844            Xor => a.bitxor(&b),
11845            Shl | Sar => {
11846                // A shift count is a `BigInt` here, and both directions are exact; a
11847                // negative count would be the other direction, which the spec forbids.
11848                let Some(count) = b.to_i64() else {
11849                    return Err(Signal::Throw(
11850                        self.make_error("RangeError", "BigInt shift count is too large"),
11851                    ));
11852                };
11853                if count < 0 {
11854                    return Err(Signal::Throw(self.make_error(
11855                        "RangeError",
11856                        "BigInt shift count must be non-negative",
11857                    )));
11858                }
11859                if op == Shl {
11860                    a.shl(count as u64)
11861                } else {
11862                    a.shr(count as u64)
11863                }
11864            }
11865            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
11866            _ => {
11867                return Err(Signal::Throw(self.make_error(
11868                    "TypeError",
11869                    "BigInts have no unsigned right shift, use >> instead",
11870                )));
11871            }
11872        };
11873        Ok(self.bigint(result))
11874    }
11875
11876    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
11877    ///
11878    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
11879    /// is on the mathematical values, and nothing is rounded first.
11880    /// `<`, `<=`, `>`, `>=`.
11881    ///
11882    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
11883    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
11884    /// It is a `?`-returning function for exactly that reason: an object operand can run
11885    /// script, and script can throw. The old version compared `to_number` of the raw
11886    /// values, which answered `false` for every object instead of calling `valueOf` —
11887    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
11888    /// never ran.
11889    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11890        // The hot arm first: `i < n` with both sides already integers. No conversion, no
11891        // call, nothing that can throw.
11892        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11893            let ordering = Some(left.cmp(right));
11894            return Ok(ordering_answer(op, ordering));
11895        }
11896        // Anything that can run script has to be converted first, in this order.
11897        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
11898        {
11899            (
11900                self.to_primitive(left, Hint::Number)?,
11901                self.to_primitive(right, Hint::Number)?,
11902            )
11903        } else {
11904            (left, right)
11905        };
11906        let ordering = match (&left, &right) {
11907            // The loop condition `i < n` is integer against integer, and it runs once
11908            // per iteration of every loop in every program. Without this arm it took the
11909            // `to_number` path twice, which is a `match` plus a conversion each.
11910            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
11911            (Value::String(a), Value::String(b)) => {
11912                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
11913            }
11914            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
11915            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
11916            // is true even though `2.5` has no bigint form.
11917            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
11918                let b = other.to_number();
11919                if b.is_nan() {
11920                    None
11921                } else {
11922                    compare_bigint_and_f64(a, b)
11923                }
11924            }
11925            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
11926                let a = other.to_number();
11927                if a.is_nan() {
11928                    None
11929                } else {
11930                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
11931                }
11932            }
11933            _ => left.to_number().partial_cmp(&right.to_number()),
11934        };
11935        Ok(ordering_answer(op, ordering))
11936    }
11937
11938    fn binary_add(&mut self) -> JsResult<()> {
11939        let right = self.pop();
11940        let left = self.pop();
11941        // Two integers add without any of the machinery below: no `ToPrimitive` (an
11942        // `Int` is already primitive), no string check, no bigint check, no allocation.
11943        // `x += 1` in a loop is the single most common instruction sequence in real
11944        // script, and it used to walk every one of those checks before reaching the
11945        // same `checked_add`.
11946        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11947            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
11948            return Ok(());
11949        }
11950        let left = self.primitive_of(left)?;
11951        let right = self.primitive_of(right)?;
11952        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
11953        // that check comes before the bigint one: `"" + 1n` is a string, not a
11954        // mixed-type error.
11955        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
11956            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
11957            // `TypeError`, the one place a symbol and a string do not mix.
11958            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
11959            // between a copy and a rope from their lengths, and a rope is what turns
11960            // `text += "abc"` in a loop from quadratic into linear.
11961            if let (Value::String(left), Value::String(right)) = (&left, &right) {
11962                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
11963                // reports as `InternalError: string too long`.
11964                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
11965                    return Err(Signal::Throw(
11966                        self.make_error("InternalError", "string too long"),
11967                    ));
11968                };
11969                self.push(Value::String(Gc::new(self.heap, joined)));
11970                return Ok(());
11971            }
11972            // At least one operand was not a string, so `ToString` it. This rejects a
11973            // symbol, which is the one place a symbol and a string do not mix.
11974            let left = self.checked_to_wtf8(&left)?;
11975            let right = self.checked_to_wtf8(&right)?;
11976            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
11977            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
11978            let text = left.concat(&right);
11979            self.push(self.string_wtf8(text));
11980            return Ok(());
11981        }
11982        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
11983        // not a conversion.
11984        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11985            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
11986            self.push(value);
11987            return Ok(());
11988        }
11989        let left = self.numeric(left)?;
11990        let right = self.numeric(right)?;
11991        self.push(add_numbers(left, right));
11992        Ok(())
11993    }
11994
11995    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
11996        self.to_primitive(value, Hint::Default)
11997    }
11998
11999    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12000    ///
12001    /// The order depends on the hint: the "number" order tries `valueOf` first and
12002    /// `toString` second, the "string" order the other way round, and the default
12003    /// hint uses the number order. A result that is still an object is a `TypeError`,
12004    /// because no built-in `valueOf`/`toString` returns one.
12005    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12006        let Value::Object(object) = &value else {
12007            return Ok(value);
12008        };
12009        // A Date overrides the default hint to mean "string", which is what
12010        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12011        // this, `"" + new Date()` would print the milliseconds, not the date.
12012        let hint = if hint == Hint::Default && is_date_object(self, object) {
12013            Hint::String
12014        } else {
12015            hint
12016        };
12017        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12018        // handed the hint as a string. This is the hook a Date uses for its default hint
12019        // and a script uses to take over conversion entirely.
12020        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12021        // `GetMethod`, not "is it a callable object": the property has to be read and then
12022        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12023        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12024        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12025        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12026        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12027        // callable.
12028        match self.get_property_key(object, &key)? {
12029            None | Some(Value::Undefined) | Some(Value::Null) => {}
12030            Some(Value::Object(function)) if function.is_callable() => {
12031                let hint = match hint {
12032                    Hint::String => "string",
12033                    Hint::Number => "number",
12034                    Hint::Default => "default",
12035                };
12036                let hint = self.string(hint);
12037                let result = self.call_value(
12038                    Value::Object(function),
12039                    Value::Object(object.clone()),
12040                    vec![hint],
12041                )?;
12042                if !matches!(result, Value::Object(_)) {
12043                    return Ok(result);
12044                }
12045                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12046            }
12047            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12048        }
12049        let order: [&str; 2] = match hint {
12050            Hint::String => ["toString", "valueOf"],
12051            Hint::Number | Hint::Default => ["valueOf", "toString"],
12052        };
12053        let receiver = object.clone();
12054        for method in order {
12055            if let Some(function) = self.get_property(&receiver, method)?
12056                && matches!(&function, Value::Object(object) if object.is_callable())
12057            {
12058                let result =
12059                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12060                if !matches!(result, Value::Object(_)) {
12061                    return Ok(result);
12062                }
12063            }
12064        }
12065        Err(self.type_error("cannot convert object to primitive value"))
12066    }
12067
12068    /// `ToString` with the object case going through `ToPrimitive`.
12069    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12070        if matches!(value, Value::Object(_)) {
12071            let primitive = self.to_primitive(value.clone(), Hint::String)?;
12072            return Ok(primitive.to_js_string());
12073        }
12074        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12075        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12076        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12077        // check here broke `String(Symbol())` and 45 cases that print a symbol.
12078        Ok(value.to_js_string())
12079    }
12080
12081    /// `ToString(value)`, with §7.1.19's symbol refusal.
12082    ///
12083    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12084    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12085    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12086    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12087        if matches!(value, Value::Symbol(_)) {
12088            return Err(self.type_error("cannot convert a Symbol to a string"));
12089        }
12090        if matches!(value, Value::Object(_)) {
12091            let primitive = self.to_primitive(value.clone(), Hint::String)?;
12092            if matches!(primitive, Value::Symbol(_)) {
12093                return Err(self.type_error("cannot convert a Symbol to a string"));
12094            }
12095            return Ok(primitive.to_js_string());
12096        }
12097        Ok(value.to_js_string())
12098    }
12099
12100    /// `ToString` that keeps the string's code units instead of flattening them.
12101    ///
12102    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12103    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12104    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12105        if matches!(value, Value::Symbol(_)) {
12106            return Err(Signal::Throw(
12107                self.make_error("TypeError", "cannot convert symbol to string"),
12108            ));
12109        }
12110        // An object runs `ToPrimitive` first, which may itself produce a symbol.
12111        let value = self.to_primitive(value.clone(), Hint::String)?;
12112        match value {
12113            Value::Symbol(_) => Err(Signal::Throw(
12114                self.make_error("TypeError", "cannot convert symbol to string"),
12115            )),
12116            Value::String(text) => Ok(text.wtf8().clone()),
12117            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12118        }
12119    }
12120
12121    /// `ToNumber` with the object case going through `ToPrimitive`.
12122    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12123        let value = if matches!(value, Value::Object(_)) {
12124            self.to_primitive(value.clone(), Hint::Number)?
12125        } else {
12126            value.clone()
12127        };
12128        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12129        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12130        // `NaN` to stay total, and the operators check for the bigint themselves — but
12131        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12132        // refuse, and answering `NaN` made them silently wrong instead.
12133        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12134        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12135        match value {
12136            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12137            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12138            other => Ok(other.to_number()),
12139        }
12140    }
12141
12142    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12143    /// [`ElementType::write`].
12144    ///
12145    /// This is separated from the write because both conversions are observable script —
12146    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12147    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12148    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12149    /// setters, and a plain `a[i] = v`.
12150    pub(crate) fn element_value(
12151        &mut self,
12152        element: crate::builtins::typedarray::ElementType,
12153        value: Value,
12154    ) -> JsResult<Value> {
12155        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12156        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12157        let primitive = match &value {
12158            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12159            _ => value,
12160        };
12161        if element.is_bigint() {
12162            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12163            Ok(Value::BigInt(Gc::new(self.heap, big)))
12164        } else {
12165            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12166            Ok(Value::Float(self.to_js_number(&primitive)?))
12167        }
12168    }
12169
12170    /// `ToPropertyKey`: what a computed member access uses as its key.
12171    ///
12172    /// A symbol is returned as itself, never stringified — that is what keeps
12173    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12174    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12175        match value {
12176            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12177            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12178            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12179            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12180            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12181                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12182                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12183                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12184                    other.to_js_string(),
12185                ))),
12186            },
12187            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12188        }
12189    }
12190
12191    /// `ToPropertyKey` for the callers that can only use a string key.
12192    ///
12193    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12194    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12195    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12196    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12197    /// program continues with a value nobody asked for.
12198    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12199        use crate::value::Wtf8;
12200        Ok(match value {
12201            // A string key keeps its code units. Going through a lossy `String` would make
12202            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12203            Value::String(text) => text.wtf8().clone(),
12204            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12205            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12206            // falling back to its `ToString` would print `[object Object]`.
12207            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12208                Value::String(text) => text.wtf8().clone(),
12209                other => Wtf8::new(other.to_js_string()),
12210            },
12211            other => Wtf8::new(other.to_js_string()),
12212        })
12213    }
12214
12215    // -- object operations used by instructions -----------------------------
12216
12217    /// Read `object[key]`, returning `undefined` when the property is missing.
12218    ///
12219    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12220    /// primitive (looking through its prototype) as well as an object — which is what
12221    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
12222    /// argument needs too.
12223    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
12224        self.read_field_key(object, &PropertyKey::from(key))
12225    }
12226
12227    /// [`Interp::read_field`] with a key that may be a symbol.
12228    ///
12229    /// A symbol key never reaches the string shortcuts: a string's `length` and its
12230    /// indices are string properties, and a symbol named `length` is a different
12231    /// property that a string primitive cannot have.
12232    /// [`Interp::read_field_key`], with an inline cache in front of it.
12233    ///
12234    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
12235    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
12236    /// without this the engine walked the chain and compared ~40 property names on each
12237    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
12238    ///
12239    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
12240    /// missing property. Those answers depend on running code or on state the guard below
12241    /// does not cover, and a wrong answer here is far more expensive than a lookup.
12242    ///
12243    /// A hit is re-validated against the *whole* walked chain, not just the level that
12244    /// answered: the receiver and every prototype down to that level must still be the same
12245    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
12246    /// property-table *lengths* — which is what catches a property appearing on an
12247    /// intermediate prototype and shadowing the cached one.
12248    pub fn read_field_cached(
12249        &mut self,
12250        object: &Value,
12251        key: &PropertyKey,
12252        slot: usize,
12253    ) -> JsResult<Value> {
12254        let index = Self::field_cache_slot(object, key, slot);
12255        let Value::Object(target) = object else {
12256            return self.read_field_key(object, key);
12257        };
12258        if target.proxy_state().is_some() {
12259            return self.read_field_key(object, key);
12260        }
12261        if let Some(cached) = &self.field_cache[index]
12262            && cached.key == *key
12263            && let Some(value) = Self::cached_hit(target, cached)
12264        {
12265            return Ok(value);
12266        }
12267        let value = self.read_field_key(object, key)?;
12268        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
12269        Ok(value)
12270    }
12271
12272    /// Whether a cache entry still describes this lookup, and if so the value.
12273    ///
12274    /// The guard is the whole point of the entry: identity plus property-table length for
12275    /// every level walked. Re-checked per level rather than once at the receiving end,
12276    /// because a shadowing property can appear anywhere along the chain.
12277    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
12278        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
12279        // starts with: a clone is a reference-count bump and a drop, and for
12280        // `property:monomorphic` every single hit takes only this arm.
12281        let (weak, len) = cached.chain[0].as_ref()?;
12282        if !target.upgrades_to(weak) {
12283            return None;
12284        }
12285        if cached.level == 0 {
12286            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
12287            return target.cached_property_at(cached.index, &cached.key, *len);
12288        }
12289        if target.props_len() != *len {
12290            return None;
12291        }
12292        let mut level = 1;
12293        let mut current = target.proto()?;
12294        loop {
12295            let (weak, len) = cached.chain[level].as_ref()?;
12296            if !current.upgrades_to(weak) || current.props_len() != *len {
12297                return None;
12298            }
12299            if level == cached.level as usize {
12300                // The level that answered: the value is only reusable while the key is
12301                // still there and still a plain data property.
12302                return current.cached_data_property(cached.index, &cached.key);
12303            }
12304            current = current.proto()?;
12305            level += 1;
12306        }
12307    }
12308
12309    /// Build a cache entry for a lookup that just went through the slow path.
12310    ///
12311    /// Records the chain only when the answer came from a plain data property at a level
12312    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
12313    /// costs the next lookup the walk it would have cost anyway.
12314    fn record_field_lookup(
12315        target: &Gc<JsObject>,
12316        key: &PropertyKey,
12317        _value: Value,
12318    ) -> Option<FieldCache> {
12319        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
12320            [None, None, None];
12321        let mut current = target.clone();
12322        for level in 0..MAX_CACHED_CHAIN {
12323            chain[level] = Some((current.downgrade(), current.props_len()));
12324            if let Some((found, _)) = current.own_property_index(key) {
12325                // `own_property_index` declines an accessor and a hole, which is exactly
12326                // the set that must not be cached.
12327                return Some(FieldCache {
12328                    key: key.clone(),
12329                    index: found,
12330                    level: level as u8,
12331                    chain,
12332                });
12333            }
12334            current = current.proto()?;
12335        }
12336        None
12337    }
12338
12339    /// Which cache slot a lookup uses.
12340    ///
12341    /// Mixes the object's address, the name and the site, so that two properties of one
12342    /// object, and one property of two objects, land in different slots — which is what lets
12343    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
12344    /// other iteration.
12345    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
12346        let mut hash = match object {
12347            Value::Object(object) => object.address(),
12348            _ => 0,
12349        };
12350        hash = hash
12351            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
12352            .rotate_left(17)
12353            .wrapping_add(key.hash_code());
12354        hash = hash.wrapping_add(site.wrapping_mul(31));
12355        // The table is a power of two, so the low bits are the slot.
12356        hash & (FIELD_CACHE_SLOTS - 1)
12357    }
12358
12359    /// Read `key` from `object`, without the inline cache.
12360    ///
12361    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
12362    /// prototype chain, while the cached form answers an own data property from memory.
12363    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
12364        let text = key.as_str().unwrap_or("");
12365        let Value::Object(object) = object else {
12366            // Reading a property of `undefined`/`null` is the classic TypeError.
12367            if object.is_nullish() {
12368                return Err(Signal::Throw(self.make_error(
12369                    "TypeError",
12370                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
12371                )));
12372            }
12373            // A string has `length` and index access without being boxed.
12374            if let Value::String(value) = object {
12375                if text == "length" {
12376                    return Ok(Value::Int(value.utf16_len() as i32));
12377                }
12378                if let Some(index) = array_index(text) {
12379                    return Ok(match value.wtf8().unit_at(index as usize) {
12380                        Some(unit) => self.string_wtf8(unit),
12381                        None => Value::Undefined,
12382                    });
12383                }
12384            }
12385            // A property of a primitive is looked up on its prototype: this is what
12386            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
12387            let prototype = match object {
12388                Value::String(_) => self.realm.string_proto.clone(),
12389                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12390                Value::Bool(_) => self.realm.boolean_proto.clone(),
12391                // A symbol's methods live on `Symbol.prototype`, reached the same way —
12392                // `sym.description` reads through the prototype, not off the symbol.
12393                Value::Symbol(_) => self.realm.symbol_proto.clone(),
12394                // …and a bigint's on `BigInt.prototype`, which is how
12395                // `(255n).toString(16)` reaches its method.
12396                Value::BigInt(_) => self.realm.bigint_proto.clone(),
12397                _ => None,
12398            };
12399            if let Some(prototype) = prototype
12400                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
12401            {
12402                return Ok(value);
12403            }
12404            return Ok(Value::Undefined);
12405        };
12406        Ok(self
12407            .get_property_key(object, key)?
12408            .unwrap_or(Value::Undefined))
12409    }
12410
12411    /// The `#name` a private symbol stands for, for error messages.
12412    ///
12413    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12414    /// was made from.
12415    fn private_name(symbol: &Value) -> Option<String> {
12416        match symbol {
12417            Value::Symbol(symbol) if symbol.is_private() => Some(
12418                symbol
12419                    .description()
12420                    .map(|text| text.to_string())
12421                    .unwrap_or_default(),
12422            ),
12423            _ => None,
12424        }
12425    }
12426
12427    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12428    ///
12429    /// Every private-field opcode takes the symbol the class stored in its own scope; a
12430    /// non-symbol here would be a compiler bug, and the reference guards it with
12431    /// `JS_ThrowTypeErrorNotASymbol`.
12432    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12433        match symbol {
12434            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12435            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12436        }
12437    }
12438
12439    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12440    ///
12441    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12442    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12443    /// would hit if the parser did not reject it first.
12444    fn define_private_field(
12445        &mut self,
12446        object: &Value,
12447        symbol: &Value,
12448        value: Value,
12449    ) -> JsResult<()> {
12450        let key = self.private_key(symbol)?;
12451        let Some(target) = object.as_object() else {
12452            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12453        };
12454        if !target.is_extensible() {
12455            return Err(Signal::Throw(
12456                self.make_error("TypeError", "object is not extensible"),
12457            ));
12458        }
12459        if target.own_property_key(&key).is_some() {
12460            let name = Self::private_name(symbol).unwrap_or_default();
12461            return Err(Signal::Throw(self.make_error(
12462                "TypeError",
12463                &format!("private class field '{name}' already exists"),
12464            )));
12465        }
12466        target.define_data_key(&key, value);
12467        Ok(())
12468    }
12469
12470    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12471    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12472        let key = self.private_key(symbol)?;
12473        let Some(target) = object.as_object() else {
12474            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12475        };
12476        match target.own_property_key(&key) {
12477            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12478            None => {
12479                let name = Self::private_name(symbol).unwrap_or_default();
12480                Err(Signal::Throw(self.make_error(
12481                    "TypeError",
12482                    &format!("private class field '{name}' does not exist"),
12483                )))
12484            }
12485        }
12486    }
12487
12488    /// `JS_SetPrivateField`: the store half of the same rule.
12489    fn write_private_field(
12490        &mut self,
12491        object: &Value,
12492        symbol: &Value,
12493        value: Value,
12494    ) -> JsResult<()> {
12495        let key = self.private_key(symbol)?;
12496        let Some(target) = object.as_object() else {
12497            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12498        };
12499        if target.write_value_key(&key, value) {
12500            return Ok(());
12501        }
12502        let name = Self::private_name(symbol).unwrap_or_default();
12503        Err(Signal::Throw(self.make_error(
12504            "TypeError",
12505            &format!("private class field '{name}' does not exist"),
12506        )))
12507    }
12508
12509    /// The `in` half: does `object` have this private field?
12510    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12511    ///
12512    /// The symbol is created once per class — the first `add_brand` on a given home object
12513    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12514    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12515    /// emit for the *instance* brand passes null because all it wants is the symbol.
12516    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12517        let Some(home_object) = home.as_object() else {
12518            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12519        };
12520        let symbol = match home_object.private_brand() {
12521            Some(symbol) => symbol,
12522            None => {
12523                let symbol = Gc::new(
12524                    self.heap,
12525                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
12526                );
12527                home_object.set_private_brand(symbol.clone());
12528                symbol
12529            }
12530        };
12531        let Some(target) = object.as_object() else {
12532            // Not an object: nothing to brand. The reference does the same, and `undefined`
12533            // here would otherwise turn a field initialiser into a TypeError.
12534            return Ok(());
12535        };
12536        if !target.is_extensible() {
12537            return Err(Signal::Throw(
12538                self.make_error("TypeError", "object is not extensible"),
12539            ));
12540        }
12541        if target.carries_brand(&symbol) {
12542            return Err(Signal::Throw(
12543                self.make_error("TypeError", "private method is already present"),
12544            ));
12545        }
12546        target.add_brand(symbol);
12547        Ok(())
12548    }
12549
12550    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12551    ///
12552    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12553    /// decides whether to throw.
12554    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12555        let Some(function) = function.as_object() else {
12556            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12557        };
12558        let Some(home) = function.home_object() else {
12559            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12560        };
12561        let Some(brand) = home.private_brand() else {
12562            return Err(Signal::Throw(
12563                self.make_error("TypeError", "expecting <brand> private field"),
12564            ));
12565        };
12566        Ok(object.carries_brand(&brand))
12567    }
12568
12569    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12570        let Value::Object(object) = object else {
12571            return Err(Signal::Throw(self.make_error(
12572                "TypeError",
12573                &format!("cannot set property '{key}' of {}", object.to_js_string()),
12574            )));
12575        };
12576        // The write half of the property inline cache, in effect: an own, writable,
12577        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12578        // decide — no prototype walk (an own property shadows the chain before a setter
12579        // there could matter), no extensibility check (the object already has the key),
12580        // and no `[[DefineOwnProperty]]`.
12581        //
12582        // `this.value = …` inside a method is the whole write side of
12583        // `property:method-call`, and it was reaching `set_property_with_key` with its
12584        // proxy test, its typed-array test, its array-index test and finally a linear
12585        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12586        //
12587        // Every disqualifier is checked here: a proxy traps the set, an array index and
12588        // `length` live outside the property table, and a typed array's element is stored
12589        // through its view's element type.
12590        if object.proxy_state().is_none()
12591            && !object.is_array()
12592            && object.typed_array_element_type().is_none()
12593            && object.write_value_key(key, value.clone())
12594        {
12595            return Ok(());
12596        }
12597        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12598        let on_failure = if self.frame().code.code.strict {
12599            DeleteFailure::Throw
12600        } else {
12601            DeleteFailure::Ignore
12602        };
12603        self.set_property_with_key(object, key, value, on_failure)
12604    }
12605
12606    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12607    ///
12608    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12609    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12610    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12611    /// `Number.parseInt(sym)` — so those callers use this instead.
12612    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12613        if matches!(value, Value::Symbol(_)) {
12614            return Err(Signal::Throw(
12615                self.make_error("TypeError", "cannot convert symbol to string"),
12616            ));
12617        }
12618        // An object runs `ToPrimitive` first, which may itself produce a symbol —
12619        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12620        let value = self.to_primitive(value.clone(), Hint::String)?;
12621        if matches!(value, Value::Symbol(_)) {
12622            return Err(Signal::Throw(
12623                self.make_error("TypeError", "cannot convert symbol to string"),
12624            ));
12625        }
12626        Ok(value.to_js_string())
12627    }
12628
12629    /// `ToPropertyKey` for a builtin that takes a key argument.
12630    ///
12631    /// Fallible: a key whose `toString` throws has to propagate that error, both for
12632    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12633    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12634    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12635    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12636        self.propkey(value)
12637    }
12638
12639    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12640    ///
12641    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12642    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12643    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12644    /// `RangeError` — and why this cannot be a plain `ToNumber`.
12645    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
12646        let number = match value {
12647            Value::Int(number) => *number as f64,
12648            Value::Float(number) => *number,
12649            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
12650            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
12651            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
12652            // reference answers 0.
12653            Value::Null | Value::Bool(_) => value.to_number(),
12654            _ => {
12655                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
12656                match primitive {
12657                    Value::Int(number) => number as f64,
12658                    Value::Float(number) => number,
12659                    other => {
12660                        // `ToString` then `ToNumber`, so a string length goes through the
12661                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
12662                        // `Value::to_number` on the string already implements exactly that.
12663                        let text = self.to_js_string(&other)?;
12664                        crate::value::string_to_number(&text)
12665                    }
12666                }
12667            }
12668        };
12669        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
12670        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
12671        // is a `RangeError`, not `0`.
12672        if !number.is_finite()
12673            || number.fract() != 0.0
12674            || !(0.0..=u32::MAX as f64).contains(&number)
12675        {
12676            return Err(self.range_error("invalid array length"));
12677        }
12678        Ok(number as u32)
12679    }
12680
12681    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
12682    /// `Object.getOwnPropertySymbols` put in their result array.
12683    pub fn key_value(&self, key: &PropertyKey) -> Value {
12684        match key {
12685            PropertyKey::String(text) => self.string_wtf8(text.clone()),
12686            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12687        }
12688    }
12689
12690    /// Fill in a String exotic object: `_value`, `length` and the index properties.
12691    ///
12692    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
12693    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
12694    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
12695    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
12696    /// the two paths had drifted; this is the one both now use.
12697    ///
12698    /// The indices are *code units*, so an astral character occupies two of them — the
12699    /// same rule `s.length` and `s[i]` follow.
12700    /// Give an already-created object the internal slot that makes it a wrapper of
12701    /// `value`, so the primitive's prototype methods work on it.
12702    ///
12703    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
12704    /// which are wrappers of their own type holding the empty value.
12705    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
12706        self.internal_set(object, "_value", value);
12707    }
12708
12709    pub(crate) fn init_string_wrapper(
12710        &mut self,
12711        object: &Gc<JsObject>,
12712        text: &Gc<crate::value::JsString>,
12713    ) {
12714        object.define(
12715            "length",
12716            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
12717        );
12718        for index in 0..text.utf16_len() {
12719            if let Some(unit) = text.wtf8().unit_at(index) {
12720                object.define(
12721                    &index.to_string(),
12722                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
12723                    Property::with_attributes(self.string_wtf8(unit), false, true),
12724                );
12725            }
12726        }
12727        object.define_key(
12728            &self.internal_slot("_value"),
12729            Property::with_attributes(Value::String(text.clone()), false, false),
12730        );
12731    }
12732
12733    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
12734    ///
12735    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
12736    /// throws. The wrapper carries its primitive in `_value` — the same slot
12737    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
12738    /// on a boxed value no constructor ever built.
12739    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12740        let (prototype, primitive) = match value {
12741            Value::Object(object) => return Ok(object.clone()),
12742            Value::String(text) => {
12743                let object = self.new_object(self.realm.string_proto.clone());
12744                self.init_string_wrapper(&object, text);
12745                return Ok(object);
12746            }
12747            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
12748            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
12749            // A symbol and a bigint box into wrappers whose methods live on
12750            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
12751            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
12752            // branch below instead produced an object with *no* prototype, so those
12753            // methods were unreachable on a box.
12754            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
12755            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
12756            Value::Undefined | Value::Null => {
12757                return Err(Signal::Throw(self.make_error(
12758                    "TypeError",
12759                    &format!("cannot convert {} to object", value.to_js_string()),
12760                )));
12761            }
12762            _ => (None, value.clone()),
12763        };
12764        let object = self.new_object(prototype);
12765        self.internal_set(&object, "_value", primitive);
12766        Ok(object)
12767    }
12768
12769    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
12770    ///
12771    /// Split out for a reader that has to create the object *before* it knows what it wraps:
12772    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
12773    /// written before its primitive, so the placeholder has to exist first and be filled in
12774    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
12775    /// than a second in the deserialiser.
12776    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
12777        let prototype = match value {
12778            Value::String(_) => self.realm.string_proto.clone(),
12779            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12780            Value::Bool(_) => self.realm.boolean_proto.clone(),
12781            Value::Symbol(_) => self.realm.symbol_proto.clone(),
12782            Value::BigInt(_) => self.realm.bigint_proto.clone(),
12783            _ => {
12784                return Err(Signal::Throw(self.make_error(
12785                    "TypeError",
12786                    &format!("cannot box {}", value.to_js_string()),
12787                )));
12788            }
12789        };
12790        object.set_proto(prototype);
12791        if let Value::String(text) = value {
12792            self.init_string_wrapper(object, text);
12793            return Ok(());
12794        }
12795        self.internal_set(object, "_value", value.clone());
12796        Ok(())
12797    }
12798
12799    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
12800    ///
12801    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
12802    /// through the `Symbol` function object, so the registry is reachable as a method rather
12803    /// than only from `builtins::symbol`.
12804    pub fn symbol_for(&mut self, key: &str) -> Value {
12805        if let Some(existing) = self.realm.symbol_registry.get(key) {
12806            return existing.clone();
12807        }
12808        let symbol = crate::builtins::symbol::symbol_value(
12809            self,
12810            crate::value::JsSymbol::registered(key.to_string()),
12811        );
12812        self.realm
12813            .symbol_registry
12814            .insert(key.to_string(), symbol.clone());
12815        symbol
12816    }
12817
12818    /// `a == b`, the coercing comparison.
12819    ///
12820    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
12821    /// which is what makes `[] == ""` true: `[]` becomes `""` via
12822    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
12823    /// because the conversion is allowed to call script code, so the two primitive
12824    /// operands are handed back to it.
12825    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
12826        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
12827            return Ok(left.loose_equals(&right));
12828        }
12829        // `null == undefined` holds even though neither is an object.
12830        if matches!(left, Value::Undefined | Value::Null)
12831            && matches!(right, Value::Undefined | Value::Null)
12832        {
12833            return Ok(true);
12834        }
12835        if matches!(left, Value::Undefined | Value::Null)
12836            || matches!(right, Value::Undefined | Value::Null)
12837        {
12838            return Ok(false);
12839        }
12840        // Two objects compare by identity. Only an object *against a primitive* is
12841        // converted, which is why `{} == {}` is false while `[] == ""` is true.
12842        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
12843            return Ok(a.ptr_eq(b));
12844        }
12845        let left = self.to_primitive(left, Hint::Default)?;
12846        let right = self.to_primitive(right, Hint::Default)?;
12847        Ok(left.loose_equals(&right))
12848    }
12849
12850    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
12851        let Value::Object(object) = object else {
12852            return Err(Signal::Throw(
12853                self.make_error("TypeError", "cannot use 'in' on a non-object"),
12854            ));
12855        };
12856        let key = self.propkey(key)?;
12857        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
12858        // trap. One implementation, so an array's derived `length` and its inherited holes
12859        // cannot be right in one caller and wrong in another.
12860        self.has_own_or_inherited(object, &key)
12861    }
12862
12863    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
12864    ///
12865    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
12866    /// whole reason the operator is a hook rather than a prototype walk.
12867    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12868        if let Value::Object(function) = constructor {
12869            let key = self.realm.well_known_key(WellKnown::HasInstance);
12870            let method = self.get_property_key(function, &key)?;
12871            if let Some(method) = method
12872                && !matches!(method, Value::Undefined)
12873            {
12874                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
12875                return Ok(answer.to_boolean());
12876            }
12877        }
12878        self.instance_of(object, constructor)
12879    }
12880
12881    /// `OrdinaryHasInstance`: the prototype walk on its own.
12882    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12883        self.instance_of(object, constructor)
12884    }
12885
12886    /// `IsArray`: an array, or a proxy whose target is one.
12887    ///
12888    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
12889    /// makes `Array.isArray(new Proxy([], {}))` true.
12890    pub fn is_array_value(&self, value: &Value) -> bool {
12891        match value {
12892            Value::Object(object) => {
12893                if let Some(state) = object.proxy_state() {
12894                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
12895                }
12896                object.is_array()
12897            }
12898            _ => false,
12899        }
12900    }
12901
12902    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
12903    ///
12904    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
12905    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
12906    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
12907    /// see [`Interp::enqueue_job_function`].
12908    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
12909        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
12910        // the handler is reported rather than lost — the same reason a `then` reaction needs a
12911        // promise to settle.
12912        let promise = self.new_promise();
12913        self.fulfill_promise(&promise, Value::Undefined);
12914        self.jobs.push_back(Job::Reaction {
12915            handler: Some(function),
12916            argument: Value::Undefined,
12917            rejected: false,
12918            promise,
12919        });
12920        Ok(())
12921    }
12922
12923    /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
12924    ///
12925    /// Four of its steps were missing or wrong, and each one is a test262 case in
12926    /// `Function/prototype/Symbol.hasInstance/`:
12927    ///
12928    /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
12929    /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
12930    ///   `[[BoundThis]]` standing in for the object when that is an object), which is why
12931    ///   `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
12932    ///   `prototype` of its own, so without this step the walk below gives `false`;
12933    /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
12934    /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
12935    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12936        let Value::Object(function) = constructor else {
12937            return Ok(false);
12938        };
12939        if !function.is_callable() {
12940            return Ok(false);
12941        }
12942        // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
12943        // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
12944        // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
12945        if let Some((target, this)) = function.bound_target_and_this() {
12946            let object = if this.as_object().is_some() {
12947                this
12948            } else {
12949                object.clone()
12950            };
12951            return self.instance_of(&object, &target);
12952        }
12953        let Value::Object(target) = object else {
12954            return Ok(false);
12955        };
12956        let prototype = self.get_property(function, "prototype")?;
12957        let Some(Value::Object(prototype)) = prototype else {
12958            return Err(Signal::Throw(self.make_error(
12959                "TypeError",
12960                "function has non-object prototype in instanceof check",
12961            )));
12962        };
12963        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
12964        // which is also what makes `proxyOfInstance instanceof C` work.
12965        let mut current = Some(target.clone());
12966        while let Some(object) = current {
12967            if object.ptr_eq(&prototype) {
12968                return Ok(true);
12969            }
12970            current = self.object_prototype_of(&object)?;
12971        }
12972        Ok(false)
12973    }
12974
12975    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
12976    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
12977        if let Some(proto) = self.proxy_get_prototype_of(object)? {
12978            return Ok(proto);
12979        }
12980        if let Some(exotic) = object.exotic()
12981            && let Some(proto) = exotic.get_prototype(self, object)?
12982        {
12983            return Ok(proto);
12984        }
12985        Ok(object.proto())
12986    }
12987
12988    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
12989    pub fn object_set_prototype_of(
12990        &mut self,
12991        object: &Gc<JsObject>,
12992        proto: Option<Gc<JsObject>>,
12993    ) -> JsResult<bool> {
12994        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
12995            return Ok(answer);
12996        }
12997        if let Some(exotic) = object.exotic()
12998            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
12999        {
13000            return Ok(answer);
13001        }
13002        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13003        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13004        // inheriting from itself, which every later prototype walk then had to defend
13005        // against — and `Reflect.setPrototypeOf` reported success for an operation the
13006        // language says is impossible.
13007        if let Some(proto) = &proto {
13008            let mut current = Some(proto.clone());
13009            let mut guard = 0;
13010            while let Some(node) = current {
13011                if node.ptr_eq(object) {
13012                    return Err(Signal::Throw(
13013                        self.make_error("TypeError", "circular prototype chain"),
13014                    ));
13015                }
13016                guard += 1;
13017                if guard > 1000 {
13018                    break;
13019                }
13020                current = node.proto();
13021            }
13022        }
13023        // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13024        // re-setting it to the *same* one is a no-op `true`. Missing this made
13025        // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13026        // actually reparent the object — and it is what
13027        // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13028        // forwarding path has nothing else left to refuse it.
13029        if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13030            return Ok(false);
13031        }
13032        object.set_proto(proto);
13033        Ok(true)
13034    }
13035
13036    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13037    ///
13038    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13039    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13040    /// already one.
13041    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13042        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
13043        // (§10.4.5.2 step 1.b) — the prototype chain is *not* consulted for a canonical
13044        // numeric index. That is observable twice over: a view that has been resized out
13045        // of bounds has no indices, so `2 in view` must then be `false` even when
13046        // `Object.getPrototypeOf(view)[2]` exists, and a key like `"-1"` or `"1.5"` is
13047        // canonical-numeric-but-invalid, so `in` answers `false` where an ordinary
13048        // lookup would have found `TypedArray.prototype["1.5"]`. A proxy is excluded
13049        // because it has no `[[ViewedArrayBuffer]]` slot of its own.
13050        if object.typed_array_parts().is_some()
13051            && object.proxy_state().is_none()
13052            && let Some(numeric) = canonical_numeric_index(key)
13053        {
13054            return Ok(typed_array_index_is_valid(object, numeric));
13055        }
13056        let mut current = Some(object.clone());
13057        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
13058        let mut guard = 0;
13059        while let Some(node) = current {
13060            guard += 1;
13061            if guard > 1000 {
13062                return Ok(false);
13063            }
13064            let own = self.object_get_own_property(&node, key)?;
13065            if own.is_some() {
13066                return Ok(true);
13067            }
13068            current = self.object_prototype_of(&node)?;
13069        }
13070        Ok(false)
13071    }
13072
13073    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13074    ///
13075    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13076    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13077    /// boolean as well, and it needs the receiver to be the one the caller named.
13078    pub fn set_property_with_key_receiver(
13079        &mut self,
13080        object: &Gc<JsObject>,
13081        key: &PropertyKey,
13082        value: Value,
13083        receiver: Option<&Value>,
13084        on_failure: DeleteFailure,
13085    ) -> JsResult<bool> {
13086        let receiver = receiver
13087            .cloned()
13088            .unwrap_or_else(|| Value::Object(object.clone()));
13089        if object.proxy_state().is_some() {
13090            return match self.proxy_set(object, key, value, &receiver)? {
13091                Some(accepted) => Ok(accepted),
13092                None => Ok(true),
13093            };
13094        }
13095        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13096        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13097        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13098        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13099        //
13100        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13101        //
13102        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13103        // * an *invalid* index with a different receiver answers `true` and does nothing,
13104        //   not even converting `V` (`valueOfCalls` stays 0);
13105        // * a valid index with a different receiver falls through to
13106        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13107        //   value lands on the **receiver**, unconverted, and can be refused by a
13108        //   non-extensible receiver, an accessor, or a read-only index there.
13109        //
13110        // The last one used to write into the view itself, which left `target[0]` changed
13111        // and `receiver[0]` untouched — backwards.
13112        if object.typed_array_element_type().is_some()
13113            && let Some(numeric) = canonical_numeric_index(key)
13114        {
13115            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13116            if same {
13117                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13118                return Ok(true);
13119            }
13120            if !typed_array_index_is_valid(object, numeric) {
13121                return Ok(true);
13122            }
13123            let Some(receiver) = receiver.as_object().cloned() else {
13124                return Ok(false);
13125            };
13126            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13127                if existing.is_accessor() || !existing.writable {
13128                    return Ok(false);
13129                }
13130                let property = Property {
13131                    value: Some(value),
13132                    ..existing
13133                };
13134                return self.object_define_own_property(&receiver, key, property);
13135            }
13136            return self.object_define_own_property(&receiver, key, Property::data(value));
13137        }
13138        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13139        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13140        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13141        // `Reflect.set` to *report* the refusal instead of raising.
13142        //
13143        // A receiver that is not the object turns the whole operation into
13144        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13145        // `[[Set]]` rather than a lookup — that is what makes
13146        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13147        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13148        // writes to `object`, so it cannot express that and is only used when the two are
13149        // the same.
13150        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13151        if !same {
13152            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13153        }
13154        // Same receiver: the plain path below writes into `object`, which is right, but it
13155        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13156        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13157        if let Some(existing) = self.object_get_own_property(object, key)? {
13158            if existing.is_accessor() {
13159                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13160                    Some(setter) => {
13161                        self.call_value(setter, receiver, vec![value])?;
13162                        Ok(true)
13163                    }
13164                    None => Ok(false),
13165                };
13166            }
13167            if !existing.writable {
13168                return Ok(false);
13169            }
13170        }
13171        // Otherwise it is an ordinary create-or-write into `object` itself.
13172        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13173        Ok(true)
13174    }
13175
13176    /// `[[IsExtensible]]`, with the proxy trap when there is one.
13177    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13178        if let Some(answer) = self.proxy_is_extensible(object)? {
13179            return Ok(answer);
13180        }
13181        if let Some(exotic) = object.exotic()
13182            && let Some(answer) = exotic.is_extensible(self, object)?
13183        {
13184            return Ok(answer);
13185        }
13186        Ok(object.is_extensible())
13187    }
13188
13189    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13190    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13191        if let Some(answer) = self.proxy_prevent_extensions(object)? {
13192            return Ok(answer);
13193        }
13194        if let Some(exotic) = object.exotic()
13195            && let Some(answer) = exotic.prevent_extensions(self, object)?
13196        {
13197            return Ok(answer);
13198        }
13199        object.set_extensible(false);
13200        Ok(true)
13201    }
13202
13203    fn copy_properties(
13204        &mut self,
13205        target: &Value,
13206        source: &Value,
13207        exclusion: &Value,
13208    ) -> JsResult<()> {
13209        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
13210        // does contribute: its index properties are own, enumerable and writable, which
13211        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
13212        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
13213        // is a no-op.
13214        let Some(target) = target.as_object() else {
13215            return Ok(());
13216        };
13217        let source_object = match source {
13218            Value::Object(object) => object.clone(),
13219            Value::String(text) => {
13220                // Untaken keys are the string's indices, which are code units.
13221                for index in 0..text.utf16_len() {
13222                    if let Some(unit) = text.wtf8().unit_at(index) {
13223                        target.define_data(&index.to_string(), self.string_wtf8(unit));
13224                    }
13225                }
13226                return Ok(());
13227            }
13228            _ => return Ok(()),
13229        };
13230        // An object *rest* element passes the keys already taken by the literal part as
13231        // an array of strings; a spread passes `null`, which excludes nothing. Only the
13232        // string keys of the exclusion array are meaningful, so an array is read by its
13233        // elements rather than by its own property names.
13234        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
13235        if let Value::Object(list) = exclusion
13236            && let Some(length) = list.array_length()
13237        {
13238            for index in 0..length {
13239                if let Some(value) = list.array_get(index) {
13240                    excluded.push(self.propkey_of(&value)?);
13241                }
13242            }
13243        }
13244        let source = &source_object;
13245        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
13246        // Reading the property table directly made every spread of a proxy empty.
13247        let keys = self.object_own_property_keys(source)?;
13248        for as_key in keys {
13249            if as_key.is_symbol() {
13250                // A spread copies string-keyed properties only.
13251                continue;
13252            }
13253            if excluded.contains(&crate::value::Wtf8::new(
13254                as_key.as_str().unwrap_or_default(),
13255            )) {
13256                continue;
13257            }
13258            let enumerable = self
13259                .object_get_own_property(source, &as_key)?
13260                .is_some_and(|property| property.enumerable);
13261            if !enumerable {
13262                continue;
13263            }
13264            let value = self
13265                .get_property_key(source, &as_key)?
13266                .unwrap_or(Value::Undefined);
13267            target.define_data_key(&as_key, value);
13268        }
13269        Ok(())
13270    }
13271
13272    // -- iteration ---------------------------------------------------------
13273
13274    /// One object's own keys in enumeration order: array indices ascending, then the
13275    /// rest in insertion order.
13276    ///
13277    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
13278    /// whether the key is enumerable, which the caller resolves per key because an
13279    /// array's elements are not in the same store as its named properties.
13280    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
13281        // An index can arrive twice, once from the array's element store and once from
13282        // its property map, so the numeric keys go through a map that keeps the
13283        // enumerable answer if either source gave one.
13284        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
13285        for (key, enumerable) in &own {
13286            if let Some(index) = key.as_str().and_then(array_index) {
13287                let entry = numeric.entry(index).or_insert(false);
13288                *entry = *entry || *enumerable;
13289            }
13290        }
13291        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
13292            .into_iter()
13293            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
13294            .collect();
13295        ordered.extend(
13296            own.into_iter()
13297                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
13298        );
13299        ordered
13300    }
13301
13302    /// Build the key list a `for-in` loop walks.
13303    ///
13304    /// The order is the specification's: own properties before inherited ones, and
13305    /// within one object the integer-like keys in ascending numeric order ahead of the
13306    /// string keys in insertion order. A shadowed key only appears once, and a key that
13307    /// is a non-enumerable own property anywhere nearer is skipped entirely.
13308    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13309        let record = self.new_object(None);
13310        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
13311        // A proxy supplies its own key list, and — the reason this is not just another
13312        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
13313        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
13314        // descriptor there.
13315        if let Value::Object(object) = value
13316            && object.proxy_state().is_some()
13317        {
13318            let own = self
13319                .proxy_own_keys(object)?
13320                .unwrap_or_else(|| object.own_property_keys());
13321            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
13322            let mut numeric: Vec<u32> = Vec::new();
13323            let mut rest: Vec<PropertyKey> = Vec::new();
13324            for key in own {
13325                match key.as_str().and_then(array_index) {
13326                    Some(index) => numeric.push(index),
13327                    None => rest.push(key),
13328                }
13329            }
13330            numeric.sort_unstable();
13331            ordered.extend(
13332                numeric
13333                    .into_iter()
13334                    .map(|index| PropertyKey::from(index.to_string())),
13335            );
13336            ordered.extend(rest);
13337            for (index, key) in ordered.into_iter().enumerate() {
13338                record.define_data(&index.to_string(), self.key_value(&key));
13339            }
13340            record.define_data("__index", Value::Int(0));
13341            // The mark that makes `for_in_advance` re-ask the proxy per key.
13342            record.define_data("__proxy", Value::Object(object.clone()));
13343            return Ok(record);
13344        }
13345        if let Value::Object(object) = value {
13346            let mut chain = vec![object.clone()];
13347            chain.extend(object.chain());
13348            // Every own string key the walk has seen, enumerable or not. A
13349            // non-enumerable own property still hides a same-named enumerable one
13350            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
13351            // keeps `x` out of the loop even when the prototype has one.
13352            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
13353            for object in chain {
13354                let mut own: Vec<(crate::value::Wtf8, bool)> = object
13355                    .own_property_keys()
13356                    .iter()
13357                    .filter_map(|key| key.as_wtf8().cloned())
13358                    .map(|key| {
13359                        let enumerable = object
13360                            .own_property(&key.to_string_lossy())
13361                            .map(|property| property.enumerable)
13362                            .unwrap_or(false);
13363                        (key, enumerable)
13364                    })
13365                    .collect();
13366                if let Some(length) = object.array_length() {
13367                    own.retain(|(key, _)| key.as_str() != Some("length"));
13368                    for index in 0..length {
13369                        if object.array_get(index).is_some() {
13370                            own.push((crate::value::Wtf8::new(index.to_string()), true));
13371                        }
13372                    }
13373                }
13374                // Integer-like keys come first in ascending order, then the rest in
13375                // insertion order — and the ordering is *per object*, not for the chain
13376                // as a whole: one pass over every collected key lifted a prototype's
13377                // `"4"` above the target's own `x`/`y`, which is not the order
13378                // `for…in` reports.
13379                for (key, enumerable) in Self::order_own_keys(own) {
13380                    if visited.contains(&key) {
13381                        continue;
13382                    }
13383                    visited.push(key.clone());
13384                    if enumerable {
13385                        keys.push(key);
13386                    }
13387                }
13388            }
13389        }
13390        for (index, key) in keys.into_iter().enumerate() {
13391            record.define_data(&index.to_string(), self.string_wtf8(key));
13392        }
13393        record.define_data("__index", Value::Int(0));
13394        Ok(record)
13395    }
13396
13397    /// The next key of a `for…in` record, `None` when the loop is done.
13398    ///
13399    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
13400    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
13401    /// the loop reaches it, so a handler that stops reporting a key partway through drops
13402    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
13403    /// key the handler had already withdrawn.
13404    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
13405        let Value::Object(record) = record else {
13406            return Ok(None);
13407        };
13408        let proxy = record
13409            .own_property("__proxy")
13410            .and_then(|property| property.value);
13411        loop {
13412            let index = record
13413                .own_property("__index")
13414                .and_then(|property| property.value)
13415                .map(|value| value.to_int32())
13416                .unwrap_or(0);
13417            let Some(candidate) = record
13418                .own_property(&index.to_string())
13419                .and_then(|property| property.value)
13420            else {
13421                return Ok(None);
13422            };
13423            record.define_data("__index", Value::Int(index + 1));
13424            let text = candidate.to_js_string();
13425            let Some(Value::Object(proxy)) = &proxy else {
13426                return Ok(Some(text));
13427            };
13428            // The candidate is already a key string here, so the lookup does not need a
13429            // second `ToPropertyKey` conversion.
13430            let key = PropertyKey::from(text.as_str());
13431            let live = match self.proxy_get_own_property(proxy, &key)? {
13432                Some(descriptor) => descriptor,
13433                // Not a proxy after all, or it lost its state: fall back to the target.
13434                None => proxy.own_property_key(&key),
13435            };
13436            if live.is_some_and(|property| property.enumerable) {
13437                return Ok(Some(text));
13438            }
13439            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13440            // next one.
13441        }
13442    }
13443
13444    /// The iterator for `for-of`: the object and its `next` method.
13445    ///
13446    /// An object that already carries a `next` method is used as it is — that is what
13447    /// `arr.values()` returns — and only arrays and strings get the built-in
13448    /// sequence iterator.
13449    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13450    ///
13451    /// Callers that must choose between the iterable and the array-like protocol — the
13452    /// typed-array constructor is the main one — need to ask *before* committing to one.
13453    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13454        let key = self.realm.well_known_key(WellKnown::Iterator);
13455        let method = self.read_field_key(value, &key)?;
13456        if matches!(method, Value::Undefined | Value::Null) {
13457            return Ok(false);
13458        }
13459        if !matches!(&method, Value::Object(object) if object.is_callable()) {
13460            return Err(Signal::Throw(
13461                self.make_error("TypeError", "Symbol.iterator is not callable"),
13462            ));
13463        }
13464        Ok(true)
13465    }
13466
13467    /// Collect everything an iterable yields.
13468    ///
13469    /// The cap is a guard against a generator that never ends: an unbounded collect would
13470    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13471    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13472    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13473    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13474        const MAX_ITEMS: usize = 1 << 24;
13475        let iterator = self.get_iterator(value)?;
13476        let mut out = Vec::new();
13477        loop {
13478            let (element, done) = self.iterator_step(&iterator)?;
13479            if done {
13480                return Ok(out);
13481            }
13482            out.push(element);
13483            if out.len() > MAX_ITEMS {
13484                // Close before refusing: the walk is being abandoned, so the iterator's
13485                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
13486                // unrun and a locked resource unreleased.
13487                self.close_iterator_after_throw(&iterator)?;
13488                return Err(self.range_error("iterable is too long to collect"));
13489            }
13490        }
13491    }
13492
13493    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
13494    ///
13495    /// A native constructor calls this once it has validated its arguments, which is the
13496    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
13497    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
13498    /// never reached. The prototype comes from `new.target` when it is an object, and from
13499    /// `default_proto` otherwise.
13500    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13501        let proto = self.ctor_prototype(default_proto)?;
13502        Ok(self.new_object(Some(proto)))
13503    }
13504
13505    /// An **array** whose prototype comes from `new.target`.
13506    ///
13507    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
13508    /// instance from `new.target.prototype`, and building a plain array instead made every
13509    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
13510    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
13511        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
13512        Ok(JsObject::array(self.heap, Some(proto), 0))
13513    }
13514
13515    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
13516    ///
13517    /// The `Option` form is for the constructors that build their instance in a helper which
13518    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
13519    /// from `await`'s internal promise, and only the first has a `new.target`.
13520    fn ctor_prototype_opt(
13521        &mut self,
13522        default_proto: Option<Gc<JsObject>>,
13523    ) -> JsResult<Option<Gc<JsObject>>> {
13524        let Some(target) = self.pending_new_target.clone() else {
13525            return Ok(default_proto);
13526        };
13527        let Some(target) = target.as_object().cloned() else {
13528            return Ok(default_proto);
13529        };
13530        match self.get_property(&target, "prototype")? {
13531            Some(Value::Object(proto)) => Ok(Some(proto)),
13532            _ => Ok(default_proto),
13533        }
13534    }
13535
13536    /// `new.target.prototype`, or `default_proto` when this is a plain call.
13537    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13538        let Some(target) = self.pending_new_target.clone() else {
13539            return Ok(default_proto);
13540        };
13541        let Some(target) = target.as_object().cloned() else {
13542            return Ok(default_proto);
13543        };
13544        match self.get_property(&target, "prototype")? {
13545            Some(Value::Object(proto)) => Ok(proto),
13546            _ => Ok(default_proto),
13547        }
13548    }
13549
13550    /// `CreateDataPropertyOrThrow(O, key, value)`.
13551    ///
13552    /// A *definition*, not an assignment. The difference is visible the moment the target
13553    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
13554    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
13555    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
13556    /// refused (`configurable: false`).
13557    ///
13558    /// The fast path exists because this is called once per element by `map`, `filter`,
13559    /// `slice` and friends: a plain array with no custom element descriptors and a writable
13560    /// `length` can store straight into its element vector.
13561    pub fn create_data_property_or_throw(
13562        &mut self,
13563        object: &Gc<JsObject>,
13564        index: usize,
13565        value: Value,
13566    ) -> JsResult<()> {
13567        if object.is_array()
13568            && object.elements_writable()
13569            && !object.has_element_descriptors()
13570            && object.is_extensible()
13571            && object.array_set(self.heap, index, value.clone())
13572        {
13573            return Ok(());
13574        }
13575        let key = PropertyKey::from(index.to_string());
13576        let property = Property {
13577            value: Some(value),
13578            writable: true,
13579            enumerable: true,
13580            configurable: true,
13581            ..Property::default()
13582        };
13583        // `CreateDataProperty` always asks for the default attributes, so it can only ever
13584        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13585        // the rest. Checking here rather than inside `object_define_own_property` is
13586        // deliberate: that function receives a fully-populated `Property` and cannot tell
13587        // an omitted attribute from an explicit `false`, so the generic check it would need
13588        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13589        // writable property (that cost eight `Object/defineProperty` tests).
13590        if let Some(existing) = self.object_get_own_property(object, &key)?
13591            && !existing.configurable
13592        {
13593            return Err(self.type_error("cannot create the property"));
13594        }
13595        if self.object_define_own_property(object, &key, property)? {
13596            return Ok(());
13597        }
13598        Err(self.type_error("cannot create the property"))
13599    }
13600
13601    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
13602    ///
13603    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
13604    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
13605    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
13606    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
13607    /// run user code and both can throw.
13608    pub fn species_constructor(
13609        &mut self,
13610        object: &Gc<JsObject>,
13611        default: Value,
13612    ) -> JsResult<Value> {
13613        let Some(constructor) = self.get_property(object, "constructor")? else {
13614            return Ok(default);
13615        };
13616        let constructor = match constructor {
13617            Value::Undefined => return Ok(default),
13618            Value::Object(constructor) => constructor,
13619            _ => return Err(self.type_error("constructor is not an object")),
13620        };
13621        let key = self.realm.well_known_key(WellKnown::Species);
13622        let species = self.get_property_key(&constructor, &key)?;
13623        match species {
13624            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
13625            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
13626            Some(_) => Err(self.type_error("species is not a constructor")),
13627        }
13628    }
13629
13630    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
13631    ///
13632    /// The result is an array of `length` holes whose prototype comes from
13633    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
13634    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
13635    /// is why the `IsArray` check is the first step and not an optimisation.
13636    pub fn array_species_create(
13637        &mut self,
13638        original: &Value,
13639        length: usize,
13640    ) -> JsResult<Gc<JsObject>> {
13641        let Some(object) = original.as_object().cloned() else {
13642            return Ok(self.new_array_of_length(length));
13643        };
13644        if !object.is_array() {
13645            return Ok(self.new_array_of_length(length));
13646        }
13647        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
13648        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
13649        let Some(constructor) = self.get_property(&object, "constructor")? else {
13650            return Ok(self.new_array_of_length(length));
13651        };
13652        let species = match constructor {
13653            Value::Undefined => return Ok(self.new_array_of_length(length)),
13654            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
13655                return Ok(self.new_array_of_length(length));
13656            }
13657            Value::Object(constructor) => {
13658                let key = self.realm.well_known_key(WellKnown::Species);
13659                match self.get_property_key(&constructor, &key)? {
13660                    None | Some(Value::Undefined) | Some(Value::Null) => {
13661                        return Ok(self.new_array_of_length(length));
13662                    }
13663                    Some(species) => species,
13664                }
13665            }
13666            // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
13667            // is a `TypeError`, not "the default". Treating it as the default made
13668            // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
13669            // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
13670            // `concat/create-ctor-non-object` are the same rule three times.
13671            _ => return Err(self.type_error("constructor is not an object")),
13672        };
13673        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
13674        // that is merely callable is the `create-species-non-ctor` case.
13675        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
13676            return Err(self.type_error("species is not a constructor"));
13677        }
13678        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
13679        let Some(created) = created.as_object().cloned() else {
13680            return Err(self.type_error("species constructor did not answer an object"));
13681        };
13682        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
13683        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
13684        // object, and `create-species-with-non-writable-property` asserts exactly that.
13685        // The length is set for the array case; the generic case is the caller's
13686        // `Set(A, "length", …)`.
13687        if created.is_array() {
13688            created.array_set_length(self.heap, length);
13689        }
13690        Ok(created)
13691    }
13692
13693    /// Whether `object` is this realm's `%Array%`.
13694    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
13695        self.realm
13696            .array_constructor
13697            .as_ref()
13698            .is_some_and(|array| array.ptr_eq(object))
13699    }
13700
13701    /// A fresh `length`-hole array with the intrinsic prototype.
13702    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
13703        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
13704        array.array_set_length(self.heap, length);
13705        array
13706    }
13707
13708    /// Whether this call is a construction, i.e. `new.target` is defined.
13709    ///
13710    /// A native constructor receives `this = undefined` (it builds its own instance), so it
13711    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
13712    /// The native function currently executing, if any.
13713    pub fn current_native(&self) -> Option<Gc<JsObject>> {
13714        self.current_native.clone()
13715    }
13716
13717    /// Whether this call is a construction, i.e. `new.target` is defined.
13718    pub fn is_constructing(&self) -> bool {
13719        self.pending_new_target.is_some()
13720    }
13721
13722    /// The `TypeError` a constructor too primitive to have a wrapper raises.
13723    ///
13724    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
13725    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
13726    /// happens inside the native function, which is why the trace carries an
13727    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
13728    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
13729    /// constructor`, and an unnamed one reports the leading space of `" is not a
13730    /// constructor"` because the reference formats the empty name as it is.
13731    ///
13732    /// It is also the answer for a `new.target` that cannot be named at all — not a
13733    /// function, or a throwing `name` getter — where the reference falls back to the bare
13734    /// `not a constructor`.
13735    pub fn not_a_constructor_error(&mut self) -> Signal {
13736        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
13737        self.not_a_constructor_error_for(target)
13738    }
13739
13740    /// The same `TypeError` for an explicit target, for the callers that check
13741    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
13742    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
13743        let target = match target {
13744            Value::Object(target) if target.is_callable() => target,
13745            _ => return self.type_error("not a constructor"),
13746        };
13747        let name = match self.get_property(&target, "name") {
13748            Ok(Some(value)) => value.to_js_string(),
13749            _ => return self.type_error("not a constructor"),
13750        };
13751        self.type_error(format!("{name} is not a constructor"))
13752    }
13753
13754    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
13755    ///
13756    /// True whenever `new.target` is not the callee itself, or when it has no usable
13757    /// `prototype` — the cases where reading the property is observable at all.
13758    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
13759        match &self.pending_new_target {
13760            Some(Value::Object(target)) => !target.ptr_eq(callee),
13761            Some(_) => true,
13762            None => false,
13763        }
13764    }
13765
13766    /// The symbol key for one of the engine's own hidden slots.
13767    ///
13768    /// Cached on the realm, so every object of a kind shares one key and a slot can be
13769    /// read back by name.
13770    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
13771        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
13772            return PropertyKey::Symbol(symbol.clone());
13773        }
13774        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
13775        self.realm
13776            .internal_slots
13777            .borrow_mut()
13778            .insert(name, Value::Symbol(symbol.clone()));
13779        PropertyKey::Symbol(symbol)
13780    }
13781
13782    /// Read a hidden slot, or `None` when the object has none of that name.
13783    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
13784        let slots = self.realm.internal_slots.borrow();
13785        let Value::Symbol(symbol) = slots.get(name)? else {
13786            return None;
13787        };
13788        object
13789            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
13790            .and_then(|property| property.value)
13791    }
13792
13793    /// Define a hidden slot.
13794    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
13795        let key = self.internal_slot(name);
13796        object.define_key(&key, Property::with_attributes(value, false, false));
13797    }
13798
13799    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
13800    ///
13801    /// The method is looked up on the value (through its prototype), called with no
13802    /// arguments, and its result becomes the iterator. A generator gets here through
13803    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
13804    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
13805    ///
13806    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
13807    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
13808    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
13809    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
13810    /// does, and a user-defined iterable works without a special case.
13811    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
13812    /// `Symbol.iterator`.
13813    ///
13814    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
13815    /// iterable is legal there, and each value it produces is simply already settled by
13816    /// the time the `await` around it runs.
13817    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13818        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
13819        let method = self.read_field_key(value, &async_key)?;
13820        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
13821        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
13822        // is *present but not callable* is a TypeError — it does not mean "try the other
13823        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
13824        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
13825        // guard is there to catch.
13826        let absent = matches!(method, Value::Undefined | Value::Null);
13827        if !absent {
13828            let Value::Object(object) = &method else {
13829                return Err(Signal::Throw(
13830                    self.make_error("TypeError", "value is not iterable"),
13831                ));
13832            };
13833            if !object.is_callable() {
13834                return Err(Signal::Throw(
13835                    self.make_error("TypeError", "value is not iterable"),
13836                ));
13837            }
13838        }
13839        if absent {
13840            return self.get_iterator(value);
13841        }
13842        let iterator = self.call_value(method, value.clone(), Vec::new())?;
13843        if !matches!(iterator, Value::Object(_)) {
13844            return Err(Signal::Throw(
13845                self.make_error("TypeError", "iterator is not an object"),
13846            ));
13847        }
13848        let next = self.read_field(&iterator, "next")?;
13849        Ok(Iterator {
13850            object: iterator,
13851            next,
13852        })
13853    }
13854
13855    /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
13856    /// read — `@@iterator` is **not** consulted.
13857    ///
13858    /// The distinction is observable and test262 exercises it: a set-like object's `keys`
13859    /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
13860    /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
13861    /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
13862    /// refused it with "[object Object] is not iterable".
13863    pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
13864        if !matches!(value, Value::Object(_)) {
13865            return Err(self.type_error("iterator is not an object"));
13866        }
13867        let next = self.read_field(&value, "next")?;
13868        Ok(Iterator {
13869            object: value,
13870            next,
13871        })
13872    }
13873
13874    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13875        let key = self.realm.well_known_key(WellKnown::Iterator);
13876        let method = self.read_field_key(value, &key)?;
13877        let Value::Object(function) = &method else {
13878            return Err(Signal::Throw(self.make_error(
13879                "TypeError",
13880                &format!("{} is not iterable", value.to_js_string()),
13881            )));
13882        };
13883        if !function.is_callable() {
13884            return Err(Signal::Throw(self.make_error(
13885                "TypeError",
13886                &format!("{} is not iterable", value.to_js_string()),
13887            )));
13888        }
13889        let iterator = self.call_value(method, value.clone(), Vec::new())?;
13890        // The spec requires an object here; a primitive iterator has no `next` to call
13891        // and would fail one step later with a confusing message.
13892        if !matches!(iterator, Value::Object(_)) {
13893            return Err(Signal::Throw(
13894                self.make_error("TypeError", "iterator is not an object"),
13895            ));
13896        }
13897        let next = self.read_field(&iterator, "next")?;
13898        Ok(Iterator {
13899            object: iterator,
13900            next,
13901        })
13902    }
13903
13904    /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
13905    /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
13906    /// exception from `return` propagates normally instead of being swallowed. That is the
13907    /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
13908    /// because confusing them is exactly the bug both exist to avoid.
13909    pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
13910        let method = self.read_field(&iterator.object, "return")?;
13911        if matches!(method, Value::Undefined | Value::Null) {
13912            return Ok(());
13913        }
13914        if !matches!(&method, Value::Object(object) if object.is_callable()) {
13915            return Err(self.type_error("iterator return is not a function"));
13916        }
13917        self.call_value(method, iterator.object.clone(), Vec::new())?;
13918        Ok(())
13919    }
13920
13921    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
13922    /// cannot replace it.
13923    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
13924        let method = self.read_field(&iterator.object, "return")?;
13925        if matches!(method, Value::Undefined | Value::Null) {
13926            return Ok(());
13927        }
13928        if !matches!(&method, Value::Object(object) if object.is_callable()) {
13929            return Err(self.type_error("iterator return is not a function"));
13930        }
13931        self.call_value(method, iterator.object.clone(), Vec::new())?;
13932        Ok(())
13933    }
13934
13935    /// One step of an internal iterator: the value and whether it is exhausted.
13936    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
13937        // A real iterator (`next` is a function) answers with a result object.
13938        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
13939            let result =
13940                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
13941            let Some(result) = result.as_object().cloned() else {
13942                return Err(self.type_error("iterator result is not an object"));
13943            };
13944            let done = self
13945                .get_property(&result, "done")?
13946                .is_some_and(|value| value.to_boolean());
13947            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
13948            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
13949            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
13950            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
13951            // made an unrelated `value` getter observable after the loop was over.
13952            if done {
13953                return Ok((Value::Undefined, true));
13954            }
13955            let value = self
13956                .get_property(&result, "value")?
13957                .unwrap_or(Value::Undefined);
13958            return Ok((value, false));
13959        }
13960        // An iterator whose `next` is not callable is treated as exhausted, which is
13961        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
13962        // that are not iterable at all.
13963        Ok((Value::Undefined, true))
13964    }
13965
13966    /// `[...iterable]`: append everything the iterator yields, and answer the next
13967    /// index.
13968    ///
13969    /// This goes through the same iterator machinery `for-of` uses rather than copying
13970    /// an array's elements, because a spread source is any iterable: a string spreads
13971    /// into its characters and an array iterator spreads into its results. Handling
13972    /// only arrays made `[..."ab"]` come out empty with no error at all.
13973    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
13974        let Some(target) = array.as_object().cloned() else {
13975            return Ok(0);
13976        };
13977        let start = target.array_length().unwrap_or(0);
13978        let mut added = 0;
13979        let iterator = self.get_iterator(iterable)?;
13980        loop {
13981            let (value, done) = self.iterator_step(&iterator)?;
13982            if done {
13983                break;
13984            }
13985            target.array_set(self.heap, start + added, value);
13986            added += 1;
13987        }
13988        Ok((start + added) as i32)
13989    }
13990
13991    /// How an uncaught exception is reported.
13992    ///
13993    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
13994    /// with `ToString` — `js_std_dump_error` is three lines that end in
13995    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
13996    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
13997    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
13998    ///
13999    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14000    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14001    /// `toString`"; it does call it, but only for objects of a class it does not know how
14002    /// to walk, and never for errors, arrays or plain objects.
14003    ///
14004    /// A printer that fails must not take the reporter down with it, so that case falls
14005    /// back to the `ToString` rendering.
14006    pub fn describe_exception(&mut self, value: &Value) -> String {
14007        match crate::print::sprint(self, value) {
14008            Ok(text) => text,
14009            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14010        }
14011    }
14012
14013    /// The file name of whatever is running, innermost frame first.
14014    ///
14015    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14016    /// innermost frame's file name, without distinguishing a module body from a plain
14017    /// script. `import()` uses it as the base for a relative specifier, which is why
14018    /// `import('./x.js')` inside a script resolves next to the script and not next to the
14019    /// process's working directory.
14020    pub fn script_or_module_name(&self) -> Option<String> {
14021        self.script_or_module_name_at(0)
14022    }
14023
14024    /// [`Interp::script_or_module_name`] `level` frames further out.
14025    ///
14026    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14027    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14028    /// frame without a file name is skipped rather than counted, because a native call
14029    /// pushes no frame of its own and so cannot be a level.
14030    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14031        self.frames
14032            .iter()
14033            .rev()
14034            .filter_map(|frame| frame.code.code.filename.clone())
14035            .nth(level)
14036    }
14037
14038    /// The current call stack, formatted the way `qjs` prints `error.stack`.
14039    ///
14040    /// One `    at name (file:line:col)` line per active frame, innermost first. The
14041    /// position is the one recorded for the instruction each frame is stopped on, which
14042    /// is why the compiler builds a pc-to-position table per function: without it a
14043    /// trace could only name the function, not the line inside it.
14044    ///
14045    /// A frame whose code has no positions prints just `(file)`, matching the
14046    /// reference's output for stripped bytecode.
14047    pub fn stack_trace(&self) -> String {
14048        self.stack_trace_skipping(0)
14049    }
14050
14051    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
14052    fn stack_trace_skipping(&self, skip: usize) -> String {
14053        // One ordered list, innermost first, so `skip` counts the same thing whether the
14054        // frames it leaves out are native or bytecode. Indices rather than references: a
14055        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
14056        let depth = self.frames.len();
14057        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
14058        // A native entered while `at` bytecode frames were live was called *from* the
14059        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
14060        // entered at the current depth are therefore innermost of all.
14061        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
14062            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
14063                if *at == wanted {
14064                    order.push((true, index));
14065                }
14066            }
14067        };
14068        push_natives(&mut order, depth);
14069        for index in (0..depth).rev() {
14070            order.push((false, index));
14071            push_natives(&mut order, index);
14072        }
14073        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
14074        // barrier. Natives entered at exactly the barrier depth are the eval entry point
14075        // itself (`evalScript (native)`), and the reference leaves those out too.
14076        if let Some(barrier) = self.trace_barriers.last().copied() {
14077            order.retain(|(is_native, index)| match is_native {
14078                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
14079                false => *index >= barrier,
14080            });
14081        }
14082
14083        let mut out = String::new();
14084        for (is_native, index) in order.into_iter().skip(skip) {
14085            match is_native {
14086                true => {
14087                    out.push_str("    at ");
14088                    let (native, _) = &self.native_frames[index];
14089                    let name = native
14090                        .own_property("name")
14091                        .and_then(|property| property.value)
14092                        .map(|value| value.to_js_string())
14093                        .unwrap_or_default();
14094                    out.push_str(&name);
14095                    out.push_str(" (native)\n");
14096                }
14097                false => {
14098                    let frame = &self.frames[index];
14099                    let code = &frame.code.code;
14100                    let file = code.filename.as_deref().unwrap_or("<input>");
14101                    // The name comes from the function *object*, not from the compiled code:
14102                    // an anonymous function expression is named by the property it is stored
14103                    // in (`{valueOf: function(){}}`), which only the object knows.
14104                    let bound_name = match &frame.callee {
14105                        Value::Object(object) => {
14106                            object
14107                                .own_property("name")
14108                                .and_then(|property| match property.value {
14109                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
14110                                        Some(text.to_string_lossy().into_owned())
14111                                    }
14112                                    _ => None,
14113                                })
14114                        }
14115                        _ => None,
14116                    };
14117                    // No callee object means the body was entered by the host, so the
14118                    // name has to come from the compiled code. Two cases differ:
14119                    //
14120                    // * an *unnamed* function of any kind — the reference reads the
14121                    //   `name` property, finds it empty, and prints `<anonymous>`;
14122                    // * a *module* body, which has no `name` property at all: the
14123                    //   reference builds that function object with `js_closure2` and
14124                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
14125                    //   so a trace reaching it also prints `<anonymous>` — while a
14126                    //   *script* body prints `<eval>`, its `name`.
14127                    let unnamed = code.name.is_empty() || code.module.is_some();
14128                    out.push_str("    at ");
14129                    match bound_name.as_deref() {
14130                        Some(name) => out.push_str(name),
14131                        None if unnamed => out.push_str("<anonymous>"),
14132                        None => out.push_str(&code.name),
14133                    }
14134                    match code.position_at(frame.at as u32) {
14135                        Some((line, column)) => {
14136                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
14137                        }
14138                        None => out.push_str(&format!(" ({file})\n")),
14139                    }
14140                }
14141            }
14142        }
14143        out
14144    }
14145
14146    /// Give an anonymous function the name of the property it is stored in.
14147    ///
14148    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
14149    /// enumerable and not configurable, and a function that already has a real name
14150    /// keeps it.
14151    ///
14152    /// "Already named" means a *non-empty* name: every function object is created with
14153    /// a `name` of `""` so the property exists on all of them, and treating that empty
14154    /// string as a name left every anonymous function nameless — which is how a stack
14155    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
14156    /// `SetFunctionName`, for a name that came from source text.
14157    fn set_function_name(&mut self, function: &Value, name: &str) {
14158        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
14159    }
14160
14161    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
14162    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
14163    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
14164        let Value::Object(object) = function else {
14165            return;
14166        };
14167        // `SetFunctionName` applies to *functions* and classes only, and only when they are
14168        // anonymous. Without the callability guard, `{value: someObject}` renamed
14169        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
14170        // on the right-hand side of a property. That is how a `zipKeyed` result object
14171        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
14172        // has no `NamedEvaluation` at all.
14173        if !object.is_callable() {
14174            return;
14175        }
14176        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
14177            && !existing.wtf8().is_empty()
14178        {
14179            return;
14180        }
14181        let text = self.string_wtf8(name.clone());
14182        object.define("name", Property::name_or_length(text));
14183    }
14184
14185    // -- global declarations -----------------------------------------------
14186
14187    /// Declare a global binding, creating its reference cell.
14188    /// Declare a `var` or function global, whose home is the global object.
14189    ///
14190    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
14191    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
14192    /// such as `print`, or a redeclaration — is left alone.
14193    pub fn declare_var_global(&mut self, name: &str) {
14194        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
14195        // global object is exactly the leak `typeof my_var === "undefined"` after
14196        // `eval("var my_var=2")` rules out.
14197        if let Some(scope) = self.eval_scope.as_mut() {
14198            scope.entry(name.to_string()).or_insert(Value::Undefined);
14199            return;
14200        }
14201        // A sloppy direct eval declares into its *caller's* variable environment. Doing
14202        // this on the global object instead made `eval("var c = 1")` inside a parameter
14203        // list overwrite a global `c`, and made two calls to the same function share one
14204        // binding.
14205        if let Some(cell) = self.declare_eval_local(name) {
14206            cell.set(Value::Undefined);
14207            return;
14208        }
14209        let global = self.realm.global.clone();
14210        if global.own_property(name).is_some() {
14211            return;
14212        }
14213        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
14214        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
14215        // whole point of that trick and what lets `Object.defineProperty` reshape it
14216        // afterwards. `eval_scope` is `Some` while an eval is running.
14217        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
14218        global.define(
14219            name,
14220            Property {
14221                value: Some(Value::Undefined),
14222                writable: true,
14223                enumerable: true,
14224                configurable: from_eval,
14225                ..Property::default()
14226            },
14227        );
14228    }
14229
14230    /// Declare a *lexical* global binding, which starts in its dead zone.
14231    ///
14232    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
14233    /// global object and is created when its initialiser runs.
14234    pub fn declare_global(&mut self, name: &str, is_const: bool) {
14235        if is_const {
14236            self.realm.lexical_consts.insert(name.to_string());
14237        }
14238        if !self.realm.globals.contains_key(name) {
14239            // `Uninitialized` rather than `Undefined`: the binding exists but is not
14240            // readable until its initialiser runs, and that is what `let x` before
14241            // `x = 1` has to observe.
14242            let cell = self.new_cell(Value::Uninitialized);
14243            self.realm.globals.insert(name.to_string(), cell);
14244            self.realm.declared.push(name.to_string());
14245        }
14246    }
14247}
14248
14249/// The bytecode and environment of a function object, if it is a bytecode function.
14250///
14251/// Extracted before a call so no borrow of the object is held across it.
14252fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
14253    function.with(|data| match &data.kind {
14254        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
14255        _ => None,
14256    })
14257}
14258
14259/// A native call target, extracted before the call so no borrow is held.
14260enum NativeCall {
14261    Native(NativeFn),
14262    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
14263    /// not hold that object's `RefCell` borrow.
14264    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
14265    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
14266    Bound {
14267        target: Value,
14268        this: Value,
14269        leading: Vec<Value>,
14270    },
14271    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
14272    Revoker(crate::object::ProxyRef),
14273    /// A promise's `resolve`.
14274    PromiseResolve(Gc<JsObject>),
14275    /// A promise's `reject`.
14276    PromiseReject(Gc<JsObject>),
14277    /// The executor `NewPromiseCapability(C)` hands a user constructor.
14278    CapabilityExecutor {
14279        state: Gc<JsObject>,
14280    },
14281    /// One leg of a `then` that settles through a user capability.
14282    ThenShim {
14283        handler: Option<Value>,
14284        resolve: Value,
14285        reject: Value,
14286        fulfilled: bool,
14287    },
14288    /// One continuation of an `await`.
14289    AwaitResume {
14290        coroutine: Gc<JsObject>,
14291        promise: Gc<JsObject>,
14292        kind: ResumeKind,
14293    },
14294    /// One element of a `Promise` combinator settling.
14295    CombinatorSettle {
14296        state: Gc<JsObject>,
14297        index: usize,
14298        fulfilled: bool,
14299    },
14300    /// One of `Promise.prototype.finally`'s two shims.
14301    FinallyShim {
14302        callback: Option<Value>,
14303        fulfilled: bool,
14304        constructor: Value,
14305    },
14306    /// Settle a promise with a fixed outcome.
14307    SettlePromise {
14308        promise: Gc<JsObject>,
14309        value: Value,
14310        rejected: bool,
14311    },
14312    /// Continue an async generator after its `await` settled.
14313    GeneratorResume {
14314        generator: Gc<JsObject>,
14315        promise: Gc<JsObject>,
14316        kind: ResumeKind,
14317    },
14318    /// Read a module namespace's binding out of its cell.
14319    ModuleBinding(Gc<Cell>),
14320    /// Finish a completed async generator's `return(v)` once `v` has settled.
14321    CompletedReturn {
14322        generator: Gc<JsObject>,
14323        promise: Gc<JsObject>,
14324        rejected: bool,
14325    },
14326    /// Answer a pending async-generator method with `{value, done}`.
14327    YieldResult {
14328        generator: Gc<JsObject>,
14329        promise: Gc<JsObject>,
14330        done: bool,
14331    },
14332    /// One step of `AsyncDisposableStack.disposeAsync`.
14333    DisposeStep {
14334        remaining: Gc<JsObject>,
14335        promise: Gc<JsObject>,
14336        error: Value,
14337        rejected: bool,
14338    },
14339}
14340
14341/// What a store does when the object refuses the write.
14342#[derive(Clone, Copy, PartialEq, Eq)]
14343pub enum DeleteFailure {
14344    /// Raise a `TypeError`, which is what strict mode and every built-in does.
14345    Throw,
14346    /// Ignore the write, which is what a sloppy-mode assignment does.
14347    Ignore,
14348}
14349
14350/// Whether `object` is a `Date` instance, by the class tag it carries.
14351///
14352/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
14353/// builtins module depending on the interpreter's conversion order.
14354fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
14355    interp
14356        .internal_get(object, "_class")
14357        .is_some_and(|value| value.to_js_string() == "Date")
14358}
14359
14360/// Which type `ToPrimitive` prefers when it converts an object.
14361#[derive(Clone, Copy, PartialEq, Eq)]
14362pub enum Hint {
14363    /// The default hint, which behaves like [`Hint::Number`].
14364    Default,
14365    /// `Number(obj)` and the arithmetic operators.
14366    Number,
14367    /// `String(obj)` and `ToPropertyKey`.
14368    String,
14369}
14370
14371/// Which table a binding slot indexes, for the messages that name it.
14372#[derive(Clone, Copy)]
14373enum VarSlot {
14374    Loc,
14375    Closure,
14376}
14377
14378/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
14379fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
14380    Ok(this)
14381}
14382
14383/// An internal iterator: the sequence plus a cursor.
14384pub(crate) struct Iterator {
14385    pub(crate) object: Value,
14386    pub(crate) next: Value,
14387}
14388
14389/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
14390/// and plain `a` for a method.
14391///
14392/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
14393/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
14394/// reads `at get a (file:1:2)`.
14395/// The same prefixing, for a name that may hold an unpaired surrogate.
14396fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
14397    let prefix = match flags & 3 {
14398        1 => "get ",
14399        2 => "set ",
14400        _ => return key.clone(),
14401    };
14402    let mut units: Vec<u16> = prefix.encode_utf16().collect();
14403    units.extend_from_slice(&key.to_units());
14404    crate::value::Wtf8::from_units(&units)
14405}
14406
14407fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
14408    match flags & 3 {
14409        1 => format!("get {key}"),
14410        2 => format!("set {key}"),
14411        _ => key.to_string(),
14412    }
14413}
14414
14415/// Define a method or accessor property, per the `define_method` flag byte.
14416///
14417/// The low two bits pick value/getter/setter and bit 2 marks the property
14418/// enumerable.
14419///
14420/// A getter and a setter arrive as two separate `define_method` instructions, and the
14421/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
14422/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
14423/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
14424/// `JS_DefineProperty`, which leaves the other half alone.
14425fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
14426    let enumerable = flags & 4 != 0;
14427    let kind = flags & 3;
14428    let existing = object.own_property_key(key);
14429    let property = match kind {
14430        1 => Property {
14431            getter: Some(function),
14432            // The setter half, if this literal already defined one.
14433            setter: existing
14434                .filter(Property::is_accessor)
14435                .and_then(|p| p.setter),
14436            enumerable,
14437            configurable: true,
14438            ..Property::default()
14439        },
14440        2 => Property {
14441            getter: existing
14442                .filter(Property::is_accessor)
14443                .and_then(|p| p.getter),
14444            setter: Some(function),
14445            enumerable,
14446            configurable: true,
14447            ..Property::default()
14448        },
14449        _ => Property {
14450            value: Some(function),
14451            writable: true,
14452            enumerable,
14453            configurable: true,
14454            ..Property::default()
14455        },
14456    };
14457    object.define_key(key, property);
14458}
14459
14460// ---------------------------------------------------------------------------
14461// Operand decoding
14462// ---------------------------------------------------------------------------
14463
14464/// How `print` renders a value: the reference's `JS_PrintValue`.
14465///
14466/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
14467/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
14468/// The format is reproduced closely because the test suite compares output text:
14469///
14470/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
14471/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
14472/// * a cycle prints `[circular N]` with `N` the stack index of the object;
14473/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
14474///   end print as `<N empty item(s)>`;
14475/// * a string is quoted inside a container but raw at the top level, which is why
14476///   `print("x")` and `print(["x"])` differ.
14477pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
14478    // A string argument is printed raw: `js_print` converts it with `ToString`
14479    // instead of dumping it, and the quoting only appears inside a container.
14480    if let Value::String(text) = value {
14481        return text.to_string_lossy().into_owned();
14482    }
14483    let mut printer = Printer {
14484        interp,
14485        out: String::new(),
14486        stack: Vec::new(),
14487    };
14488    printer.value(value, 0);
14489    printer.out
14490}
14491
14492/// The internal class name an object carries, when it has one.
14493fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
14494    interp
14495        .internal_get(object, "_class")
14496        .map(|value| value.to_js_string())
14497}
14498
14499/// A string property, looked up the way `GetProperty` does: own first, then the
14500/// prototype chain. Needed because the print formatter holds the interpreter
14501/// immutably and so cannot run getters.
14502fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
14503    let mut current = Some(object.clone());
14504    // Bounded, because a prototype cycle would otherwise loop forever.
14505    for _ in 0..100 {
14506        let node = current?;
14507        if let Some(property) = node.own_property(name)
14508            && let Some(value) = property.value
14509        {
14510            return Some(value.to_js_string());
14511        }
14512        current = node.with(|data| data.proto.clone());
14513    }
14514    None
14515}
14516
14517/// The `JS_PrintValue` state: output, and the objects currently being printed.
14518struct Printer<'a, 'rt> {
14519    /// Kept for the class-name lookups that typed arrays and `Date` will need.
14520    #[allow(dead_code)]
14521    interp: &'a Interp<'rt>,
14522    out: String,
14523    stack: Vec<Gc<JsObject>>,
14524}
14525
14526impl Printer<'_, '_> {
14527    /// Depth past which a container is summarised by its class name.
14528    const MAX_DEPTH: usize = 2;
14529
14530    fn value(&mut self, value: &Value, level: usize) {
14531        match value {
14532            Value::Undefined
14533            | Value::Uninitialized
14534            | Value::Hole
14535            | Value::CatchOffset(_)
14536            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
14537            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
14538            // The printer writes a bigint the way the language spells one, so a dump is
14539            // unambiguous about which kind of number it is showing.
14540            Value::BigInt(big) => {
14541                self.out.push_str(&big.to_decimal_string());
14542                self.out.push('n');
14543            }
14544            Value::Null => self.out.push_str("null"),
14545            Value::Bool(true) => self.out.push_str("true"),
14546            Value::Bool(false) => self.out.push_str("false"),
14547            Value::Int(number) => self.out.push_str(&number.to_string()),
14548            Value::Float(number) => {
14549                self.out
14550                    .push_str(&crate::value::number_to_string_for_print(*number));
14551            }
14552            Value::String(text) => self.print_string(&text.to_string_lossy()),
14553            Value::Object(object) => self.object(object, level),
14554        }
14555    }
14556
14557    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
14558        // A cycle is reported rather than followed; the index is where the object
14559        // already sits in the print stack, which is what the reference shows.
14560        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
14561            self.out.push_str(&format!("[circular {index}]"));
14562            return;
14563        }
14564        if object.is_callable() {
14565            let name = object
14566                .own_property("name")
14567                .and_then(|property| property.value)
14568                .map(|value| value.to_js_string())
14569                .unwrap_or_default();
14570            if name.is_empty() {
14571                self.out.push_str("[Function (anonymous)]");
14572            } else {
14573                self.out.push_str(&format!("[Function {name}]"));
14574            }
14575            return;
14576        }
14577        if level >= Self::MAX_DEPTH {
14578            let class = if object.is_array() { "Array" } else { "Object" };
14579            self.out.push_str(&format!("[{class}]"));
14580            return;
14581        }
14582        // `Date` and `Error` print as themselves rather than as bags of properties:
14583        // the ISO string, and `Name: message` followed by the trace.
14584        if let Some(class) = class_of(self.interp, object) {
14585            if class == "Date" {
14586                self.date(object);
14587                return;
14588            }
14589            if class == "Error" {
14590                self.error(object);
14591                return;
14592            }
14593        }
14594        self.stack.push(object.clone());
14595        if object.is_array() {
14596            self.array(object, level);
14597        } else {
14598            self.plain_object(object, level);
14599        }
14600        self.stack.pop();
14601    }
14602
14603    /// A Date prints as its ISO string; an invalid one falls through to the plain
14604    /// object form, the way the reference falls back when `toISOString` throws.
14605    fn date(&mut self, object: &Gc<JsObject>) {
14606        let value = self
14607            .interp
14608            .internal_get(object, "_date_value")
14609            .map(|value| value.to_number());
14610        match value.and_then(crate::builtins::date::iso_string) {
14611            Some(text) => self.out.push_str(&text),
14612            None => self.plain_object(object, 0),
14613        }
14614    }
14615
14616    /// `Name: message`, then the trace with its trailing newline removed.
14617    fn error(&mut self, object: &Gc<JsObject>) {
14618        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
14619        self.out.push_str(&name);
14620        if let Some(message) = inherited(object, "message")
14621            && !message.is_empty()
14622        {
14623            self.out.push_str(": ");
14624            self.out.push_str(&message);
14625        }
14626        if let Some(stack) = inherited(object, "stack") {
14627            self.out.push('\n');
14628            self.out.push_str(stack.trim_end_matches('\n'));
14629        }
14630    }
14631
14632    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
14633        let elements = object.array_elements().unwrap_or_default();
14634        self.out.push_str("[ ");
14635        // An interior hole means the array is "sparse": the reference prints those
14636        // as `index: value` pairs and says nothing about the holes themselves, while
14637        // a hole run at the end becomes a single `<N empty items>` note.
14638        let last_present = elements
14639            .iter()
14640            .rposition(|value| !matches!(value, Value::Hole));
14641        let has_interior_hole = match last_present {
14642            Some(last) => elements[..last]
14643                .iter()
14644                .any(|value| matches!(value, Value::Hole)),
14645            None => false,
14646        };
14647        let mut first = true;
14648        if has_interior_hole {
14649            let mut index = 0;
14650            while index < elements.len() {
14651                let value = &elements[index];
14652                if matches!(value, Value::Hole) {
14653                    index += 1;
14654                    continue;
14655                }
14656                if !first {
14657                    self.out.push_str(", ");
14658                }
14659                first = false;
14660                self.out.push_str(&format!("{index}: "));
14661                self.value(value, level + 1);
14662                index += 1;
14663            }
14664        } else {
14665            for (index, value) in elements.iter().enumerate() {
14666                if matches!(value, Value::Hole) {
14667                    continue;
14668                }
14669                if !first {
14670                    self.out.push_str(", ");
14671                }
14672                first = false;
14673                let _ = index;
14674                self.value(value, level + 1);
14675            }
14676            if let Some(last) = last_present {
14677                let trailing = elements.len() - last - 1;
14678                if trailing > 0 {
14679                    if !first {
14680                        self.out.push_str(", ");
14681                    }
14682                    self.out.push_str(&format!(
14683                        "<{trailing} empty item{}>",
14684                        if trailing > 1 { "s" } else { "" }
14685                    ));
14686                }
14687            } else if !elements.is_empty() {
14688                let count = elements.len();
14689                self.out.push_str(&format!(
14690                    "<{count} empty item{}>",
14691                    if count > 1 { "s" } else { "" }
14692                ));
14693            }
14694        }
14695        self.out.push_str(" ]");
14696    }
14697
14698    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
14699        self.out.push_str("{ ");
14700        let mut first = true;
14701        for key in object.own_keys() {
14702            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
14703                continue;
14704            };
14705            if !property.enumerable {
14706                continue;
14707            }
14708            if !first {
14709                self.out.push_str(", ");
14710            }
14711            first = false;
14712            self.out
14713                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
14714                    &key.to_string_lossy(),
14715                )));
14716            self.out.push_str(": ");
14717            // An accessor has no value to dump; the reference names the half that
14718            // exists instead of calling it.
14719            if property.is_accessor() {
14720                let text = match (property.getter.is_some(), property.setter.is_some()) {
14721                    (true, true) => "[Getter/Setter]",
14722                    (false, true) => "[Setter]",
14723                    _ => "[Getter]",
14724                };
14725                self.out.push_str(text);
14726            } else {
14727                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
14728            }
14729        }
14730        self.out.push_str(" }");
14731    }
14732
14733    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
14734    fn print_string(&mut self, text: &str) {
14735        self.out.push('"');
14736        for character in text.chars() {
14737            match character {
14738                '"' => self.out.push_str("\\\""),
14739                '\\' => self.out.push_str("\\\\"),
14740                '\n' => self.out.push_str("\\n"),
14741                '\r' => self.out.push_str("\\r"),
14742                '\t' => self.out.push_str("\\t"),
14743                c if (c as u32) < 0x20 => {
14744                    self.out.push_str(&format!("\\u{:04x}", c as u32));
14745                }
14746                c => self.out.push(c),
14747            }
14748        }
14749        self.out.push('"');
14750    }
14751}
14752
14753/// How `print` renders a value.
14754///
14755/// `ToString`, except that negative zero keeps its sign — the reference's host
14756/// printer does that while `String(-0)` is `"0"`.
14757pub fn display(value: &Value) -> String {
14758    match value {
14759        Value::Float(number) => crate::value::number_to_string_for_print(*number),
14760        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
14761            "undefined".to_string()
14762        }
14763        other => other.to_js_string(),
14764    }
14765}
14766
14767// ---------------------------------------------------------------------------
14768// Numeric operators
14769// ---------------------------------------------------------------------------
14770
14771/// `a + b` keeping the `Int` representation when it fits.
14772fn add_numbers(left: Value, right: Value) -> Value {
14773    match (&left, &right) {
14774        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
14775            Some(sum) => Value::Int(sum),
14776            None => Value::Float(*a as f64 + *b as f64),
14777        },
14778        _ => Value::Float(left.to_number() + right.to_number()),
14779    }
14780}
14781
14782/// The arithmetic operators other than `+`, which needs string concatenation.
14783fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14784    use Opcode::*;
14785    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
14786    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
14787    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
14788    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
14789        return Ok(match op {
14790            And => Value::Int(x & y),
14791            Or => Value::Int(x | y),
14792            Xor => Value::Int(x ^ y),
14793            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
14794            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
14795            Shr => match (*x as u32) >> ((*y as u32) & 31) {
14796                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
14797                shifted => Value::Float(shifted as f64),
14798            },
14799            Sub => match x.checked_sub(*y) {
14800                Some(value) => Value::Int(value),
14801                None => Value::Float(*x as f64 - *y as f64),
14802            },
14803            _ => return arithmetic_slow(op, left, right),
14804        });
14805    }
14806    arithmetic_slow(op, left, right)
14807}
14808
14809/// [`arithmetic`] for everything the integer fast path above does not take.
14810fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14811    use Opcode::*;
14812    let (a, b) = (left.to_number(), right.to_number());
14813    Ok(match op {
14814        Sub => match (&left, &right) {
14815            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
14816                Some(value) => Value::Int(value),
14817                None => Value::Float(a - b),
14818            },
14819            _ => Value::Float(a - b),
14820        },
14821        Mul => Value::Float(a * b),
14822        Div => Value::Float(a / b),
14823        Mod => Value::Float(js_mod(a, b)),
14824        Pow => Value::Float(a.powf(b)),
14825        And => Value::Int(left.to_int32() & right.to_int32()),
14826        Or => Value::Int(left.to_int32() | right.to_int32()),
14827        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
14828        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
14829        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
14830        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
14831        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
14832        // fits the small-integer representation stays an `Int`; the rest become a
14833        // float, which is how the reference keeps `n >>> 0` non-negative.
14834        Shr => {
14835            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
14836            match i32::try_from(shifted) {
14837                Ok(value) => Value::Int(value),
14838                Err(_) => Value::Float(shifted as f64),
14839            }
14840        }
14841        _ => Value::Float(a),
14842    })
14843}
14844
14845/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
14846///
14847/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
14848/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
14849/// slow path where the rules live.
14850fn is_number(value: &Value) -> bool {
14851    matches!(value, Value::Int(_) | Value::Float(_))
14852}
14853
14854/// The `Value::Bool` a comparison operator answers for `ordering`.
14855///
14856/// `None` is the unordered case — a `NaN` on either side — and every operator answers
14857/// false for it, including `<=` and `>=`.
14858fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
14859    use Opcode::*;
14860    let answer = match (op, ordering) {
14861        (_, None) => false,
14862        (Lt, Some(ordering)) => ordering.is_lt(),
14863        (Lte, Some(ordering)) => ordering.is_le(),
14864        (Gt, Some(ordering)) => ordering.is_gt(),
14865        (Gte, Some(ordering)) => ordering.is_ge(),
14866        _ => false,
14867    };
14868    Value::Bool(answer)
14869}
14870
14871/// `%`, which follows the sign of the dividend rather than Rust's.
14872fn js_mod(left: f64, right: f64) -> f64 {
14873    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
14874        return f64::NAN;
14875    }
14876    if right.is_infinite() {
14877        return left;
14878    }
14879    let remainder = left % right;
14880    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
14881    // the spec makes the sign match the dividend.
14882    if remainder == 0.0 {
14883        0.0f64.copysign(left)
14884    } else {
14885        remainder
14886    }
14887}
14888
14889fn negate(value: Value) -> Value {
14890    match value {
14891        Value::Int(0) => Value::Float(-0.0),
14892        Value::Int(i) => Value::Int(-i),
14893        other => Value::Float(-other.to_number()),
14894    }
14895}
14896
14897fn increment(value: Value) -> Value {
14898    match value {
14899        Value::Int(i) => match i.checked_add(1) {
14900            Some(next) => Value::Int(next),
14901            None => Value::Float(i as f64 + 1.0),
14902        },
14903        other => Value::Float(other.to_number() + 1.0),
14904    }
14905}
14906
14907fn decrement(value: Value) -> Value {
14908    match value {
14909        Value::Int(i) => match i.checked_sub(1) {
14910            Some(next) => Value::Int(next),
14911            None => Value::Float(i as f64 - 1.0),
14912        },
14913        other => Value::Float(other.to_number() - 1.0),
14914    }
14915}
14916
14917/// Compare a `BigInt` with an `f64` on their mathematical values.
14918///
14919/// Neither side is rounded to the other's precision: the number is split into its integer
14920/// part (compared as an exact bigint) and its fraction, which is what decides the answer
14921/// when the integer parts are equal. An infinite value is larger than every bigint.
14922fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
14923    use std::cmp::Ordering;
14924    if number.is_nan() {
14925        return None;
14926    }
14927    if number.is_infinite() {
14928        return Some(if number > 0.0 {
14929            Ordering::Less
14930        } else {
14931            Ordering::Greater
14932        });
14933    }
14934    let truncated = number.trunc();
14935    // A number wider than `i128` still has an exact integer part, but no bigint form we can
14936    // build cheaply; the sign of the difference is all that is needed, so compare against
14937    // the bigint's own magnitude instead.
14938    if truncated.abs() >= 1.7e38 {
14939        let big_as_f64 = big.to_f64();
14940        return big_as_f64.partial_cmp(&number);
14941    }
14942    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
14943    match big.cmp(&integer) {
14944        Ordering::Equal => {
14945            // Same integer part: the fraction decides, and a negative number's fraction is
14946            // below the integer (`-1.5` truncates to `-1`).
14947            if number > truncated {
14948                Some(Ordering::Less)
14949            } else if number < truncated {
14950                Some(Ordering::Greater)
14951            } else {
14952                Some(Ordering::Equal)
14953            }
14954        }
14955        other => Some(other),
14956    }
14957}
14958
14959/// `CanonicalNumericIndexString(argument)` (§7.1.21).
14960///
14961/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
14962/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
14963/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
14964/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
14965/// rather than treating it as `0`.
14966fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
14967    let PropertyKey::String(text) = key else {
14968        // A symbol is never an index.
14969        return None;
14970    };
14971    let text = text.to_string_lossy();
14972    if text == "-0" {
14973        return Some(-0.0);
14974    }
14975    let number: f64 = text.parse().ok()?;
14976    // The round-trip test *is* the definition: only the canonical spelling qualifies.
14977    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
14978    // `"0.10"` does not.
14979    let rendered = Value::Float(number).to_js_string();
14980    (rendered == text).then_some(number)
14981}
14982
14983/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
14984///
14985/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
14986/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
14987/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
14988/// numeric and invalid, which is why they stop the prototype chain instead of falling
14989/// through it.
14990///
14991/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
14992/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
14993/// `in`, `delete` and `defineProperty` separately to make sure it does not.
14994fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
14995    numeric.is_finite()
14996        && numeric.fract() == 0.0
14997        && !(numeric == 0.0 && numeric.is_sign_negative())
14998        && numeric >= 0.0
14999        && object
15000            .typed_array_length()
15001            .is_some_and(|length| (numeric as usize) < length)
15002}